python-doctr 1.0.1__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 (121) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +506 -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 +2 -1
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +5 -4
  12. doctr/datasets/generator/pytorch.py +4 -5
  13. doctr/datasets/ic03.py +3 -2
  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 +123 -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 +2 -1
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +3 -2
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +14 -5
  29. doctr/datasets/vocabs.py +2 -0
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +1 -0
  33. doctr/io/elements.py +252 -260
  34. doctr/io/exporters.py +1275 -0
  35. doctr/io/image/base.py +3 -2
  36. doctr/io/image/pytorch.py +5 -3
  37. doctr/models/__init__.py +2 -0
  38. doctr/models/_utils.py +56 -8
  39. doctr/models/builder.py +532 -61
  40. doctr/models/classification/__init__.py +2 -0
  41. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  42. doctr/models/classification/mobilenet/pytorch.py +6 -6
  43. doctr/models/classification/predictor/pytorch.py +6 -2
  44. doctr/models/classification/resnet/pytorch.py +5 -5
  45. doctr/models/classification/starnet/__init__.py +1 -0
  46. doctr/models/classification/starnet/pytorch.py +202 -0
  47. doctr/models/classification/textnet/pytorch.py +6 -5
  48. doctr/models/classification/vgg/pytorch.py +3 -2
  49. doctr/models/classification/vip/layers/pytorch.py +4 -4
  50. doctr/models/classification/vip/pytorch.py +4 -4
  51. doctr/models/classification/vit/pytorch.py +3 -3
  52. doctr/models/classification/vit_det/__init__.py +1 -0
  53. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  54. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  55. doctr/models/classification/vit_det/pytorch.py +346 -0
  56. doctr/models/classification/zoo.py +3 -0
  57. doctr/models/detection/_utils/base.py +23 -7
  58. doctr/models/detection/core.py +33 -18
  59. doctr/models/detection/differentiable_binarization/base.py +6 -4
  60. doctr/models/detection/differentiable_binarization/pytorch.py +3 -3
  61. doctr/models/detection/fast/base.py +5 -1
  62. doctr/models/detection/fast/pytorch.py +3 -3
  63. doctr/models/detection/linknet/base.py +5 -1
  64. doctr/models/detection/linknet/pytorch.py +3 -3
  65. doctr/models/detection/predictor/pytorch.py +3 -2
  66. doctr/models/detection/zoo.py +2 -2
  67. doctr/models/factory/hub.py +56 -41
  68. doctr/models/kie_predictor/base.py +16 -1
  69. doctr/models/kie_predictor/pytorch.py +41 -10
  70. doctr/models/layout/__init__.py +2 -0
  71. doctr/models/layout/lw_detr/__init__.py +1 -0
  72. doctr/models/layout/lw_detr/base.py +309 -0
  73. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  74. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  75. doctr/models/layout/lw_detr/pytorch.py +838 -0
  76. doctr/models/layout/predictor/__init__.py +1 -0
  77. doctr/models/layout/predictor/pytorch.py +82 -0
  78. doctr/models/layout/zoo.py +90 -0
  79. doctr/models/modules/layers/pytorch.py +139 -3
  80. doctr/models/predictor/base.py +137 -15
  81. doctr/models/predictor/pytorch.py +150 -8
  82. doctr/models/preprocessor/pytorch.py +77 -22
  83. doctr/models/reading_order/__init__.py +1 -0
  84. doctr/models/reading_order/base.py +667 -0
  85. doctr/models/recognition/crnn/pytorch.py +5 -7
  86. doctr/models/recognition/master/pytorch.py +6 -7
  87. doctr/models/recognition/parseq/pytorch.py +4 -4
  88. doctr/models/recognition/predictor/pytorch.py +1 -1
  89. doctr/models/recognition/sar/pytorch.py +1 -1
  90. doctr/models/recognition/utils.py +8 -10
  91. doctr/models/recognition/viptr/pytorch.py +3 -5
  92. doctr/models/recognition/vitstr/pytorch.py +5 -5
  93. doctr/models/recognition/zoo.py +5 -6
  94. doctr/models/table_structure/__init__.py +2 -0
  95. doctr/models/table_structure/predictor/__init__.py +1 -0
  96. doctr/models/table_structure/predictor/pytorch.py +80 -0
  97. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  98. doctr/models/table_structure/tablecenternet/base.py +485 -0
  99. doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
  100. doctr/models/table_structure/zoo.py +82 -0
  101. doctr/models/utils/pytorch.py +314 -15
  102. doctr/models/zoo.py +90 -2
  103. doctr/transforms/modules/base.py +247 -82
  104. doctr/transforms/modules/pytorch.py +212 -73
  105. doctr/utils/common_types.py +21 -1
  106. doctr/utils/data.py +4 -2
  107. doctr/utils/fonts.py +55 -16
  108. doctr/utils/geometry.py +135 -18
  109. doctr/utils/metrics.py +350 -18
  110. doctr/utils/multithreading.py +5 -2
  111. doctr/utils/reconstitution.py +696 -132
  112. doctr/utils/visualization.py +62 -3
  113. doctr/version.py +1 -1
  114. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/METADATA +67 -27
  115. python_doctr-1.1.0.dist-info/RECORD +179 -0
  116. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
  117. python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
  118. python_doctr-1.0.1.dist-info/RECORD +0 -149
  119. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
  120. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
  121. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
