python-doctr 1.0.0__py3-none-any.whl → 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +506 -0
  3. doctr/contrib/artefacts.py +1 -1
  4. doctr/contrib/base.py +1 -1
  5. doctr/datasets/__init__.py +2 -0
  6. doctr/datasets/coco_text.py +5 -3
  7. doctr/datasets/cord.py +3 -2
  8. doctr/datasets/datasets/base.py +13 -25
  9. doctr/datasets/datasets/pytorch.py +15 -5
  10. doctr/datasets/detection.py +3 -2
  11. doctr/datasets/doc_artefacts.py +3 -2
  12. doctr/datasets/funsd.py +3 -2
  13. doctr/datasets/generator/base.py +6 -5
  14. doctr/datasets/generator/pytorch.py +5 -6
  15. doctr/datasets/ic03.py +4 -3
  16. doctr/datasets/ic13.py +5 -3
  17. doctr/datasets/iiit5k.py +3 -2
  18. doctr/datasets/iiithws.py +5 -3
  19. doctr/datasets/imgur5k.py +5 -3
  20. doctr/datasets/layout.py +123 -0
  21. doctr/datasets/mjsynth.py +5 -3
  22. doctr/datasets/ocr.py +3 -2
  23. doctr/datasets/orientation.py +3 -2
  24. doctr/datasets/recognition.py +3 -2
  25. doctr/datasets/sroie.py +3 -2
  26. doctr/datasets/svhn.py +3 -2
  27. doctr/datasets/svt.py +4 -3
  28. doctr/datasets/synthtext.py +3 -2
  29. doctr/datasets/table_structure.py +97 -0
  30. doctr/datasets/utils.py +15 -6
  31. doctr/datasets/vocabs.py +3 -1
  32. doctr/datasets/wildreceipt.py +5 -3
  33. doctr/file_utils.py +4 -2
  34. doctr/io/__init__.py +1 -0
  35. doctr/io/elements.py +253 -261
  36. doctr/io/exporters.py +1275 -0
  37. doctr/io/html.py +1 -1
  38. doctr/io/image/base.py +4 -3
  39. doctr/io/image/pytorch.py +6 -4
  40. doctr/io/pdf.py +1 -1
  41. doctr/io/reader.py +1 -1
  42. doctr/models/__init__.py +2 -0
  43. doctr/models/_utils.py +111 -25
  44. doctr/models/builder.py +533 -62
  45. doctr/models/classification/__init__.py +2 -0
  46. doctr/models/classification/magc_resnet/pytorch.py +2 -2
  47. doctr/models/classification/mobilenet/pytorch.py +7 -7
  48. doctr/models/classification/predictor/pytorch.py +7 -3
  49. doctr/models/classification/resnet/pytorch.py +6 -6
  50. doctr/models/classification/starnet/__init__.py +1 -0
  51. doctr/models/classification/starnet/pytorch.py +202 -0
  52. doctr/models/classification/textnet/pytorch.py +7 -6
  53. doctr/models/classification/vgg/pytorch.py +4 -3
  54. doctr/models/classification/vip/layers/pytorch.py +5 -5
  55. doctr/models/classification/vip/pytorch.py +5 -5
  56. doctr/models/classification/vit/pytorch.py +4 -4
  57. doctr/models/classification/vit_det/__init__.py +1 -0
  58. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  60. doctr/models/classification/vit_det/pytorch.py +346 -0
  61. doctr/models/classification/zoo.py +4 -1
  62. doctr/models/core.py +1 -1
  63. doctr/models/detection/_utils/base.py +24 -8
  64. doctr/models/detection/_utils/pytorch.py +1 -1
  65. doctr/models/detection/core.py +34 -19
  66. doctr/models/detection/differentiable_binarization/base.py +7 -5
  67. doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
  68. doctr/models/detection/fast/base.py +6 -2
  69. doctr/models/detection/fast/pytorch.py +4 -4
  70. doctr/models/detection/linknet/base.py +6 -2
  71. doctr/models/detection/linknet/pytorch.py +4 -4
  72. doctr/models/detection/predictor/pytorch.py +4 -3
  73. doctr/models/detection/zoo.py +3 -3
  74. doctr/models/factory/hub.py +72 -52
  75. doctr/models/kie_predictor/base.py +17 -2
  76. doctr/models/kie_predictor/pytorch.py +42 -11
  77. doctr/models/layout/__init__.py +2 -0
  78. doctr/models/layout/lw_detr/__init__.py +1 -0
  79. doctr/models/layout/lw_detr/base.py +309 -0
  80. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  81. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  82. doctr/models/layout/lw_detr/pytorch.py +838 -0
  83. doctr/models/layout/predictor/__init__.py +1 -0
  84. doctr/models/layout/predictor/pytorch.py +82 -0
  85. doctr/models/layout/zoo.py +90 -0
  86. doctr/models/modules/layers/pytorch.py +140 -4
  87. doctr/models/modules/transformer/pytorch.py +1 -1
  88. doctr/models/modules/vision_transformer/pytorch.py +1 -1
  89. doctr/models/predictor/base.py +138 -16
  90. doctr/models/predictor/pytorch.py +151 -9
  91. doctr/models/preprocessor/pytorch.py +78 -23
  92. doctr/models/reading_order/__init__.py +1 -0
  93. doctr/models/reading_order/base.py +667 -0
  94. doctr/models/recognition/core.py +1 -1
  95. doctr/models/recognition/crnn/pytorch.py +6 -8
  96. doctr/models/recognition/master/base.py +1 -1
  97. doctr/models/recognition/master/pytorch.py +7 -8
  98. doctr/models/recognition/parseq/base.py +1 -1
  99. doctr/models/recognition/parseq/pytorch.py +5 -5
  100. doctr/models/recognition/predictor/_utils.py +1 -1
  101. doctr/models/recognition/predictor/pytorch.py +2 -2
  102. doctr/models/recognition/sar/pytorch.py +2 -2
  103. doctr/models/recognition/utils.py +9 -11
  104. doctr/models/recognition/viptr/pytorch.py +4 -6
  105. doctr/models/recognition/vitstr/base.py +1 -1
  106. doctr/models/recognition/vitstr/pytorch.py +6 -6
  107. doctr/models/recognition/zoo.py +6 -7
  108. doctr/models/table_structure/__init__.py +2 -0
  109. doctr/models/table_structure/predictor/__init__.py +1 -0
  110. doctr/models/table_structure/predictor/pytorch.py +80 -0
  111. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  112. doctr/models/table_structure/tablecenternet/base.py +485 -0
  113. doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
  114. doctr/models/table_structure/zoo.py +82 -0
  115. doctr/models/utils/pytorch.py +316 -16
  116. doctr/models/zoo.py +91 -3
  117. doctr/transforms/functional/base.py +3 -2
  118. doctr/transforms/functional/pytorch.py +1 -1
  119. doctr/transforms/modules/base.py +248 -83
  120. doctr/transforms/modules/pytorch.py +213 -74
  121. doctr/utils/common_types.py +22 -2
  122. doctr/utils/data.py +5 -4
  123. doctr/utils/fonts.py +56 -17
  124. doctr/utils/geometry.py +136 -19
  125. doctr/utils/metrics.py +351 -19
  126. doctr/utils/multithreading.py +6 -3
  127. doctr/utils/reconstitution.py +697 -133
  128. doctr/utils/repr.py +1 -1
  129. doctr/utils/visualization.py +63 -4
  130. doctr/version.py +1 -1
  131. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
  132. python_doctr-1.1.0.dist-info/RECORD +179 -0
  133. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
  134. python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
  135. python_doctr-1.0.0.dist-info/RECORD +0 -149
  136. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
  137. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
  138. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
