python-doctr 1.0.1__py3-none-any.whl → 1.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -3,9 +3,13 @@
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 dataclasses import dataclass
6
7
  from pathlib import Path
8
+ from typing import Any
7
9
 
8
- __all__ = ["Point2D", "BoundingBox", "Polygon4P", "Polygon", "Bbox"]
10
+ import numpy as np
11
+
12
+ __all__ = ["Point2D", "BoundingBox", "Polygon4P", "Polygon", "Bbox", "Sample"]
9
13
 
10
14
 
11
15
  Point2D = tuple[float, float]
@@ -15,3 +19,19 @@ Polygon = list[Point2D]
15
19
  AbstractPath = str | Path
16
20
  AbstractFile = AbstractPath | bytes
17
21
  Bbox = tuple[float, float, float, float]
22
+
23
+
24
+ @dataclass
25
+ class Sample:
26
+ """Canonical data container for all transforms."""
27
+
28
+ image: Any
29
+ mask: Any | None = None
30
+ target: np.ndarray | dict[str, np.ndarray] | None = None
31
+
32
+ def replace(self, **kwargs) -> "Sample":
33
+ return Sample(
34
+ image=kwargs.get("image", self.image),
35
+ mask=kwargs.get("mask", self.mask),
36
+ target=kwargs.get("target", self.target),
37
+ )
doctr/utils/data.py CHANGED
@@ -11,27 +11,40 @@ import os
11
11
  import re
12
12
  import urllib.error
13
13
  import urllib.request
14
+ import uuid
14
15
  from pathlib import Path
15
16
 
16
17
  from tqdm.auto import tqdm
17
18
 
18
19
  __all__ = ["download_from_url"]
19
20
 
21
+ logger = logging.getLogger(__name__)
22
+
20
23
 
21
24
  # matches bfd8deac from resnet18-bfd8deac.ckpt
22
- HASH_REGEX = re.compile(r"-([a-f0-9]*)\.")
25
+ # Hash prefix at the end of a file name (e.g. "db_resnet50-79bd7d70.pt"), shorter runs like "-10." are not hashes
26
+ HASH_REGEX = re.compile(r"-([a-f0-9]{8,})\.")
23
27
  USER_AGENT = "mindee/doctr"
24
28
 
25
29
 
26
30
  def _urlretrieve(url: str, filename: Path | str, chunk_size: int = 1024) -> None:
27
- with open(filename, "wb") as fh:
28
- with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": USER_AGENT})) as response:
29
- with tqdm(total=response.length) as pbar:
30
- for chunk in iter(lambda: response.read(chunk_size), ""):
31
- if not chunk:
32
- break
33
- pbar.update(chunk_size)
34
- fh.write(chunk)
31
+ # Download to a temporary file first: an interrupted download must not leave a truncated file
32
+ # behind, which would then be reused as is by the next call when there is no hash to check.
33
+ # The name is unique to each call, so that concurrent downloads of the same file do not share it
34
+ tmp_path = Path(f"{filename}.{uuid.uuid4().hex}.part")
35
+ try:
36
+ with open(tmp_path, "wb") as fh:
37
+ with urllib.request.urlopen(urllib.request.Request(url, headers={"User-Agent": USER_AGENT})) as response:
38
+ with tqdm(total=response.length) as pbar:
39
+ for chunk in iter(lambda: response.read(chunk_size), ""):
40
+ if not chunk:
41
+ break
42
+ pbar.update(chunk_size)
43
+ fh.write(chunk)
44
+ os.replace(tmp_path, filename)
45
+ except BaseException:
46
+ tmp_path.unlink(missing_ok=True)
47
+ raise
35
48
 
36
49
 
37
50
  def _check_integrity(file_path: str | Path, hash_prefix: str) -> bool:
@@ -84,7 +97,7 @@ def download_from_url(
84
97
  file_path = folder_path.joinpath(file_name)
85
98
  # Check file existence
86
99
  if file_path.is_file() and (hash_prefix is None or _check_integrity(file_path, hash_prefix)):
87
- logging.info(f"Using downloaded & verified file: {file_path}")
100
+ logger.info(f"Using downloaded & verified file: {file_path}")
88
101
  return file_path
89
102
 
90
103
  try:
@@ -98,7 +111,7 @@ def download_from_url(
98
111
  error_message += (
99
112
  ". You can change default cache directory using 'DOCTR_CACHE_DIR' environment variable if needed."
100
113
  )
101
- logging.error(error_message)
114
+ logger.error(error_message)
102
115
  raise
103
116
  # Download the file
104
117
  try:
doctr/utils/fonts.py CHANGED
@@ -5,34 +5,81 @@
5
5
 
6
6
  import logging
7
7
  import platform
8
+ from functools import lru_cache
8
9
 
9
10
  from PIL import ImageFont
10
11
 
11
- __all__ = ["get_font"]
12
+ __all__ = ["get_font", "get_font_candidates"]
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ _FONT_CANDIDATES: dict[str, tuple[str, ...]] = {
17
+ "Linux": (
18
+ "DejaVuSans.ttf",
19
+ "NotoSans-Regular.ttf",
20
+ "LiberationSans-Regular.ttf",
21
+ "FreeSans.ttf",
22
+ "FreeMono.ttf", # legacy default
23
+ ),
24
+ "Darwin": (
25
+ "Arial Unicode.ttf",
26
+ "Helvetica.ttc",
27
+ "Arial.ttf", # legacy default
28
+ ),
29
+ "Windows": (
30
+ "arial.ttf", # legacy default
31
+ "segoeui.ttf",
32
+ "tahoma.ttf",
33
+ ),
34
+ }
35
+
36
+
37
+ def _is_available(font_family: str) -> bool:
38
+ try:
39
+ _ = ImageFont.truetype(font_family, 10)
40
+ except OSError:
41
+ return False
42
+ return True
43
+
44
+
45
+ def get_font_candidates() -> tuple[str, ...]:
46
+ """List the recommended fonts which are installed on this system."""
47
+ candidates = _FONT_CANDIDATES.get(platform.system(), _FONT_CANDIDATES["Linux"])
48
+ return tuple(family for family in candidates if _is_available(family))
49
+
50
+
51
+ @lru_cache(maxsize=1)
52
+ def _resolve_default_font_family() -> str | None:
53
+ """Find the first available candidate font for this platform."""
54
+ candidates = get_font_candidates()
55
+ return candidates[0] if candidates else None
12
56
 
13
57
 
14
58
  def get_font(font_family: str | None = None, font_size: int = 13) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
15
59
  """Resolves a compatible ImageFont for the system
16
60
 
17
61
  Args:
18
- font_family: the font family to use
62
+ font_family: the font family (or path to a font file) to use. If None,
63
+ the best available system font is picked automatically.
19
64
  font_size: the size of the font upon rendering
20
65
 
21
66
  Returns:
22
67
  the Pillow font
23
68
  """
24
- # Font selection
25
- if font_family is None:
26
- try:
27
- font = ImageFont.truetype("FreeMono.ttf" if platform.system() == "Linux" else "Arial.ttf", font_size)
28
- except OSError: # pragma: no cover
29
- font = ImageFont.load_default() # type: ignore[assignment]
30
- logging.warning(
31
- "unable to load recommended font family. Loading default PIL font,"
32
- "font size issues may be expected."
33
- "To prevent this, it is recommended to specify the value of 'font_family'."
34
- )
35
- else: # pragma: no cover
36
- font = ImageFont.truetype(font_family, font_size)
37
-
38
- return font
69
+ if font_family is not None:
70
+ return ImageFont.truetype(font_family, font_size)
71
+
72
+ default_family = _resolve_default_font_family()
73
+ if default_family is not None:
74
+ return ImageFont.truetype(default_family, font_size)
75
+
76
+ # Last resort: Pillow's built-in font.
77
+ try:
78
+ return ImageFont.load_default(size=font_size)
79
+ except TypeError: # pragma: no cover
80
+ logger.warning(
81
+ "Unable to load any recommended font family. Loading default PIL font, "
82
+ "font size issues may be expected. "
83
+ "To prevent this, it is recommended to specify the value of 'font_family'."
84
+ )
85
+ return ImageFont.load_default()
doctr/utils/geometry.py CHANGED
@@ -3,7 +3,6 @@
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 copy import deepcopy
7
6
  from math import ceil
8
7
 
9
8
  import cv2
@@ -14,12 +13,14 @@ from .common_types import BoundingBox, Polygon4P
14
13
  __all__ = [
15
14
  "bbox_to_polygon",
16
15
  "polygon_to_bbox",
16
+ "order_points",
17
17
  "resolve_enclosing_bbox",
18
18
  "resolve_enclosing_rbbox",
19
19
  "rotate_boxes",
20
20
  "compute_expanded_shape",
21
21
  "rotate_image",
22
22
  "remove_image_padding",
23
+ "straighten_page",
23
24
  "estimate_page_angle",
24
25
  "convert_to_relative_coords",
25
26
  "rotate_abs_geoms",
@@ -36,9 +37,9 @@ def bbox_to_polygon(bbox: BoundingBox) -> Polygon4P:
36
37
  bbox: a bounding box
37
38
 
38
39
  Returns:
39
- a polygon
40
+ a polygon with the top left, top right, bottom right and bottom left corners
40
41
  """
41
- return bbox[0], (bbox[1][0], bbox[0][1]), (bbox[0][0], bbox[1][1]), bbox[1]
42
+ return bbox[0], (bbox[1][0], bbox[0][1]), bbox[1], (bbox[0][0], bbox[1][1])
42
43
 
43
44
 
44
45
  def polygon_to_bbox(polygon: Polygon4P) -> BoundingBox:
@@ -54,6 +55,56 @@ def polygon_to_bbox(polygon: Polygon4P) -> BoundingBox:
54
55
  return (min(x), min(y)), (max(x), max(y))
55
56
 
56
57
 
58
+ def order_points(pts: np.ndarray) -> np.ndarray:
59
+ """Order points in the following order: top-left, top-right, bottom-right, bottom-left
60
+
61
+ Args:
62
+ pts: array of shape (4, 2) or (4,) with the coordinates of the points
63
+
64
+ Returns:
65
+ ordered points in the following order: top-left, top-right, bottom-right, bottom-left
66
+ """
67
+ pts = np.asarray(pts)
68
+
69
+ # (xmin, ymin, xmax, ymax)
70
+ if pts.shape == (4,):
71
+ xmin, ymin, xmax, ymax = pts
72
+ return np.array(
73
+ [
74
+ [xmin, ymin], # top-left
75
+ [xmax, ymin], # top-right
76
+ [xmax, ymax], # bottom-right
77
+ [xmin, ymax], # bottom-left
78
+ ],
79
+ dtype=pts.dtype,
80
+ )
81
+
82
+ # (4, 2) quadrangle
83
+ if pts.shape == (4, 2):
84
+ c = pts.mean(axis=0)
85
+
86
+ # compute angle of each point around centroid
87
+ angles = np.arctan2(pts[:, 1] - c[1], pts[:, 0] - c[0])
88
+
89
+ # sort by angle (counter-clockwise ordering)
90
+ pts = pts[np.argsort(angles)]
91
+
92
+ # ensure consistent starting point (top-left)
93
+ start_idx = np.argmin(pts.sum(axis=1))
94
+ pts = np.roll(pts, -start_idx, axis=0)
95
+
96
+ # ensure order is TL, TR, BR, BL (clockwise)
97
+ def area(poly):
98
+ return 0.5 * np.sum(poly[:, 0] * np.roll(poly[:, 1], -1) - poly[:, 1] * np.roll(poly[:, 0], -1))
99
+
100
+ if area(pts) < 0:
101
+ pts = np.roll(pts[::-1], 1, axis=0)
102
+
103
+ return pts.astype(pts.dtype)
104
+
105
+ raise ValueError(f"Unsupported shape {pts.shape}, expected (4,) or (4,2)")
106
+
107
+
57
108
  def detach_scores(boxes: list[np.ndarray]) -> tuple[list[np.ndarray], list[np.ndarray]]:
58
109
  """Detach the objectness scores from box predictions
59
110
 
@@ -70,6 +121,8 @@ def detach_scores(boxes: list[np.ndarray]) -> tuple[list[np.ndarray], list[np.nd
70
121
  return boxes[:, :-1], boxes[:, -1]
71
122
  return boxes[:, :-1], boxes[:, -1, -1]
72
123
 
124
+ if len(boxes) == 0:
125
+ return [], []
73
126
  loc_preds, obj_scores = zip(*(_detach(box) for box in boxes))
74
127
  return list(loc_preds), list(obj_scores)
75
128
 
@@ -113,9 +166,8 @@ def resolve_enclosing_rbbox(rbboxes: list[np.ndarray], intermed_size: int = 1024
113
166
  """
114
167
  cloud: np.ndarray = np.concatenate(rbboxes, axis=0)
115
168
  # Convert to absolute for minAreaRect
116
- cloud *= intermed_size
117
- rect = cv2.minAreaRect(cloud.astype(np.int32))
118
- return cv2.boxPoints(rect) / intermed_size
169
+ rect = cv2.minAreaRect(cloud.astype(np.float32) * intermed_size)
170
+ return order_points(cv2.boxPoints(rect) / intermed_size)
119
171
 
120
172
 
121
173
  def rotate_abs_points(points: np.ndarray, angle: float = 0.0) -> np.ndarray:
@@ -129,8 +181,10 @@ def rotate_abs_points(points: np.ndarray, angle: float = 0.0) -> np.ndarray:
129
181
  Rotated points
130
182
  """
131
183
  angle_rad = angle * np.pi / 180.0 # compute radian angle for np functions
184
+ # Integer points need a float matrix, otherwise its cosine and sine are truncated to 0 or 1
132
185
  rotation_mat = np.array(
133
- [[np.cos(angle_rad), -np.sin(angle_rad)], [np.sin(angle_rad), np.cos(angle_rad)]], dtype=points.dtype
186
+ [[np.cos(angle_rad), -np.sin(angle_rad)], [np.sin(angle_rad), np.cos(angle_rad)]],
187
+ dtype=np.result_type(points.dtype, np.float32),
134
188
  )
135
189
  return np.matmul(points, rotation_mat.T)
136
190
 
@@ -216,7 +270,8 @@ def remap_boxes(loc_preds: np.ndarray, orig_shape: tuple[int, int], dest_shape:
216
270
  raise ValueError(f"Image_shape length should be 2, was found at: {len(orig_shape)}")
217
271
  orig_height, orig_width = orig_shape
218
272
  dest_height, dest_width = dest_shape
219
- mboxes = loc_preds.copy()
273
+ # The remapped coordinates are fractional, so integer boxes (e.g. a whole page) are remapped in floating point
274
+ mboxes = loc_preds.astype(np.result_type(loc_preds.dtype, np.float32))
220
275
  mboxes[:, :, 0] = ((loc_preds[:, :, 0] * orig_width) + (dest_width - orig_width) / 2) / dest_width
221
276
  mboxes[:, :, 1] = ((loc_preds[:, :, 1] * orig_height) + (dest_height - orig_height) / 2) / dest_height
222
277
 
@@ -245,8 +300,8 @@ def rotate_boxes(
245
300
  Returns:
246
301
  A batch of rotated boxes (N, 4, 2): or a batch of straight bounding boxes
247
302
  """
248
- # Change format of the boxes to rotated boxes
249
- _boxes = loc_preds.copy()
303
+ # Change format of the boxes to rotated boxes (in floating point, so that integer boxes can be rotated)
304
+ _boxes = loc_preds.astype(np.result_type(loc_preds.dtype, np.float32))
250
305
  if _boxes.ndim == 2:
251
306
  _boxes = np.stack(
252
307
  [
@@ -280,6 +335,11 @@ def rotate_boxes(
280
335
  return rotated_boxes
281
336
 
282
337
 
338
+ def _pad_width(image: np.ndarray, h_pad: int, w_pad: int) -> tuple[tuple[int, int], ...]:
339
+ """Pad widths centering an image of shape (H, W) or (H, W, C) in a canvas larger by h_pad x w_pad"""
340
+ return ((h_pad // 2, h_pad - h_pad // 2), (w_pad // 2, w_pad - w_pad // 2)) + ((0, 0),) * (image.ndim - 2)
341
+
342
+
283
343
  def rotate_image(
284
344
  image: np.ndarray,
285
345
  angle: float,
@@ -289,7 +349,7 @@ def rotate_image(
289
349
  """Rotate an image counterclockwise by an given angle.
290
350
 
291
351
  Args:
292
- image: numpy tensor to rotate
352
+ image: array of shape (H, W) or (H, W, C)
293
353
  angle: rotation angle in degrees, between -90 and +90
294
354
  expand: whether the image should be padded before the rotation
295
355
  preserve_origin_shape: if expand is set to True, resizes the final output to the original image size
@@ -305,7 +365,7 @@ def rotate_image(
305
365
  int(max(0, ceil(exp_shape[0] - image.shape[0]))),
306
366
  int(max(0, ceil(exp_shape[1] - image.shape[1]))),
307
367
  )
308
- exp_img = np.pad(image, ((h_pad // 2, h_pad - h_pad // 2), (w_pad // 2, w_pad - w_pad // 2), (0, 0)))
368
+ exp_img = np.pad(image, _pad_width(image, h_pad, w_pad))
309
369
  else:
310
370
  exp_img = image
311
371
 
@@ -321,10 +381,13 @@ def rotate_image(
321
381
  # Pad height
322
382
  else:
323
383
  h_pad, w_pad = int(rot_img.shape[1] * image.shape[0] / image.shape[1] - rot_img.shape[0]), 0
324
- rot_img = np.pad(rot_img, ((h_pad // 2, h_pad - h_pad // 2), (w_pad // 2, w_pad - w_pad // 2), (0, 0)))
384
+ rot_img = np.pad(rot_img, _pad_width(rot_img, h_pad, w_pad))
325
385
  if preserve_origin_shape:
326
386
  # rescale
327
- rot_img = cv2.resize(rot_img, image.shape[:-1][::-1], interpolation=cv2.INTER_LINEAR)
387
+ rot_img = cv2.resize(rot_img, image.shape[1::-1], interpolation=cv2.INTER_LINEAR)
388
+
389
+ if rot_img.ndim < image.ndim: # cv2 drops a singleton channel axis
390
+ rot_img = rot_img[..., None]
328
391
 
329
392
  return rot_img
330
393
 
@@ -338,15 +401,82 @@ def remove_image_padding(image: np.ndarray) -> np.ndarray:
338
401
  Returns:
339
402
  Image with padding removed
340
403
  """
341
- # Find the bounding box of the non-black region
342
- rows = np.any(image, axis=1)
343
- cols = np.any(image, axis=0)
344
- rmin, rmax = np.where(rows)[0][[0, -1]]
345
- cmin, cmax = np.where(cols)[0][[0, -1]]
404
+ # Find the bounding box of the non-black region (reduce over every axis but the one of interest)
405
+ rows = np.any(image, axis=tuple(ax for ax in range(image.ndim) if ax != 0))
406
+ cols = np.any(image, axis=tuple(ax for ax in range(image.ndim) if ax != 1))
407
+ if not rows.any(): # fully black image: nothing to crop
408
+ return image
409
+ rmin, rmax = int(np.argmax(rows)), image.shape[0] - 1 - int(np.argmax(rows[::-1]))
410
+ cmin, cmax = int(np.argmax(cols)), image.shape[1] - 1 - int(np.argmax(cols[::-1]))
346
411
 
347
412
  return image[rmin : rmax + 1, cmin : cmax + 1]
348
413
 
349
414
 
415
+ def straighten_page(
416
+ page: np.ndarray,
417
+ angle: float,
418
+ ) -> tuple[np.ndarray, np.ndarray]:
419
+ """Straighten a page by rotating it and cropping to content, returning the straightened image
420
+ and the inverse affine matrix that maps straightened-page coordinates back to the original page.
421
+
422
+ Args:
423
+ page: the original page image (H, W) or (H, W, C)
424
+ angle: rotation angle in degrees (between -90 and +90)
425
+
426
+ Returns:
427
+ a tuple (straightened, M_inv) where straightened is the page rotated and cropped to the
428
+ non-padded region, and M_inv is a (3, 3) array mapping points in the straightened image's
429
+ pixel space (x, y, 1) back to the original page's pixel space.
430
+ """
431
+ h, w = page.shape[:2]
432
+
433
+ # Padding to preserve content after rotation
434
+ exp = compute_expanded_shape((h, w), angle)
435
+ h_pad = int(max(0, np.ceil(exp[0] - h)))
436
+ w_pad = int(max(0, np.ceil(exp[1] - w)))
437
+
438
+ pt, pb = h_pad // 2, h_pad - h_pad // 2
439
+ pl, pr = w_pad // 2, w_pad - w_pad // 2
440
+
441
+ # A grayscale page (H, W) has no channel axis to leave unpadded
442
+ channels = ((0, 0),) * (page.ndim - 2)
443
+ exp_img = np.pad(page, ((pt, pb), (pl, pr), *channels))
444
+ ph_pad, pw_pad = exp_img.shape[:2]
445
+
446
+ # Rotate around the padded image center
447
+ rot_mat = cv2.getRotationMatrix2D((pw_pad / 2, ph_pad / 2), angle, 1.0)
448
+ rotated = cv2.warpAffine(exp_img, rot_mat, (pw_pad, ph_pad))
449
+ if rotated.ndim < exp_img.ndim: # cv2 drops a singleton channel axis
450
+ rotated = rotated[..., None]
451
+
452
+ # Aspect-ratio padding (applied only on right/bottom so analytic crop stays simple)
453
+ if h_pad > 0 or w_pad > 0:
454
+ if (rotated.shape[0] / rotated.shape[1]) > (h / w):
455
+ w_pad2 = int(rotated.shape[0] * w / h - rotated.shape[1])
456
+ rotated = np.pad(rotated, ((0, 0), (0, w_pad2), *channels))
457
+ else:
458
+ h_pad2 = int(rotated.shape[1] * h / w - rotated.shape[0])
459
+ rotated = np.pad(rotated, ((0, h_pad2), (0, 0), *channels))
460
+
461
+ # Analytic crop: project the four content corners through the rotation matrix
462
+ corners = np.array(
463
+ [[pl, pt, 1], [pl + w, pt, 1], [pl + w, pt + h, 1], [pl, pt + h, 1]],
464
+ dtype=np.float64,
465
+ ).T
466
+ rc = rot_mat @ corners
467
+ cx, cy = max(0, int(np.floor(rc[0].min()))), max(0, int(np.floor(rc[1].min())))
468
+ cropped = rotated[cy:, cx:]
469
+
470
+ # Composite forward matrix: crop ∘ rotate ∘ pad
471
+ # cv2.warpAffine treats the rotation matrix as src→dst
472
+ c3 = np.array([[1, 0, -cx], [0, 1, -cy], [0, 0, 1]], dtype=np.float64)
473
+ r3 = np.vstack([rot_mat, [0, 0, 1]])
474
+ p3 = np.array([[1, 0, pl], [0, 1, pt], [0, 0, 1]], dtype=np.float64)
475
+ m_inv = np.linalg.inv(c3 @ r3 @ p3)
476
+
477
+ return cropped, m_inv
478
+
479
+
350
480
  def estimate_page_angle(polys: np.ndarray) -> float:
351
481
  """Takes a batch of rotated previously ORIENTED polys (N, 4, 2) (rectified by the classifier) and return the
352
482
  estimated angle ccw in degrees
@@ -356,13 +486,12 @@ def estimate_page_angle(polys: np.ndarray) -> float:
356
486
  yleft = polys[:, 0, 1] + polys[:, 3, 1]
357
487
  xright = polys[:, 1, 0] + polys[:, 2, 0]
358
488
  yright = polys[:, 1, 1] + polys[:, 2, 1]
359
- with np.errstate(divide="raise", invalid="raise"):
360
- try:
361
- return float(
362
- np.median(np.arctan((yleft - yright) / (xright - xleft)) * 180 / np.pi) # Y axis from top to bottom!
363
- )
364
- except FloatingPointError:
365
- return 0.0
489
+ with np.errstate(divide="ignore", invalid="ignore"):
490
+ angles = np.arctan((yleft - yright) / (xright - xleft)) * 180 / np.pi # Y axis from top to bottom!
491
+ # Degenerate polygons (0/0) yield NaN: ignore them instead of discarding the whole page estimate,
492
+ # while vertical polygons (x/0 -> +/-inf) legitimately contribute +/-90 degrees through arctan
493
+ angles = angles[np.isfinite(angles)]
494
+ return float(np.median(angles)) if angles.size > 0 else 0.0
366
495
 
367
496
 
368
497
  def convert_to_relative_coords(geoms: np.ndarray, img_shape: tuple[int, int]) -> np.ndarray:
@@ -414,9 +543,11 @@ def extract_crops(img: np.ndarray, boxes: np.ndarray) -> list[np.ndarray]:
414
543
  _boxes[:, [1, 3]] *= h
415
544
  _boxes = _boxes.round().astype(int)
416
545
  # Add last index
417
- _boxes[2:] += 1
546
+ _boxes[:, 2:] += 1
547
+ # A box starting before the image would slice from its end: crop its visible part instead (empty if none)
548
+ _boxes = np.maximum(_boxes, 0)
418
549
 
419
- return deepcopy([img[box[1] : box[3], box[0] : box[2]] for box in _boxes])
550
+ return [np.ascontiguousarray(img[box[1] : box[3], box[0] : box[2]]) for box in _boxes]
420
551
 
421
552
 
422
553
  def extract_rcrops(
@@ -458,6 +589,9 @@ def extract_rcrops(
458
589
  # Divide the points into left and right
459
590
  left_points = box[box[:, 0] < centroid[0]]
460
591
  right_points = box[box[:, 0] >= centroid[0]]
592
+ if len(left_points) == 0 or len(right_points) == 0:
593
+ crops.append(np.zeros((0, 0, *img.shape[2:]), dtype=img.dtype))
594
+ continue
461
595
 
462
596
  # Sort the left points according to the y-axis
463
597
  left_points = left_points[np.argsort(left_points[:, 1])]
@@ -481,6 +615,9 @@ def extract_rcrops(
481
615
  # Get the maximum width and height
482
616
  rect_width = max(int(width_upper), int(width_lower))
483
617
  rect_height = max(int(height_left), int(height_right))
618
+ if rect_width < 1 or rect_height < 1:
619
+ crops.append(np.zeros((0, 0, *img.shape[2:]), dtype=img.dtype))
620
+ continue
484
621
 
485
622
  dst_pts = np.array(
486
623
  [
@@ -526,6 +663,8 @@ def extract_rcrops(
526
663
  cv2.getAffineTransform(src_pts[idx], dst_pts[idx]),
527
664
  (int(d1[idx]), int(d2[idx])),
528
665
  )
666
+ if int(d1[idx]) > 0 and int(d2[idx]) > 0
667
+ else np.zeros((0, 0, *img.shape[2:]), dtype=img.dtype)
529
668
  for idx in range(_boxes.shape[0])
530
669
  ]
531
670
  return crops