@@ -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))
@@ -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])
@@ -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:
@@ -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
@@ -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:
@@ -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
@@ -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:
@@ -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(
@@ -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
 
@@ -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,15 @@ 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,
33
36
  }
34
37
 
35
38
 
@@ -37,7 +40,7 @@ def login_to_hub() -> None: # pragma: no cover
37
40
  """Login to huggingface hub"""
38
41
  access_token = get_token()
39
42
  if access_token is not None:
40
- logging.info("Huggingface Hub token found and valid")
43
+ logger.info("Huggingface Hub token found and valid")
41
44
  login(token=access_token)
42
45
  else:
43
46
  login()
@@ -96,60 +99,66 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
96
99
 
97
100
  if run_config is None and arch is None:
98
101
  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")
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")
101
104
 
102
105
  # default readme
103
- readme = textwrap.dedent(
104
- f"""
105
-
106
- language: en
106
+ readme = f"""---
107
+ language: en
108
+ tags:
109
+ - ocr
110
+ - pytorch
111
+ - doctr
112
+ - {task}
113
+ ---
107
114
 
108
115
 
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>
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>
112
119
 
113
- **Optical Character Recognition made seamless & accessible to anyone, powered by PyTorch**
120
+ **Optical Character Recognition made seamless & accessible to anyone, powered by PyTorch**
114
121
 
115
- ## Task: {task}
122
+ ## Task: {task}
116
123
 
117
- https://github.com/mindee/doctr
124
+ https://github.com/mindee/doctr
118
125
 
119
- ### Example usage:
126
+ ### Example usage:
120
127
 
121
- ```python
122
- >>> from doctr.io import DocumentFile
123
- >>> 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
124
131
 
125
- >>> img = DocumentFile.from_images(['<image_path>'])
126
- >>> # Load your model from the hub
127
- >>> 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')
128
135
 
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)
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)
134
141
 
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)
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)
139
146
 
140
- >>> # Get your predictions
141
- >>> res = predictor(img)
142
- ```
143
- """
144
- )
147
+ >>> # Get your predictions
148
+ >>> res = predictor(img)
149
+ ```
150
+ """
145
151
 
146
152
  # add run configuration to readme if available
147
153
  if run_config is not None:
148
154
  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
- )
155
+ readme += f"""
156
+ ### Run Configuration
157
+
158
+ ```json
159
+ {json.dumps(vars(run_config), indent=2, ensure_ascii=False)}
160
+ ```
161
+ """
153
162
 
154
163
  if arch not in AVAILABLE_ARCHS[task]:
155
164
  raise ValueError(
@@ -161,7 +170,8 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
161
170
 
162
171
  # Create repository
163
172
  api = HfApi()
164
- api.create_repo(model_name, token=get_token(), exist_ok=False)
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
165
175
 
166
176
  # Save model files to a temporary directory
167
177
  with tempfile.TemporaryDirectory() as tmp_dir:
@@ -172,7 +182,8 @@ def push_to_hf_hub(model: Any, model_name: str, task: str, **kwargs) -> None: #
172
182
  # Upload all files to the hub
173
183
  api.upload_folder(
174
184
  folder_path=tmp_dir,
175
- repo_id=model_name,
185
+ repo_id=full_repo_id,
186
+ repo_type="model",
176
187
  commit_message=commit_message,
177
188
  token=get_token(),
178
189
  )
@@ -208,6 +219,10 @@ def from_hub(repo_id: str, **kwargs: Any):
208
219
  model = models.detection.__dict__[arch](pretrained=False)
209
220
  elif task == "recognition":
210
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)
211
226
 
212
227
  # update model cfg
213
228
  model.cfg = cfg
@@ -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 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
@@ -12,6 +12,7 @@ from torch import nn
12
12
  from doctr.io.elements import Document
13
13
  from doctr.models._utils import get_language, invert_data_structure
14
14
  from doctr.models.detection.predictor import DetectionPredictor
15
+ from doctr.models.layout.predictor import LayoutPredictor
15
16
  from doctr.models.recognition.predictor import RecognitionPredictor
16
17
  from doctr.utils.geometry import detach_scores
17
18
 
@@ -35,6 +36,9 @@ class KIEPredictor(nn.Module, _KIEPredictor):
35
36
  page. Doing so will slightly deteriorate the overall latency.
36
37
  detect_language: if True, the language prediction will be added to the predictions for each
37
38
  page. Doing so will slightly deteriorate the overall latency.
39
+ preserve_original_coords: if True and straighten_pages is True, bounding boxes are mapped back to the
40
+ original page coordinates. Useful for redaction and annotation.
41
+ layout_predictor: optional layout detection module
38
42
  **kwargs: keyword args of `DocumentBuilder`
