python-doctr 1.0.0__py3-none-any.whl → 1.1.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 (138) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +506 -0
  3. doctr/contrib/artefacts.py +1 -1
  4. doctr/contrib/base.py +1 -1
  5. doctr/datasets/__init__.py +2 -0
  6. doctr/datasets/coco_text.py +5 -3
  7. doctr/datasets/cord.py +3 -2
  8. doctr/datasets/datasets/base.py +13 -25
  9. doctr/datasets/datasets/pytorch.py +15 -5
  10. doctr/datasets/detection.py +3 -2
  11. doctr/datasets/doc_artefacts.py +3 -2
  12. doctr/datasets/funsd.py +3 -2
  13. doctr/datasets/generator/base.py +6 -5
  14. doctr/datasets/generator/pytorch.py +5 -6
  15. doctr/datasets/ic03.py +4 -3
  16. doctr/datasets/ic13.py +5 -3
  17. doctr/datasets/iiit5k.py +3 -2
  18. doctr/datasets/iiithws.py +5 -3
  19. doctr/datasets/imgur5k.py +5 -3
  20. doctr/datasets/layout.py +123 -0
  21. doctr/datasets/mjsynth.py +5 -3
  22. doctr/datasets/ocr.py +3 -2
  23. doctr/datasets/orientation.py +3 -2
  24. doctr/datasets/recognition.py +3 -2
  25. doctr/datasets/sroie.py +3 -2
  26. doctr/datasets/svhn.py +3 -2
  27. doctr/datasets/svt.py +4 -3
  28. doctr/datasets/synthtext.py +3 -2
  29. doctr/datasets/table_structure.py +97 -0
  30. doctr/datasets/utils.py +15 -6
  31. doctr/datasets/vocabs.py +3 -1
  32. doctr/datasets/wildreceipt.py +5 -3
  33. doctr/file_utils.py +4 -2
  34. doctr/io/__init__.py +1 -0
  35. doctr/io/elements.py +253 -261
  36. doctr/io/exporters.py +1275 -0
  37. doctr/io/html.py +1 -1
  38. doctr/io/image/base.py +4 -3
  39. doctr/io/image/pytorch.py +6 -4
  40. doctr/io/pdf.py +1 -1
  41. doctr/io/reader.py +1 -1
  42. doctr/models/__init__.py +2 -0
  43. doctr/models/_utils.py +111 -25
  44. doctr/models/builder.py +533 -62
  45. doctr/models/classification/__init__.py +2 -0
  46. doctr/models/classification/magc_resnet/pytorch.py +2 -2
  47. doctr/models/classification/mobilenet/pytorch.py +7 -7
  48. doctr/models/classification/predictor/pytorch.py +7 -3
  49. doctr/models/classification/resnet/pytorch.py +6 -6
  50. doctr/models/classification/starnet/__init__.py +1 -0
  51. doctr/models/classification/starnet/pytorch.py +202 -0
  52. doctr/models/classification/textnet/pytorch.py +7 -6
  53. doctr/models/classification/vgg/pytorch.py +4 -3
  54. doctr/models/classification/vip/layers/pytorch.py +5 -5
  55. doctr/models/classification/vip/pytorch.py +5 -5
  56. doctr/models/classification/vit/pytorch.py +4 -4
  57. doctr/models/classification/vit_det/__init__.py +1 -0
  58. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  60. doctr/models/classification/vit_det/pytorch.py +346 -0
  61. doctr/models/classification/zoo.py +4 -1
  62. doctr/models/core.py +1 -1
  63. doctr/models/detection/_utils/base.py +24 -8
  64. doctr/models/detection/_utils/pytorch.py +1 -1
  65. doctr/models/detection/core.py +34 -19
  66. doctr/models/detection/differentiable_binarization/base.py +7 -5
  67. doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
  68. doctr/models/detection/fast/base.py +6 -2
  69. doctr/models/detection/fast/pytorch.py +4 -4
  70. doctr/models/detection/linknet/base.py +6 -2
  71. doctr/models/detection/linknet/pytorch.py +4 -4
  72. doctr/models/detection/predictor/pytorch.py +4 -3
  73. doctr/models/detection/zoo.py +3 -3
  74. doctr/models/factory/hub.py +72 -52
  75. doctr/models/kie_predictor/base.py +17 -2
  76. doctr/models/kie_predictor/pytorch.py +42 -11
  77. doctr/models/layout/__init__.py +2 -0
  78. doctr/models/layout/lw_detr/__init__.py +1 -0
  79. doctr/models/layout/lw_detr/base.py +309 -0
  80. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  81. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  82. doctr/models/layout/lw_detr/pytorch.py +838 -0
  83. doctr/models/layout/predictor/__init__.py +1 -0
  84. doctr/models/layout/predictor/pytorch.py +82 -0
  85. doctr/models/layout/zoo.py +90 -0
  86. doctr/models/modules/layers/pytorch.py +140 -4
  87. doctr/models/modules/transformer/pytorch.py +1 -1
  88. doctr/models/modules/vision_transformer/pytorch.py +1 -1
  89. doctr/models/predictor/base.py +138 -16
  90. doctr/models/predictor/pytorch.py +151 -9
  91. doctr/models/preprocessor/pytorch.py +78 -23
  92. doctr/models/reading_order/__init__.py +1 -0
  93. doctr/models/reading_order/base.py +667 -0
  94. doctr/models/recognition/core.py +1 -1
  95. doctr/models/recognition/crnn/pytorch.py +6 -8
  96. doctr/models/recognition/master/base.py +1 -1
  97. doctr/models/recognition/master/pytorch.py +7 -8
  98. doctr/models/recognition/parseq/base.py +1 -1
  99. doctr/models/recognition/parseq/pytorch.py +5 -5
  100. doctr/models/recognition/predictor/_utils.py +1 -1
  101. doctr/models/recognition/predictor/pytorch.py +2 -2
  102. doctr/models/recognition/sar/pytorch.py +2 -2
  103. doctr/models/recognition/utils.py +9 -11
  104. doctr/models/recognition/viptr/pytorch.py +4 -6
  105. doctr/models/recognition/vitstr/base.py +1 -1
  106. doctr/models/recognition/vitstr/pytorch.py +6 -6
  107. doctr/models/recognition/zoo.py +6 -7
  108. doctr/models/table_structure/__init__.py +2 -0
  109. doctr/models/table_structure/predictor/__init__.py +1 -0
  110. doctr/models/table_structure/predictor/pytorch.py +80 -0
  111. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  112. doctr/models/table_structure/tablecenternet/base.py +485 -0
  113. doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
  114. doctr/models/table_structure/zoo.py +82 -0
  115. doctr/models/utils/pytorch.py +316 -16
  116. doctr/models/zoo.py +91 -3
  117. doctr/transforms/functional/base.py +3 -2
  118. doctr/transforms/functional/pytorch.py +1 -1
  119. doctr/transforms/modules/base.py +248 -83
  120. doctr/transforms/modules/pytorch.py +213 -74
  121. doctr/utils/common_types.py +22 -2
  122. doctr/utils/data.py +5 -4
  123. doctr/utils/fonts.py +56 -17
  124. doctr/utils/geometry.py +136 -19
  125. doctr/utils/metrics.py +351 -19
  126. doctr/utils/multithreading.py +6 -3
  127. doctr/utils/reconstitution.py +697 -133
  128. doctr/utils/repr.py +1 -1
  129. doctr/utils/visualization.py +63 -4
  130. doctr/version.py +1 -1
  131. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
  132. python_doctr-1.1.0.dist-info/RECORD +179 -0
  133. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
  134. python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
  135. python_doctr-1.0.0.dist-info/RECORD +0 -149
  136. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
  137. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
  138. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -7,6 +7,7 @@
