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
doctr/io/html.py CHANGED
@@ -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.
doctr/io/image/base.py CHANGED
@@ -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.
@@ -34,9 +34,10 @@ def read_img_as_numpy(
34
34
  if isinstance(file, (str, Path)):
35
35
  if not Path(file).is_file():
36
36
  raise FileNotFoundError(f"unable to access {file}")
37
- img = cv2.imread(str(file), cv2.IMREAD_COLOR)
37
+ _file: np.ndarray = np.frombuffer(Path(file).read_bytes(), np.uint8)
38
+ img = cv2.imdecode(_file, cv2.IMREAD_COLOR)
38
39
  elif isinstance(file, bytes):
39
- _file: np.ndarray = np.frombuffer(file, np.uint8)
40
+ _file = np.frombuffer(file, np.uint8)
40
41
  img = cv2.imdecode(_file, cv2.IMREAD_COLOR)
41
42
  else:
42
43
  raise TypeError("unsupported object type for argument 'file'")
doctr/io/image/pytorch.py CHANGED
@@ -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,7 +7,7 @@ from io import BytesIO
7
7
 
8
8
  import numpy as np
9
9
  import torch
10
- from PIL import Image
10
+ from PIL import Image, ImageOps
11
11
  from torchvision.transforms.functional import to_tensor
12
12
 
13
13
  from doctr.utils.common_types import AbstractPath
@@ -47,7 +47,9 @@ def read_img_as_tensor(img_path: AbstractPath, dtype: torch.dtype = torch.float3
47
47
  raise ValueError("insupported value for dtype")
48
48
 
49
49
  with Image.open(img_path, mode="r") as pil_img:
50
- return tensor_from_pil(pil_img.convert("RGB"), dtype)
50
+ # Apply the EXIF orientation before decoding, to stay consistent with `read_img_as_numpy`
51
+ # (OpenCV applies EXIF orientation automatically, PIL does not)
52
+ return tensor_from_pil(ImageOps.exif_transpose(pil_img).convert("RGB"), dtype)
51
53
 
52
54
 
53
55
  def decode_img_as_tensor(img_content: bytes, dtype: torch.dtype = torch.float32) -> torch.Tensor:
@@ -64,7 +66,7 @@ def decode_img_as_tensor(img_content: bytes, dtype: torch.dtype = torch.float32)
64
66
  raise ValueError("insupported value for dtype")
65
67
 
66
68
  with Image.open(BytesIO(img_content), mode="r") as pil_img:
67
- return tensor_from_pil(pil_img.convert("RGB"), dtype)
69
+ return tensor_from_pil(ImageOps.exif_transpose(pil_img).convert("RGB"), dtype)
68
70
 
69
71
 
70
72
  def tensor_from_numpy(npy_img: np.ndarray, dtype: torch.dtype = torch.float32) -> torch.Tensor:
doctr/io/pdf.py CHANGED
@@ -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.
doctr/io/reader.py CHANGED
@@ -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.
doctr/models/__init__.py CHANGED
@@ -1,5 +1,7 @@
1
1
  from .classification import *
2
2
  from .detection import *
3
3
  from .recognition import *
4
+ from .layout import *
5
+ from .table_structure import *
4
6
  from .zoo import *
5
7
  from .factory import *
doctr/models/_utils.py CHANGED
@@ -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
+ import heapq
6
7
  from math import floor
7
8
  from statistics import median_low
8
9
  from typing import Any
@@ -13,7 +14,14 @@ from langdetect import LangDetectException, detect_langs
13
14
 
14
15
  from doctr.utils.geometry import rotate_image
15
16
 
16
- __all__ = ["estimate_orientation", "get_language", "invert_data_structure"]
17
+ __all__ = [
18
+ "estimate_orientation",
19
+ "get_language",
20
+ "invert_data_structure",
21
+ "mask_boxes",
22
+ "rectify_crops",
23
+ "rectify_loc_preds",
24
+ ]
17
25
 
18
26
 
19
27
  def get_max_width_length_ratio(contour: np.ndarray) -> float:
@@ -26,6 +34,8 @@ def get_max_width_length_ratio(contour: np.ndarray) -> float:
26
34
  the maximum shape ratio
27
35
  """
28
36
  _, (w, h), _ = cv2.minAreaRect(contour)
37
+ if w == 0 or h == 0:
38
+ return 0.0
29
39
  return max(w / h, h / w)
30
40
 
31
41
 
@@ -53,20 +63,23 @@ def estimate_orientation(
53
63
  the estimated angle of the page (clockwise, negative for left side rotation, positive for right side rotation)
54
64
  """
55
65
  assert len(img.shape) == 3 and img.shape[-1] in [1, 3], f"Image shape {img.shape} not supported"
56
- thresh = None
66
+
57
67
  # Convert image to grayscale if necessary
58
68
  if img.shape[-1] == 3:
59
- gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
69
+ gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
60
70
  gray_img = cv2.medianBlur(gray_img, 5)
61
71
  thresh = cv2.threshold(gray_img, thresh=0, maxval=255, type=cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
62
72
  else:
63
73
  thresh = img.astype(np.uint8)
64
74
 
65
- page_orientation, orientation_confidence = general_page_orientation or (None, 0.0)
66
- if page_orientation is not None and orientation_confidence >= min_confidence:
75
+ page_orientation, orientation_confidence = general_page_orientation or (0, 0.0)
76
+ is_confident = page_orientation is not None and orientation_confidence >= min_confidence
77
+ base_angle = page_orientation if is_confident else 0
78
+
79
+ if is_confident:
67
80
  # We rotate the image to the general orientation which improves the detection
68
81
  # No expand needed bitmap is already padded
69
- thresh = rotate_image(thresh, -page_orientation)
82
+ thresh = rotate_image(thresh, -base_angle)
70
83
  else: # That's only required if we do not work on the detection models bin map
71
84
  # try to merge words in lines
72
85
  (h, w) = img.shape[:2]
@@ -78,40 +91,73 @@ def estimate_orientation(
78
91
  # extract contours
79
92
  contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
80
93
 
81
- # Filter & Sort contours
82
- contours = sorted(
83
- [contour for contour in contours if cv2.contourArea(contour) > lower_area],
94
+ # Filter contours & keep the n_ct most elongated ones
95
+ contours = heapq.nlargest(
96
+ n_ct,
97
+ (contour for contour in contours if cv2.contourArea(contour) > lower_area),
84
98
  key=get_max_width_length_ratio,
85
- reverse=True,
86
99
  )
87
100
 
88
101
  angles = []
89
- for contour in contours[:n_ct]:
102
+ for contour in contours:
90
103
  _, (w, h), angle = cv2.minAreaRect(contour)
91
- if w / h > ratio_threshold_for_lines: # select only contours with ratio like lines
92
- angles.append(angle)
93
- elif w / h < 1 / ratio_threshold_for_lines: # if lines are vertical, substract 90 degree
94
- angles.append(angle - 90)
104
+
105
+ # OpenCV version-proof normalization: force 'w' to be the long side
106
+ # so the angle is consistently relative to the major axis.
107
+ # https://github.com/opencv/opencv/pull/28051/changes
108
+ if w < h:
109
+ w, h = h, w
110
+ angle -= 90
111
+
112
+ # Normalize angle to be within [-90, 90]
113
+ while angle <= -90:
114
+ angle += 180
115
+ while angle > 90:
116
+ angle -= 180
117
+
118
+ if h > 0:
119
+ if w / h > ratio_threshold_for_lines: # select only contours with ratio like lines
120
+ angles.append(angle)
121
+ elif w / h < 1 / ratio_threshold_for_lines: # if lines are vertical, substract 90 degree
122
+ angles.append(angle - 90)
95
123
 
96
124
  if len(angles) == 0:
97
- estimated_angle = 0 # in case no angles is found
125
+ skew_angle = 0 # in case no angles is found
98
126
  else:
127
+ # median_low picks a value from the data to avoid outliers
99
128
  median = -median_low(angles)
100
- estimated_angle = -round(median) if abs(median) != 0 else 0
129
+ skew_angle = -round(median) if abs(median) != 0 else 0
130
+
131
+ # Resolve the 90-degree flip ambiguity.
132
+ # If the estimation is exactly 90/-90, it's usually a vertical detection of horizontal lines.
133
+ if abs(skew_angle) == 90:
134
+ skew_angle = 0
101
135
 
102
136
  # combine with the general orientation and the estimated angle
103
- if page_orientation is not None and orientation_confidence >= min_confidence:
137
+ # Apply the detected skew to our base orientation
138
+ final_angle = base_angle + skew_angle
139
+
140
+ # Standardize result to [-179, 180] range to handle wrap-around cases (e.g., 180 + -31)
141
+ while final_angle > 180:
142
+ final_angle -= 360
143
+ while final_angle <= -180:
144
+ final_angle += 360
145
+
146
+ if is_confident:
147
+ # If the estimated angle is perpendicular, treat it as 0 to avoid wrong flips
148
+ if abs(skew_angle) % 90 == 0:
149
+ return page_orientation
150
+
104
151
  # special case where the estimated angle is mostly wrong:
105
152
  # case 1: - and + swapped
106
153
  # case 2: estimated angle is completely wrong
107
154
  # so in this case we prefer the general page orientation
108
- if abs(estimated_angle) == abs(page_orientation):
155
+ if abs(skew_angle) == abs(page_orientation) and page_orientation != 0:
109
156
  return page_orientation
110
- estimated_angle = estimated_angle if page_orientation == 0 else page_orientation + estimated_angle
111
- if estimated_angle > 180:
112
- estimated_angle -= 360
113
157
 
114
- return estimated_angle # return the clockwise angle (negative - left side rotation, positive - right side rotation)
158
+ return int(
159
+ final_angle
160
+ ) # return the clockwise angle (negative - left side rotation, positive - right side rotation)
115
161
 
116
162
 
117
163
  def rectify_crops(
@@ -172,6 +218,46 @@ def get_language(text: str) -> tuple[str, float]:
172
218
  return lang.lang, lang.prob
173
219
 
174
220
 
221
+ def mask_boxes(img: np.ndarray, boxes: np.ndarray, fill_value: int = 255) -> np.ndarray:
222
+ """Blank out regions of an image by filling the given boxes with a constant value.
223
+
224
+ Handles both box formats produced by the models: straight boxes of shape `(N, 4)` in
225
+ `(x_min, y_min, x_max, y_max)` form and rotated 4-point polygons of shape `(N, 4, 2)`, with
226
+ coordinates relative to the image size.
227
+
228
+ Args:
229
+ img: the image to mask, shape `(H, W)` or `(H, W, C)`
230
+ boxes: relative coordinates of the regions to fill, shape `(N, 4)` or `(N, 4, 2)`
231
+ fill_value: pixel value used to fill the masked regions
232
+
233
+ Returns:
234
+ a copy of the image with the boxes filled (the input is left untouched)
235
+ """
236
+ boxes = np.asarray(boxes, dtype=np.float32)
237
+ if boxes.size == 0:
238
+ return img
239
+
240
+ h, w = img.shape[:2]
241
+ if boxes.ndim == 2: # straight boxes (N, 4) -> (N, 4, 2) corner polygons
242
+ polys = np.empty((boxes.shape[0], 4, 2), dtype=np.float32)
243
+ polys[:, 0] = boxes[:, [0, 1]] # (x_min, y_min)
244
+ polys[:, 1] = boxes[:, [2, 1]] # (x_max, y_min)
245
+ polys[:, 2] = boxes[:, [2, 3]] # (x_max, y_max)
246
+ polys[:, 3] = boxes[:, [0, 3]] # (x_min, y_max)
247
+ else: # rotated polygons (N, 4, 2)
248
+ polys = boxes.copy()
249
+
250
+ # relative -> absolute pixel corners, clipped to the image
251
+ polys[..., 0] = np.clip(polys[..., 0] * w, 0, w)
252
+ polys[..., 1] = np.clip(polys[..., 1] * h, 0, h)
253
+ polys = polys.round().astype(np.int32)
254
+
255
+ img = img.copy()
256
+ color = (int(fill_value),) * (img.shape[2] if img.ndim == 3 else 1)
257
+ cv2.fillPoly(img, list(polys), color=color)
258
+ return img
259
+
260
+
175
261
  def invert_data_structure(
176
262
  x: list[dict[str, Any]] | dict[str, list[Any]],
177
263
  ) -> list[dict[str, Any]] | dict[str, list[Any]]:
@@ -189,4 +275,4 @@ def invert_data_structure(
189
275
  elif isinstance(x, list):
190
276
  return {k: [dic[k] for dic in x] for k in x[0]}
191
277
  else:
192
- raise TypeError(f"Expected input to be either a dict or a list, got {type(input)} instead.")
278
+ raise TypeError(f"Expected input to be either a dict or a list, got {type(x)} instead.")