39
43
  """
40
44
 
@@ -48,6 +52,8 @@ class KIEPredictor(nn.Module, _KIEPredictor):
48
52
  symmetric_pad: bool = True,
49
53
  detect_orientation: bool = False,
50
54
  detect_language: bool = False,
55
+ preserve_original_coords: bool = False,
56
+ layout_predictor: LayoutPredictor | None = None,
51
57
  **kwargs: Any,
52
58
  ) -> None:
53
59
  nn.Module.__init__(self)
@@ -60,10 +66,12 @@ class KIEPredictor(nn.Module, _KIEPredictor):
60
66
  preserve_aspect_ratio,
61
67
  symmetric_pad,
62
68
  detect_orientation,
69
+ preserve_original_coords=preserve_original_coords,
63
70
  **kwargs,
64
71
  )
65
72
  self.detect_orientation = detect_orientation
66
73
  self.detect_language = detect_language
74
+ self.layout_predictor = layout_predictor.eval() if layout_predictor is not None else None
67
75
 
68
76
  @torch.inference_mode()
69
77
  def forward(
@@ -77,16 +85,25 @@ class KIEPredictor(nn.Module, _KIEPredictor):
77
85
 
78
86
  origin_page_shapes = [page.shape[:2] for page in pages]
79
87
 
80
- # Localize text elements
81
- loc_preds, out_maps = self.det_predictor(pages, return_maps=True, **kwargs)
88
+ if not self.straighten_pages:
89
+ # Detect layout regions on the pages
90
+ regions = self.layout_predictor(pages, **kwargs) if self.layout_predictor is not None else None
91
+ det_pages = self._mask_regions(pages, regions)
92
+ else:
93
+ det_pages = pages
94
+
95
+ # Localize text elements (segmentation maps are only materialized when actually consumed)
96
+ if self.detect_orientation or self.straighten_pages:
97
+ loc_preds, out_maps = self.det_predictor(det_pages, return_maps=True, **kwargs)
98
+ bin_thresh = kwargs.get("bin_thresh", getattr(self.det_predictor.model.postprocessor, "bin_thresh", 0.3))
99
+ seg_maps = [
100
+ ((np.expand_dims(np.amax(out_map, axis=-1), axis=-1) > bin_thresh).astype(np.uint8) * 255)
101
+ for out_map in out_maps
102
+ ]
103
+ else:
104
+ loc_preds = self.det_predictor(det_pages, **kwargs)
82
105
 
83
106
  # Detect document rotation and rotate pages
84
- seg_maps = [
85
- np.where(np.expand_dims(np.amax(out_map, axis=-1), axis=-1) > kwargs.get("bin_thresh", 0.3), 255, 0).astype(
86
- np.uint8
87
- )
88
- for out_map in out_maps
89
- ]
90
107
  if self.detect_orientation:
91
108
  general_pages_orientations, origin_pages_orientations = self._get_orientations(pages, seg_maps)
92
109
  orientations = [
@@ -97,12 +114,21 @@ class KIEPredictor(nn.Module, _KIEPredictor):
97
114
  general_pages_orientations = None
98
115
  origin_pages_orientations = None
99
116
  if self.straighten_pages:
100
- pages = self._straighten_pages(pages, seg_maps, general_pages_orientations, origin_pages_orientations)
117
+ _orig_shapes = origin_page_shapes
118
+ _orig_pages = list(pages)
119
+ pages, m_invs = self._straighten_pages(
120
+ pages, seg_maps, general_pages_orientations, origin_pages_orientations
121
+ )
101
122
  # update page shapes after straightening
102
123
  origin_page_shapes = [page.shape[:2] for page in pages]
124
+ _straight_shapes = origin_page_shapes
125
+
126
+ # Detect layout regions on the pages
127
+ regions = self.layout_predictor(pages, **kwargs) if self.layout_predictor is not None else None
128
+ det_pages = self._mask_regions(pages, regions)
103
129
 
104
130
  # Forward again to get predictions on straight pages
105
- loc_preds = self.det_predictor(pages, **kwargs)
131
+ loc_preds = self.det_predictor(det_pages, **kwargs)
106
132
 
107
133
  dict_loc_preds: dict[str, list[np.ndarray]] = invert_data_structure(loc_preds) # type: ignore[assignment]
108
134
 
@@ -173,7 +199,12 @@ class KIEPredictor(nn.Module, _KIEPredictor):
173
199
  crop_orientations_per_page,
174
200
  orientations,
175
201
  languages_dict,
202
+ regions,
176
203
  )
204
+
205
+ # manipulate the already built Document to restore the original pages / shapes and geometries
206
+ if self.straighten_pages and self.preserve_original_coords:
207
+ out = self._remap_to_original_coords(out, _orig_shapes, _straight_shapes, m_invs, _orig_pages) # type: ignore[assignment]
177
208
  return out
178
209
 
179
210
  @staticmethod
@@ -0,0 +1,2 @@
1
+ from .zoo import *
2
+ from .lw_detr import *
@@ -0,0 +1 @@
1
+ from .pytorch import *