7
7
  import cv2
8
8
  import numpy as np
9
9
 
10
+ from doctr.utils.multithreading import multithread_exec
10
11
  from doctr.utils.repr import NestedObject
11
12
 
12
13
  __all__ = ["DetectionPostProcessor"]
@@ -52,10 +53,15 @@ class DetectionPostProcessor(NestedObject):
52
53
  return pred[ymin : ymax + 1, xmin : xmax + 1].mean()
53
54
 
54
55
  else:
55
- mask: np.ndarray = np.zeros((h, w), np.int32)
56
- cv2.fillPoly(mask, [points.astype(np.int32)], 1.0)
57
- product = pred * mask
58
- return np.sum(product) / np.count_nonzero(product)
56
+ pts: np.ndarray = points.reshape((-1, 2)).astype(np.int32)
57
+ xmin = np.clip(pts[:, 0].min(), 0, w - 1)
58
+ xmax = np.clip(pts[:, 0].max(), 0, w - 1)
59
+ ymin = np.clip(pts[:, 1].min(), 0, h - 1)
60
+ ymax = np.clip(pts[:, 1].max(), 0, h - 1)
61
+ mask: np.ndarray = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
62
+ cv2.fillPoly(mask, [pts - np.array([[xmin, ymin]], dtype=np.int32)], 1)
63
+ vals = pred[ymin : ymax + 1, xmin : xmax + 1][mask.astype(bool)]
64
+ return float(vals.mean()) if vals.size > 0 else 0.0
59
65
 