@@ -1,18 +1,20 @@
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
6
  import math
7
+ from collections.abc import Sequence
7
8
 
8
9
  import numpy as np
9
10
  import torch
10
- from PIL.Image import Image
11
11
  from scipy.ndimage import gaussian_filter
12
12
  from torch.nn.functional import pad
13
13
  from torchvision.transforms import functional as F
14
14
  from torchvision.transforms import transforms as T
15
15
 
16
+ from doctr.utils import Sample
17
+
16
18
  from ..functional import random_shadow
17
19
 
18
20
  __all__ = [
@@ -31,8 +33,9 @@ class Resize(T.Resize):
31
33
 
32
34
  >>> import torch
33
35
  >>> from doctr.transforms import Resize
36
+ >>> from doctr.utils import Sample
34
37
  >>> transfo = Resize((64, 64), preserve_aspect_ratio=True, symmetric_pad=True)
35
- >>> out = transfo(torch.rand((3, 64, 64)))
38
+ >>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
36
39
 
37
40
  Args:
38
41
  size: output size in pixels, either a tuple (height, width) or a single integer for square images
@@ -41,6 +44,9 @@ class Resize(T.Resize):
41
44
  if True, the image will be resized to fit within the target size while maintaining its aspect ratio
42
45
  symmetric_pad: whether to symmetrically pad the image to the target size,
43
46
  if True, the image will be padded equally on both sides to fit the target size
47
+ return_padding_mask: whether to return a boolean mask alongside the image, with True on valid
48
+ (image content) pixels and False on padded areas. This matches how masks propagate through the
49
+ other transforms (padding and rotation fill new areas with False).
44
50
  """
45
51
 
46
52
  def __init__(
@@ -49,25 +55,87 @@ class Resize(T.Resize):
49
55
  interpolation=F.InterpolationMode.BILINEAR,
50
56
  preserve_aspect_ratio: bool = False,
51
57
  symmetric_pad: bool = False,
58
+ return_padding_mask: bool = False,
52
59
  ) -> None:
53
60
  super().__init__(size if isinstance(size, (list, tuple)) else (size, size), interpolation, antialias=True)
54
61
  self.preserve_aspect_ratio = preserve_aspect_ratio
55
62
  self.symmetric_pad = symmetric_pad
63
+ self.return_padding_mask = return_padding_mask
64
+
65
+ def _resize_target(
66
+ self,
67
+ target: np.ndarray,
68
+ raw_shape: Sequence[int],
69
+ final_shape: Sequence[int],
70
+ symmetric_pad: bool = False,
71
+ offset: tuple[int, int] = (0, 0),
72
+ ) -> np.ndarray:
73
+ """Resize the target boxes according to the resizing of the image and the padding if needed"""
74
+ target = target.copy()
75
+
76
+ if target.shape[1:] == (4,):
77
+ if symmetric_pad:
78
+ target[:, [0, 2]] = offset[0] + target[:, [0, 2]] * raw_shape[-1] / final_shape[-1]
79
+ target[:, [1, 3]] = offset[1] + target[:, [1, 3]] * raw_shape[-2] / final_shape[-2]
80
+ else:
81
+ target[:, [0, 2]] *= raw_shape[-1] / final_shape[-1]
82
+ target[:, [1, 3]] *= raw_shape[-2] / final_shape[-2]
83
+
84
+ elif target.shape[1:] == (4, 2):
85
+ if symmetric_pad:
86
+ target[..., 0] = offset[0] + target[..., 0] * raw_shape[-1] / final_shape[-1]
87
+ target[..., 1] = offset[1] + target[..., 1] * raw_shape[-2] / final_shape[-2]
88
+ else:
89
+ target[..., 0] *= raw_shape[-1] / final_shape[-1]
90
+ target[..., 1] *= raw_shape[-2] / final_shape[-2]
91
+
92
+ else:
93
+ raise AssertionError("Boxes should be in the format (n_boxes, 4, 2) or (n_boxes, 4)")
94
+
95
+ return np.clip(target, 0, 1)
56
96
 
57
97
  def forward(
58
98
  self,
59
- img: torch.Tensor,
60
- target: np.ndarray | None = None,
61
- ) -> torch.Tensor | tuple[torch.Tensor, np.ndarray]:
99
+ sample: Sample,
100
+ ) -> Sample:
101
+ img = sample.image
102
+ target = sample.target
103
+ mask = sample.mask
104
+
105
+ # Resize mask alongside image if provided
106
+ # Masks should use nearest interpolation to preserve label integrity
107
+ resize_mask = mask is not None
108
+ if resize_mask and mask is not None and mask.ndim == 2:
109
+ mask = mask.unsqueeze(0)
110
+
62
111
  target_ratio = self.size[0] / self.size[1]
63
112
  actual_ratio = img.shape[-2] / img.shape[-1]
64
113
 
65
114
  if not self.preserve_aspect_ratio or (target_ratio == actual_ratio):
66
115
  # If we don't preserve the aspect ratio or the wanted aspect ratio is the same than the original one
67
116
  # We can use with the regular resize
117
+ img = super().forward(img)
118
+
119
+ if resize_mask:
120
+ mask = F.resize(
121
+ mask,
122
+ self.size,
123
+ interpolation=F.InterpolationMode.NEAREST,
124
+ antialias=False,
125
+ ).squeeze(0)
126
+
127
+ if self.return_padding_mask:
128
+ # No padding was added: every pixel is valid image content
129
+ padding_mask = torch.ones(self.size, dtype=torch.bool, device=img.device)
130
+
68
131
  if target is not None:
69
- return super().forward(img), target
70
- return super().forward(img)
132
+ if self.return_padding_mask:
133
+ return sample.replace(image=img, target=target, mask=mask if resize_mask else padding_mask)
134
+ return sample.replace(image=img, target=target, mask=mask if resize_mask else sample.mask)
135
+ if self.return_padding_mask:
136
+ return sample.replace(image=img, mask=mask if resize_mask else padding_mask)
137
+ return sample.replace(image=img, mask=mask if resize_mask else sample.mask)
138
+
71
139
  else:
72
140
  # Resize
73
141
  if actual_ratio > target_ratio:
@@ -77,43 +145,77 @@ class Resize(T.Resize):
77
145
 
78
146
  # Scale image
79
147
  img = F.resize(img, tmp_size, self.interpolation, antialias=True)
148
+
149
+ if resize_mask:
150
+ mask = F.resize(
151
+ mask,
152
+ tmp_size,
153
+ interpolation=F.InterpolationMode.NEAREST,
154
+ antialias=False,
155
+ ).squeeze(0)
156
+
80
157
  raw_shape = img.shape[-2:]
158
+
81
159
  if isinstance(self.size, (tuple, list)):
82
160
  # Pad (inverted in pytorch)
83
161
  _pad = (0, self.size[1] - img.shape[-1], 0, self.size[0] - img.shape[-2])
162
+
84
163
  if self.symmetric_pad:
85
164
  half_pad = (math.ceil(_pad[1] / 2), math.ceil(_pad[3] / 2))
86
165
  _pad = (half_pad[0], _pad[1] - half_pad[0], half_pad[1], _pad[3] - half_pad[1])
87
166
  # Pad image
88
167
  img = pad(img, _pad)
89
168
 
169
+ if resize_mask and mask is not None:
170
+ mask = pad(mask, _pad)
171
+
172
+ if self.return_padding_mask:
173
+ # True on valid (image content) pixels, False on the padded borders
174
+ h, w = self.size
175
+ padding_mask = torch.zeros((h, w), dtype=torch.bool, device=img.device)
176
+ left, right, top, bottom = _pad
177
+ padding_mask[top : h - bottom, left : w - right] = True
178
+
90
179
  # In case boxes are provided, resize boxes if needed (for detection task if preserve aspect ratio)
91
180
  if target is not None:
92
181
  if self.symmetric_pad:
93
- offset = half_pad[0] / img.shape[-1], half_pad[1] / img.shape[-2]
94
-
95
- if self.preserve_aspect_ratio:
96
- # Get absolute coords
97
- if target.shape[1:] == (4,):
98
- if self.symmetric_pad:
99
- target[:, [0, 2]] = offset[0] + target[:, [0, 2]] * raw_shape[-1] / img.shape[-1]
100
- target[:, [1, 3]] = offset[1] + target[:, [1, 3]] * raw_shape[-2] / img.shape[-2]
101
- else:
102
- target[:, [0, 2]] *= raw_shape[-1] / img.shape[-1]
103
- target[:, [1, 3]] *= raw_shape[-2] / img.shape[-2]
104
- elif target.shape[1:] == (4, 2):
105
- if self.symmetric_pad:
106
- target[..., 0] = offset[0] + target[..., 0] * raw_shape[-1] / img.shape[-1]
107
- target[..., 1] = offset[1] + target[..., 1] * raw_shape[-2] / img.shape[-2]
108
- else:
109
- target[..., 0] *= raw_shape[-1] / img.shape[-1]
110
- target[..., 1] *= raw_shape[-2] / img.shape[-2]
111
- else:
112
- raise AssertionError("Boxes should be in the format (n_boxes, 4, 2) or (n_boxes, 4)")
113
-
114
- return img, np.clip(target, 0, 1)
115
-
116
- return img
182
+ offset = (
183
+ half_pad[0] / img.shape[-1],
184
+ half_pad[1] / img.shape[-2],
185
+ )
186
+ else:
187
+ offset = (0, 0)
188
+
189
+ if isinstance(target, str) or (isinstance(target, np.ndarray) and target.shape == (1,)):
190
+ # Special case for orientation targets and other non-box targets, which should not be resized
191
+ pass
192
+ elif isinstance(target, dict):
193
+ target = {
194
+ cls_name: self._resize_target(
195
+ arr,
196
+ raw_shape,
197
+ img.shape[-2:],
198
+ symmetric_pad=self.symmetric_pad,
199
+ offset=offset,
200
+ )
201
+ for cls_name, arr in target.items()
202
+ }
203
+ else:
204
+ target = self._resize_target(
205
+ target,
206
+ raw_shape,
207
+ img.shape[-2:],
208
+ symmetric_pad=self.symmetric_pad,
209
+ offset=offset,
210
+ )
211
+
212
+ if target is not None:
213
+ if self.return_padding_mask:
214
+ return sample.replace(image=img, target=target, mask=mask if resize_mask else padding_mask)
215
+ return sample.replace(image=img, target=target, mask=mask if resize_mask else sample.mask)
216
+ if self.return_padding_mask:
217
+ return sample.replace(image=img, mask=mask if resize_mask else padding_mask)
218
+ return sample.replace(image=img, mask=mask if resize_mask else sample.mask)
117
219
 
118
220
  def __repr__(self) -> str:
119
221
  interpolate_str = self.interpolation.value
@@ -128,8 +230,9 @@ class GaussianNoise(torch.nn.Module):
128
230
 
129
231
  >>> import torch
130
232
  >>> from doctr.transforms import GaussianNoise
233
+ >>> from doctr.utils import Sample
131
234
  >>> transfo = GaussianNoise(0., 1.)
132
- >>> out = transfo(torch.rand((3, 224, 224)))
235
+ >>> out = transfo(Sample(image=torch.rand((3, 224, 224))))
133
236
 
134
237
  Args:
135
238
  mean : mean of the gaussian distribution
@@ -141,13 +244,14 @@ class GaussianNoise(torch.nn.Module):
141
244
  self.std = std
142
245
  self.mean = mean
143
246
 
144
- def forward(self, x: torch.Tensor) -> torch.Tensor:
145
- # Reshape the distribution
247
+ def forward(self, sample: Sample) -> Sample:
248
+ x = sample.image
146
249
  noise = self.mean + 2 * self.std * torch.rand(x.shape, device=x.device) - self.std
147
250
  if x.dtype == torch.uint8:
148
- return (x + 255 * noise).round().clamp(0, 255).to(dtype=torch.uint8)
251
+ image = (x + 255 * noise).round().clamp(0, 255).to(dtype=torch.uint8)
149
252
  else:
150
- return (x + noise.to(dtype=x.dtype)).clamp(0, 1)
253
+ image = (x + noise.to(dtype=x.dtype)).clamp(0, 1)
254
+ return sample.replace(image=image)
151
255
 
152
256
  def extra_repr(self) -> str:
153
257
  return f"mean={self.mean}, std={self.std}"
@@ -158,7 +262,9 @@ class GaussianBlur(torch.nn.Module):
158
262
 
159
263
  >>> import torch
160
264
  >>> from doctr.transforms import GaussianBlur
265
+ >>> from doctr.utils import Sample
161
266
  >>> transfo = GaussianBlur(sigma=(0.0, 1.0))
267
+ >>> out = transfo(Sample(image=torch.rand((3, 224, 224))))
162
268
 
163
269
  Args:
164
270
  sigma : standard deviation range for the gaussian kernel
@@ -168,50 +274,77 @@ class GaussianBlur(torch.nn.Module):
168
274
  super().__init__()
169
275
  self.sigma_range = sigma
170
276
 
171
- def forward(self, x: torch.Tensor) -> torch.Tensor:
277
+ def forward(self, sample: Sample) -> Sample:
172
278
  # Sample a random sigma value within the specified range
173
279
  sigma = torch.empty(1).uniform_(*self.sigma_range).item()
174
280
 
175
281
  # Apply Gaussian blur along spatial dimensions only
176
282
  blurred = torch.tensor(
177
283
  gaussian_filter(
178
- x.numpy(),
284
+ sample.image.numpy(),
179
285
  sigma=sigma,
180
286
  mode="reflect",
181
287
  truncate=4.0,
182
288
  ),
183
- dtype=x.dtype,
184
- device=x.device,
289
+ dtype=sample.image.dtype,
290
+ device=sample.image.device,
185
291
  )
186
- return blurred
292
+ return sample.replace(image=blurred)
187
293
 
188
294
 
189
295
  class ChannelShuffle(torch.nn.Module):
190
- """Randomly shuffle channel order of a given image"""
296
+ """Randomly shuffle channel order of a given image
297
+
298
+ >>> import torch
299
+ >>> from doctr.transforms import ChannelShuffle
300
+ >>> from doctr.utils import Sample
301
+ >>> transfo = ChannelShuffle()
302
+ >>> out = transfo(Sample(image=torch.rand((3, 224, 224))))
303
+ """
191
304
 
192
305
  def __init__(self):
193
306
  super().__init__()
194
307
 
195
- def forward(self, img: torch.Tensor) -> torch.Tensor:
308
+ def forward(self, sample: Sample) -> Sample:
196
309
  # Get a random order
197
- chan_order = torch.rand(img.shape[0]).argsort()
198
- return img[chan_order]
310
+ chan_order = torch.rand(sample.image.shape[0]).argsort()
311
+ return sample.replace(image=sample.image[chan_order])
199
312
 
200
313
 
201
314
  class RandomHorizontalFlip(T.RandomHorizontalFlip):
202
- """Randomly flip the input image horizontally"""
315
+ """Randomly flip the input image horizontally
316
+
317
+ >>> import torch
318
+ >>> from doctr.transforms import RandomHorizontalFlip
319
+ >>> from doctr.utils import Sample
320
+ >>> transfo = RandomHorizontalFlip(p=1.0)
321
+ >>> out = transfo(Sample(image=torch.rand((3, 224, 224)), target=np.array([[0.1, 0.2, 0.3, 0.4]])))
322
+ """
203
323
 
204
- def forward(self, img: torch.Tensor | Image, target: np.ndarray) -> tuple[torch.Tensor | Image, np.ndarray]:
324
+ def _flip_array(self, target):
325
+ _target = target.copy()
326
+ # Changing the relative bbox coordinates
327
+ if target.shape[1:] == (4,):
328
+ _target[:, ::2] = 1 - target[:, [2, 0]]
329
+ else:
330
+ _target[..., 0] = 1 - target[..., 0]
331
+ return _target
332
+
333
+ def forward(self, sample: Sample) -> Sample:
205
334
  if torch.rand(1) < self.p:
206
- _img = F.hflip(img)
207
- _target = target.copy()
208
- # Changing the relative bbox coordinates
209
- if target.shape[1:] == (4,):
210
- _target[:, ::2] = 1 - target[:, [2, 0]]
211
- else:
212
- _target[..., 0] = 1 - target[..., 0]
213
- return _img, _target
214
- return img, target
335
+ img = F.hflip(sample.image)
336
+ mask = F.hflip(sample.mask) if sample.mask is not None else None
337
+
338
+ target = sample.target
339
+ if target is not None:
340
+ if isinstance(target, dict):
341
+ target = {k: self._flip_array(v) for k, v in target.items()}
342
+ else:
343
+ target = self._flip_array(target)
344
+
345
+ return sample.replace(image=img, mask=mask, target=target)
346
+
347
+ return sample
215
348
 
216
349
 
217
350
  class RandomShadow(torch.nn.Module):
@@ -219,8 +352,9 @@ class RandomShadow(torch.nn.Module):
219
352
 
220
353
  >>> import torch
221
354
  >>> from doctr.transforms import RandomShadow
355
+ >>> from doctr.utils import Sample
222
356
  >>> transfo = RandomShadow((0., 1.))
223
- >>> out = transfo(torch.rand((3, 64, 64)))
357
+ >>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
224
358
 
225
359
  Args:
226
360
  opacity_range : minimum and maximum opacity of the shade
@@ -230,15 +364,15 @@ class RandomShadow(torch.nn.Module):
230
364
  super().__init__()
231
365
  self.opacity_range = opacity_range if isinstance(opacity_range, tuple) else (0.2, 0.8)
232
366
 
233
- def __call__(self, x: torch.Tensor) -> torch.Tensor:
367
+ def __call__(self, sample: Sample) -> Sample:
234
368
  # Reshape the distribution
235
369
  try:
236
- if x.dtype == torch.uint8:
237
- return (
370
+ if sample.image.dtype == torch.uint8:
371
+ shadowed_image = (
238
372
  (
239
373
  255
240
374
  * random_shadow(
241
- x.to(dtype=torch.float32) / 255,
375
+ sample.image.to(dtype=torch.float32) / 255,
242
376
  self.opacity_range,
243
377
  )
244
378
  )
@@ -246,10 +380,12 @@ class RandomShadow(torch.nn.Module):
246
380
  .clip(0, 255)
247
381
  .to(dtype=torch.uint8)
248
382
  )
383
+ return sample.replace(image=shadowed_image)
249
384
  else:
250
- return random_shadow(x, self.opacity_range).clip(0, 1)
251
- except ValueError:
252
- return x
385
+ shadowed_image = random_shadow(sample.image, self.opacity_range).clip(0, 1)
386
+ return sample.replace(image=shadowed_image)
387
+ except ValueError: # pragma: no cover
388
+ return sample
253
389
 
254
390
  def extra_repr(self) -> str:
255
391
  return f"opacity_range={self.opacity_range}"
@@ -260,8 +396,9 @@ class RandomResize(torch.nn.Module):
260
396
 
261
397
  >>> import torch
262
398
  >>> from doctr.transforms import RandomResize
399
+ >>> from doctr.utils import Sample
263
400
  >>> transfo = RandomResize((0.3, 0.9), preserve_aspect_ratio=True, symmetric_pad=True, p=0.5)
264
- >>> out = transfo(torch.rand((3, 64, 64)))
401
+ >>> out = transfo(Sample(image=torch.rand((3, 64, 64))))
265
402
 
266
403
  Args:
267
404
  scale_range: range of the resizing factor for width and height (independently)
@@ -286,24 +423,26 @@ class RandomResize(torch.nn.Module):
286
423
  self.p = p
287
424
  self._resize = Resize
288
425
 
289
- def forward(self, img: torch.Tensor, target: np.ndarray) -> tuple[torch.Tensor, np.ndarray]:
426
+ def forward(
427
+ self,
428
+ sample: Sample,
429
+ ) -> Sample:
290
430
  if torch.rand(1) < self.p:
291
431
  scale_h = np.random.uniform(*self.scale_range)
292
432
  scale_w = np.random.uniform(*self.scale_range)
293
- new_size = (int(img.shape[-2] * scale_h), int(img.shape[-1] * scale_w))
433
+ new_size = (int(sample.image.shape[-2] * scale_h), int(sample.image.shape[-1] * scale_w))
294
434
 
295
- _img, _target = self._resize(
435
+ res = self._resize(
296
436
  new_size,
297
437
  preserve_aspect_ratio=self.preserve_aspect_ratio
298
438
  if isinstance(self.preserve_aspect_ratio, bool)
299
- else bool(torch.rand(1) <= self.symmetric_pad),
439
+ else bool(torch.rand(1) <= self.preserve_aspect_ratio),
300
440
  symmetric_pad=self.symmetric_pad
301
441
  if isinstance(self.symmetric_pad, bool)
302
442
  else bool(torch.rand(1) <= self.symmetric_pad),
303
- )(img, target)
304
-
305
- return _img, _target
306
- return img, target
443
+ )(sample)
444
+ return res
445
+ return sample
307
446
 
308
447
  def extra_repr(self) -> str:
309
448
  return f"scale_range={self.scale_range}, preserve_aspect_ratio={self.preserve_aspect_ratio}, symmetric_pad={self.symmetric_pad}, p={self.p}" # noqa: E501
@@ -1,11 +1,15 @@
1
- # Copyright (C) 2021-2025, Mindee.
1
+ # Copyright (C) 2021-2026, Mindee.
2
2
 
3
3
  # This program is licensed under the Apache License 2.0.
4
4
  # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
5
 
6
+ from 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
@@ -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.
@@ -9,7 +9,6 @@ import hashlib
9
9
  import logging
10
10
  import os
11
11
  import re
12
- import urllib
13
12
  import urllib.error
14
13
  import urllib.request
15
14
  from pathlib import Path
@@ -18,6 +17,8 @@ from tqdm.auto import tqdm
18
17
 
19
18
  __all__ = ["download_from_url"]
20
19
 
20
+ logger = logging.getLogger(__name__)
21
+
21
22
 
22
23
  # matches bfd8deac from resnet18-bfd8deac.ckpt
23
24
  HASH_REGEX = re.compile(r"-([a-f0-9]*)\.")
@@ -85,7 +86,7 @@ def download_from_url(
85
86
  file_path = folder_path.joinpath(file_name)
86
87
  # Check file existence
87
88
  if file_path.is_file() and (hash_prefix is None or _check_integrity(file_path, hash_prefix)):
88
- logging.info(f"Using downloaded & verified file: {file_path}")
89
+ logger.info(f"Using downloaded & verified file: {file_path}")
89
90
  return file_path
90
91
 
91
92
  try:
@@ -99,7 +100,7 @@ def download_from_url(
99
100
  error_message += (
100
101
  ". You can change default cache directory using 'DOCTR_CACHE_DIR' environment variable if needed."
101
102
  )
102
- logging.error(error_message)
103
+ logger.error(error_message)
103
104
  raise
104
105
  # Download the file
105
106
  try:
doctr/utils/fonts.py CHANGED
@@ -1,38 +1,77 @@
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
6
  import logging
7
7
  import platform
8
+ from functools import lru_cache
8
9
 
9
10
  from PIL import ImageFont
10
11
 
11
12
  __all__ = ["get_font"]
12
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
+ @lru_cache(maxsize=1)
38
+ def _resolve_default_font_family() -> str | None:
39
+ """Find the first available candidate font for this platform."""
40
+ candidates = _FONT_CANDIDATES.get(platform.system(), _FONT_CANDIDATES["Linux"])
41
+ for family in candidates:
42
+ try:
43
+ ImageFont.truetype(family, 10)
44
+ return family
45
+ except OSError:
46
+ continue
47
+ return None
48
+
13
49
 
14
50
  def get_font(font_family: str | None = None, font_size: int = 13) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
15
51
  """Resolves a compatible ImageFont for the system
16
52
 
17
53
  Args:
18
- font_family: the font family to use
54
+ font_family: the font family (or path to a font file) to use. If None,
55
+ the best available system font is picked automatically.
19
56
  font_size: the size of the font upon rendering
20
57
 
21
58
  Returns:
22
59
  the Pillow font
23
60
  """
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
61
+ if font_family is not None:
62
+ return ImageFont.truetype(font_family, font_size)
63
+
64
+ default_family = _resolve_default_font_family()
65
+ if default_family is not None:
66
+ return ImageFont.truetype(default_family, font_size)
67
+
68
+ # Last resort: Pillow's built-in font.
69
+ try:
70
+ return ImageFont.load_default(size=font_size)
71
+ except TypeError: # pragma: no cover
72
+ logger.warning(
73
+ "Unable to load any recommended font family. Loading default PIL font, "
74
+ "font size issues may be expected. "
75
+ "To prevent this, it is recommended to specify the value of 'font_family'."
76
+ )
77
+ return ImageFont.load_default()