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
doctr/io/image/base.py CHANGED
@@ -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
@@ -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/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
@@ -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
+ 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:
@@ -58,7 +66,7 @@ def estimate_orientation(
58
66
 
59
67
  # Convert image to grayscale if necessary
60
68
  if img.shape[-1] == 3:
61
- gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
69
+ gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
62
70
  gray_img = cv2.medianBlur(gray_img, 5)
63
71
  thresh = cv2.threshold(gray_img, thresh=0, maxval=255, type=cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
64
72
  else:
@@ -83,15 +91,15 @@ def estimate_orientation(
83
91
  # extract contours
84
92
  contours, _ = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
85
93
 
86
- # Filter & Sort contours
87
- contours = sorted(
88
- [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),
89
98
  key=get_max_width_length_ratio,
90
- reverse=True,
91
99
  )
92
100
 
93
101
  angles = []
94
- for contour in contours[:n_ct]:
102
+ for contour in contours:
95
103
  _, (w, h), angle = cv2.minAreaRect(contour)
96
104
 
97
105
  # OpenCV version-proof normalization: force 'w' to be the long side
@@ -210,6 +218,46 @@ def get_language(text: str) -> tuple[str, float]:
210
218
  return lang.lang, lang.prob
211
219
 
212
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
+
213
261
  def invert_data_structure(
214
262
  x: list[dict[str, Any]] | dict[str, list[Any]],
215
263
  ) -> list[dict[str, Any]] | dict[str, list[Any]]:
@@ -227,4 +275,4 @@ def invert_data_structure(
227
275
  elif isinstance(x, list):
228
276
  return {k: [dic[k] for dic in x] for k in x[0]}
229
277
  else:
230
- 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.")