60
66
  def bitmap_to_boxes(
61
67
  self,
@@ -64,6 +70,28 @@ class DetectionPostProcessor(NestedObject):
64
70
  ) -> np.ndarray:
65
71
  raise NotImplementedError
66
72
 
73
+ def _process_sample(self, proba_map: np.ndarray) -> list[np.ndarray]:
74
+ """Performs postprocessing for a single sample
75
+
76
+ Args:
77
+ proba_map: probability map of shape (H, W, C)
78
+
79
+ Returns:
80
+ list of C class predictions, each of shape (*, 5) or (*, 6)
81
+ """
82
+ return [
83
+ self.bitmap_to_boxes(
84
+ proba_map[..., idx],
85
+ # Erosion + dilation on the binary map
86
+ cv2.morphologyEx(
87
+ (proba_map[..., idx] >= self.bin_thresh).astype(np.uint8),
88
+ cv2.MORPH_OPEN,
89
+ self._opening_kernel,
90
+ ),
91
+ )
92
+ for idx in range(proba_map.shape[-1])
93
+ ]
94
+
67
95
  def __call__(
68
96
  self,
69
97
  proba_map,
@@ -79,17 +107,4 @@ class DetectionPostProcessor(NestedObject):
79
107
  """
80
108
  if proba_map.ndim != 4:
81
109
  raise AssertionError(f"arg `proba_map` is expected to be 4-dimensional, got {proba_map.ndim}.")
82
-
83
- # Erosion + dilation on the binary map
84
- bin_map = [
85
- [
86
- cv2.morphologyEx(bmap[..., idx], cv2.MORPH_OPEN, self._opening_kernel)
87
- for idx in range(proba_map.shape[-1])
88
- ]
89
- for bmap in (proba_map >= self.bin_thresh).astype(np.uint8)
90
- ]
91
-
92
- return [
93
- [self.bitmap_to_boxes(pmaps[..., idx], bmaps[idx]) for idx in range(proba_map.shape[-1])]
94
- for pmaps, bmaps in zip(proba_map, bin_map)
95
- ]
110
+ return list(multithread_exec(self._process_sample, proba_map))
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -11,6 +11,8 @@ import numpy as np
11
11
  import pyclipper
12
12
  from shapely.geometry import Polygon
13
13
 
14
+ from doctr.utils import order_points
15
+
14
16
  from ..core import DetectionPostProcessor
15
17
 
16
18
  __all__ = ["DBPostProcessor"]
@@ -80,7 +82,7 @@ class DBPostProcessor(DetectionPostProcessor):
80
82
  return (
81
83
  cv2.boundingRect(expanded_points) # type: ignore[return-value]
82
84
  if self.assume_straight_pages
83
- else np.roll(cv2.boxPoints(cv2.minAreaRect(expanded_points)), -1, axis=0)
85
+ else order_points(cv2.boxPoints(cv2.minAreaRect(expanded_points)))
84
86
  )
85
87
 
86
88
  def bitmap_to_boxes(
@@ -129,7 +131,7 @@ class DBPostProcessor(DetectionPostProcessor):
129
131
  if self.assume_straight_pages:
130
132
  if _box is None or _box[2] < min_size_box or _box[3] < min_size_box:
131
133
  continue
132
- elif np.linalg.norm(_box[2, :] - _box[0, :], axis=-1) < min_size_box:
134
+ elif _box is None or np.linalg.norm(_box[2, :] - _box[0, :], axis=-1) < min_size_box:
133
135
  continue
134
136
 
135
137
  if self.assume_straight_pages:
@@ -139,7 +141,7 @@ class DBPostProcessor(DetectionPostProcessor):
139
141
  boxes.append([xmin, ymin, xmax, ymax, score])
140
142
  else:
141
143
  # compute relative box to get rid of img shape, in that case _box is a 4pt polygon
142
- if not isinstance(_box, np.ndarray) and _box.shape == (4, 2):
144
+ if not (isinstance(_box, np.ndarray) and _box.shape == (4, 2)):
143
145
  raise AssertionError("When assume straight pages is false a box is a (4, 2) array (polygon)")
144
146
  _box[:, 0] /= width
145
147
  _box[:, 1] /= height
@@ -241,7 +243,7 @@ class _DBNet:
241
243
  ys: np.ndarray = np.broadcast_to(np.linspace(0, height - 1, num=height).reshape(height, 1), (height, width))
242
244
 
243
245
  # Compute distance map to fill the padded polygon
244
- distance_map = np.zeros((polygon.shape[0], height, width), dtype=polygon.dtype)
246
+ distance_map = np.zeros((polygon.shape[0], height, width), dtype=np.float32)
245
247
  for i in range(polygon.shape[0]):
246
248
  j = (i + 1) % polygon.shape[0]
247
249
  absolute_distance = self.compute_distance(xs, ys, polygon[i], polygon[j])
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -353,7 +353,7 @@ def db_resnet34(pretrained: bool = False, **kwargs: Any) -> DBNet:
353
353
  >>> out = model(input_tensor)
354
354
 
355
355
  Args:
356
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
356
+ pretrained: If True, returns a model pre-trained on our text detection dataset
357
357
  **kwargs: keyword arguments of the DBNet architecture
358
358
 
359
359
  Returns:
@@ -386,7 +386,7 @@ def db_resnet50(pretrained: bool = False, **kwargs: Any) -> DBNet:
386
386
  >>> out = model(input_tensor)
387
387
 
388
388
  Args:
389
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
389
+ pretrained: If True, returns a model pre-trained on our text detection dataset
390
390
  **kwargs: keyword arguments of the DBNet architecture
391
391
 
392
392
  Returns:
@@ -419,7 +419,7 @@ def db_mobilenet_v3_large(pretrained: bool = False, **kwargs: Any) -> DBNet:
419
419
  >>> out = model(input_tensor)
420
420
 
421
421
  Args:
422
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
422
+ pretrained: If True, returns a model pre-trained on our text detection dataset
423
423
  **kwargs: keyword arguments of the DBNet architecture
424
424
 
425
425
  Returns:
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -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(
@@ -122,6 +123,9 @@ class FASTPostProcessor(DetectionPostProcessor):
122
123
  else:
123
124
  _box = self.polygon_to_box(np.squeeze(contour))
124
125
 
126
+ if _box is None: # pragma: no cover
127
+ continue
128
+
125
129
  if self.assume_straight_pages:
126
130
  # compute relative polygon to get rid of img shape
127
131
  x, y, w, h = _box
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -374,7 +374,7 @@ def fast_tiny(pretrained: bool = False, **kwargs: Any) -> FAST:
374
374
  >>> out = model(input_tensor)
375
375
 
376
376
  Args:
377
- 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
378
378
  **kwargs: keyword arguments of the DBNet architecture
379
379
 
380
380
  Returns:
@@ -401,7 +401,7 @@ def fast_small(pretrained: bool = False, **kwargs: Any) -> FAST:
401
401
  >>> out = model(input_tensor)
402
402
 
403
403
  Args:
404
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
404
+ pretrained: If True, returns a model pre-trained on our text detection dataset
405
405
  **kwargs: keyword arguments of the DBNet architecture
406
406
 
407
407
  Returns:
@@ -428,7 +428,7 @@ def fast_base(pretrained: bool = False, **kwargs: Any) -> FAST:
428
428
  >>> out = model(input_tensor)
429
429
 
430
430
  Args:
431
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
431
+ pretrained: If True, returns a model pre-trained on our text detection dataset
432
432
  **kwargs: keyword arguments of the DBNet architecture
433
433
 
434
434
  Returns:
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -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(
@@ -122,6 +123,9 @@ class LinkNetPostProcessor(DetectionPostProcessor):
122
123
  else:
123
124
  _box = self.polygon_to_box(np.squeeze(contour))
124
125
 
126
+ if _box is None: # pragma: no cover
127
+ continue
128
+
125
129
  if self.assume_straight_pages:
126
130
  # compute relative polygon to get rid of img shape
127
131
  x, y, w, h = _box
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -307,7 +307,7 @@ def linknet_resnet18(pretrained: bool = False, **kwargs: Any) -> LinkNet:
307
307
  >>> out = model(input_tensor)
308
308
 
309
309
  Args:
310
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
310
+ pretrained: If True, returns a model pre-trained on our text detection dataset
311
311
  **kwargs: keyword arguments of the LinkNet architecture
312
312
 
313
313
  Returns:
@@ -337,7 +337,7 @@ def linknet_resnet34(pretrained: bool = False, **kwargs: Any) -> LinkNet:
337
337
  >>> out = model(input_tensor)
338
338
 
339
339
  Args:
340
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
340
+ pretrained: If True, returns a model pre-trained on our text detection dataset
341
341
  **kwargs: keyword arguments of the LinkNet architecture
342
342
 
343
343
  Returns:
@@ -367,7 +367,7 @@ def linknet_resnet50(pretrained: bool = False, **kwargs: Any) -> LinkNet:
367
367
  >>> out = model(input_tensor)
368
368
 
369
369
  Args:
370
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
370
+ pretrained: If True, returns a model pre-trained on our text detection dataset
371
371
  **kwargs: keyword arguments of the LinkNet architecture
372
372
 
373
373
  Returns:
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -51,11 +51,12 @@ class DetectionPredictor(nn.Module):
51
51
 
52
52
  processed_batches = self.pre_processor(pages)
53
53
  _params = next(self.model.parameters())
54
- self.model, processed_batches = set_device_and_dtype(
54
+ self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
55
55
  self.model, processed_batches, _params.device, _params.dtype
56
56
  )
57
57
  predicted_batches = [
58
- self.model(batch, return_preds=True, return_model_output=True, **kwargs) for batch in processed_batches
58
+ self.model(batch, return_preds=True, return_model_output=return_maps, **kwargs)
59
+ for batch in processed_batches
59
60
  ]
60
61
  # Remove padding from loc predictions
61
62
  preds = _remove_padding(
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -50,8 +50,8 @@ 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
 
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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.
@@ -7,18 +7,15 @@
7
7
 
8
8
  import json
9
9
  import logging
10
- import os
11
10
  import subprocess
12
- import textwrap
11
+ import tempfile
13
12
  from pathlib import Path
14
13
  from typing import Any
15
14
 
16
15
  import torch
17
16
  from huggingface_hub import (
18
17
  HfApi,
19
- Repository,
20
18
  get_token,
21
- get_token_permission,
22
19
  hf_hub_download,
23
20
  login,
24
21
  )
@@ -27,20 +24,24 @@ from doctr import models
27
24
 
28
25
  __all__ = ["login_to_hub", "push_to_hf_hub", "from_hub", "_save_model_and_config_for_hf_hub"]
29
26
 
27
+ logger = logging.getLogger(__name__)
28
+
30
29
 
31
30
  AVAILABLE_ARCHS = {
32
31
  "classification": models.classification.zoo.ARCHS + models.classification.zoo.ORIENTATION_ARCHS,
33
32
  "detection": models.detection.zoo.ARCHS,
34
33
  "recognition": models.recognition.zoo.ARCHS,
34
+ "layout": models.layout.zoo.ARCHS,
35
+ "table_structure": models.table_structure.zoo.ARCHS,
35
36
  }
36
37
 
37
38
 
38
39
  def login_to_hub() -> None: # pragma: no cover
39
40
  """Login to huggingface hub"""
40
41
  access_token = get_token()
41
- if access_token is not None and get_token_permission(access_token):
42
- logging.info("Huggingface Hub token found and valid")
43
- login(token=access_token, write_permission=True)
42
+ if access_token is not None:
43
+ logger.info("Huggingface Hub token found and valid")
44
+ login(token=access_token)
44
45
  else:
45
46
  login()
46
47
  # check if git lfs is installed
@@ -98,60 +99,66 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
98
99
 
99
100
  if run_config is None and arch is None:
100
101
  raise ValueError("run_config or arch must be specified")
101
- if task not in ["classification", "detection", "recognition"]:
102
- raise ValueError("task must be one of classification, detection, recognition")
102
+ if task not in ["classification", "detection", "recognition", "layout", "table_structure"]:
103
+ raise ValueError("task must be one of classification, detection, recognition, layout, table_structure")
103
104
 
104
105
  # default readme
105
- readme = textwrap.dedent(
106
- f"""
107
-
108
- language: en
106
+ readme = f"""---
107
+ language: en
108
+ tags:
109
+ - ocr
110
+ - pytorch
111
+ - doctr
112
+ - {task}
113
+ ---
109
114
 
110
115
 
111
- <p align="center">
112
- <img src="https://doctr-static.mindee.com/models?id=v0.3.1/Logo_doctr.gif&src=0" width="60%">
113
- </p>
116
+ <p align="center">
117
+ <img src="https://doctr-static.mindee.com/models?id=v0.3.1/Logo_doctr.gif&src=0" width="60%">
118
+ </p>
114
119
 
115
- **Optical Character Recognition made seamless & accessible to anyone, powered by PyTorch**
120
+ **Optical Character Recognition made seamless & accessible to anyone, powered by PyTorch**
116
121
 
117
- ## Task: {task}
122
+ ## Task: {task}
118
123
 
119
- https://github.com/mindee/doctr
124
+ https://github.com/mindee/doctr
120
125
 
121
- ### Example usage:
126
+ ### Example usage:
122
127
 
123
- ```python
124
- >>> from doctr.io import DocumentFile
125
- >>> from doctr.models import ocr_predictor, from_hub
128
+ ```python
129
+ >>> from doctr.io import DocumentFile
130
+ >>> from doctr.models import ocr_predictor, from_hub
126
131
 
127
- >>> img = DocumentFile.from_images(['<image_path>'])
128
- >>> # Load your model from the hub
129
- >>> model = from_hub('mindee/my-model')
132
+ >>> img = DocumentFile.from_images(['<image_path>'])
133
+ >>> # Load your model from the hub
134
+ >>> model = from_hub('mindee/my-model')
130
135
 
131
- >>> # Pass it to the predictor
132
- >>> # If your model is a recognition model:
133
- >>> predictor = ocr_predictor(det_arch='db_mobilenet_v3_large',
134
- >>> reco_arch=model,
135
- >>> pretrained=True)
136
+ >>> # Pass it to the predictor
137
+ >>> # If your model is a recognition model:
138
+ >>> predictor = ocr_predictor(det_arch='db_mobilenet_v3_large',
139
+ >>> reco_arch=model,
140
+ >>> pretrained=True)
136
141
 
137
- >>> # If your model is a detection model:
138
- >>> predictor = ocr_predictor(det_arch=model,
139
- >>> reco_arch='crnn_mobilenet_v3_small',
140
- >>> pretrained=True)
142
+ >>> # If your model is a detection model:
143
+ >>> predictor = ocr_predictor(det_arch=model,
144
+ >>> reco_arch='crnn_mobilenet_v3_small',
145
+ >>> pretrained=True)
141
146
 
142
- >>> # Get your predictions
143
- >>> res = predictor(img)
144
- ```
145
- """
146
- )
147
+ >>> # Get your predictions
148
+ >>> res = predictor(img)
149
+ ```
150
+ """
147
151
 
148
152
  # add run configuration to readme if available
149
153
  if run_config is not None:
150
154
  arch = run_config.arch
151
- readme += textwrap.dedent(
152
- f"""### Run Configuration
153
- \n{json.dumps(vars(run_config), indent=2, ensure_ascii=False)}"""
154
- )
155
+ readme += f"""
156
+ ### Run Configuration
157
+
158
+ ```json
159
+ {json.dumps(vars(run_config), indent=2, ensure_ascii=False)}
160
+ ```
161
+ """
155
162
 
156
163
  if arch not in AVAILABLE_ARCHS[task]:
157
164
  raise ValueError(
@@ -161,16 +168,25 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
161
168
 
162
169
  commit_message = f"Add {model_name} model"
163
170
 
164
- local_cache_dir = os.path.join(os.path.expanduser("~"), ".cache", "huggingface", "hub", model_name)
165
- repo_url = HfApi().create_repo(model_name, token=get_token(), exist_ok=False)
166
- repo = Repository(local_dir=local_cache_dir, clone_from=repo_url)
171
+ # Create repository
172
+ api = HfApi()
173
+ repo_url = api.create_repo(model_name, token=get_token(), repo_type="model", exist_ok=False)
174
+ full_repo_id = repo_url.repo_id
167
175
 
168
- with repo.commit(commit_message):
169
- _save_model_and_config_for_hf_hub(model, repo.local_dir, arch=arch, task=task)
170
- readme_path = Path(repo.local_dir) / "README.md"
176
+ # Save model files to a temporary directory
177
+ with tempfile.TemporaryDirectory() as tmp_dir:
178
+ _save_model_and_config_for_hf_hub(model, tmp_dir, arch=arch, task=task)
179
+ readme_path = Path(tmp_dir) / "README.md"
171
180
  readme_path.write_text(readme)
172
181
 
173
- repo.git_push()
182
+ # Upload all files to the hub
183
+ api.upload_folder(
184
+ folder_path=tmp_dir,
185
+ repo_id=full_repo_id,
186
+ repo_type="model",
187
+ commit_message=commit_message,
188
+ token=get_token(),
189
+ )
174
190
 
175
191
 
176
192
  def from_hub(repo_id: str, **kwargs: Any):
@@ -203,6 +219,10 @@ def from_hub(repo_id: str, **kwargs: Any):
203
219
  model = models.detection.__dict__[arch](pretrained=False)
204
220
  elif task == "recognition":
205
221
  model = models.recognition.__dict__[arch](pretrained=False, input_shape=cfg["input_shape"], vocab=cfg["vocab"])
222
+ elif task == "layout":
223
+ model = models.layout.__dict__[arch](pretrained=False, class_names=cfg["class_names"])
224
+ elif task == "table_structure":
225
+ model = models.table_structure.__dict__[arch](pretrained=False)
206
226
 
207
227
  # update model cfg
208
228
  model.cfg = cfg
@@ -1,8 +1,9 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
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 Collection
6
7
  from typing import Any
7
8
 
8
9
  from doctr.models.builder import KIEDocumentBuilder
@@ -26,6 +27,11 @@ class _KIEPredictor(_OCRPredictor):
26
27
  symmetric_pad: if True and preserve_aspect_ratio is True, pas the image symmetrically.
27
28
  detect_orientation: if True, the estimated general page orientation will be added to the predictions for each
28
29
  page. Doing so will slightly deteriorate the overall latency.
30
+ ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
31
+ layout model will be used to locate the regions of the specified classes, and these regions will
32
+ be masked out (filled with black) before passing the pages to the detection/recognition modules.
33
+ preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
34
+ original page coordinates. Useful for redaction and annotation.
29
35
  kwargs: keyword args of `DocumentBuilder`
30
36
  """
31
37
 
@@ -39,10 +45,19 @@ class _KIEPredictor(_OCRPredictor):
39
45
  preserve_aspect_ratio: bool = True,
40
46
  symmetric_pad: bool = True,
41
47
  detect_orientation: bool = False,
48
+ ignore_regions: Collection[str] | None = None,
49
+ preserve_original_coords: bool = False,
42
50
  **kwargs: Any,
43
51
  ) -> None:
44
52
  super().__init__(
45
- assume_straight_pages, straighten_pages, preserve_aspect_ratio, symmetric_pad, detect_orientation, **kwargs
53
+ assume_straight_pages,
54
+ straighten_pages,
55
+ preserve_aspect_ratio,
56
+ symmetric_pad,
57
+ detect_orientation,
58
+ ignore_regions,
59
+ preserve_original_coords=preserve_original_coords,
60
+ **kwargs,
46
61
  )
47
62
 
48
63
  # Remove the following arguments from kwargs after initialization of the parent class