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.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +506 -0
- doctr/contrib/artefacts.py +1 -1
- doctr/contrib/base.py +1 -1
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +5 -3
- doctr/datasets/cord.py +3 -2
- doctr/datasets/datasets/base.py +13 -25
- doctr/datasets/datasets/pytorch.py +15 -5
- doctr/datasets/detection.py +3 -2
- doctr/datasets/doc_artefacts.py +3 -2
- doctr/datasets/funsd.py +3 -2
- doctr/datasets/generator/base.py +6 -5
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +4 -3
- doctr/datasets/ic13.py +5 -3
- doctr/datasets/iiit5k.py +3 -2
- doctr/datasets/iiithws.py +5 -3
- doctr/datasets/imgur5k.py +5 -3
- doctr/datasets/layout.py +123 -0
- doctr/datasets/mjsynth.py +5 -3
- doctr/datasets/ocr.py +3 -2
- doctr/datasets/orientation.py +3 -2
- doctr/datasets/recognition.py +3 -2
- doctr/datasets/sroie.py +3 -2
- doctr/datasets/svhn.py +3 -2
- doctr/datasets/svt.py +4 -3
- doctr/datasets/synthtext.py +3 -2
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +15 -6
- doctr/datasets/vocabs.py +3 -1
- doctr/datasets/wildreceipt.py +5 -3
- doctr/file_utils.py +4 -2
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +253 -261
- doctr/io/exporters.py +1275 -0
- doctr/io/html.py +1 -1
- doctr/io/image/base.py +4 -3
- doctr/io/image/pytorch.py +6 -4
- doctr/io/pdf.py +1 -1
- doctr/io/reader.py +1 -1
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +111 -25
- doctr/models/builder.py +533 -62
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +2 -2
- doctr/models/classification/mobilenet/pytorch.py +7 -7
- doctr/models/classification/predictor/pytorch.py +7 -3
- doctr/models/classification/resnet/pytorch.py +6 -6
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +7 -6
- doctr/models/classification/vgg/pytorch.py +4 -3
- doctr/models/classification/vip/layers/pytorch.py +5 -5
- doctr/models/classification/vip/pytorch.py +5 -5
- doctr/models/classification/vit/pytorch.py +4 -4
- doctr/models/classification/vit_det/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/__init__.py +1 -0
- doctr/models/classification/vit_det/layers/pytorch.py +215 -0
- doctr/models/classification/vit_det/pytorch.py +346 -0
- doctr/models/classification/zoo.py +4 -1
- doctr/models/core.py +1 -1
- doctr/models/detection/_utils/base.py +24 -8
- doctr/models/detection/_utils/pytorch.py +1 -1
- doctr/models/detection/core.py +34 -19
- doctr/models/detection/differentiable_binarization/base.py +7 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
- doctr/models/detection/fast/base.py +6 -2
- doctr/models/detection/fast/pytorch.py +4 -4
- doctr/models/detection/linknet/base.py +6 -2
- doctr/models/detection/linknet/pytorch.py +4 -4
- doctr/models/detection/predictor/pytorch.py +4 -3
- doctr/models/detection/zoo.py +3 -3
- doctr/models/factory/hub.py +72 -52
- doctr/models/kie_predictor/base.py +17 -2
- doctr/models/kie_predictor/pytorch.py +42 -11
- doctr/models/layout/__init__.py +2 -0
- doctr/models/layout/lw_detr/__init__.py +1 -0
- doctr/models/layout/lw_detr/base.py +309 -0
- doctr/models/layout/lw_detr/layers/__init__.py +1 -0
- doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
- doctr/models/layout/lw_detr/pytorch.py +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +140 -4
- doctr/models/modules/transformer/pytorch.py +1 -1
- doctr/models/modules/vision_transformer/pytorch.py +1 -1
- doctr/models/predictor/base.py +138 -16
- doctr/models/predictor/pytorch.py +151 -9
- doctr/models/preprocessor/pytorch.py +78 -23
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/core.py +1 -1
- doctr/models/recognition/crnn/pytorch.py +6 -8
- doctr/models/recognition/master/base.py +1 -1
- doctr/models/recognition/master/pytorch.py +7 -8
- doctr/models/recognition/parseq/base.py +1 -1
- doctr/models/recognition/parseq/pytorch.py +5 -5
- doctr/models/recognition/predictor/_utils.py +1 -1
- doctr/models/recognition/predictor/pytorch.py +2 -2
- doctr/models/recognition/sar/pytorch.py +2 -2
- doctr/models/recognition/utils.py +9 -11
- doctr/models/recognition/viptr/pytorch.py +4 -6
- doctr/models/recognition/vitstr/base.py +1 -1
- doctr/models/recognition/vitstr/pytorch.py +6 -6
- doctr/models/recognition/zoo.py +6 -7
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +316 -16
- doctr/models/zoo.py +91 -3
- doctr/transforms/functional/base.py +3 -2
- doctr/transforms/functional/pytorch.py +1 -1
- doctr/transforms/modules/base.py +248 -83
- doctr/transforms/modules/pytorch.py +213 -74
- doctr/utils/common_types.py +22 -2
- doctr/utils/data.py +5 -4
- doctr/utils/fonts.py +56 -17
- doctr/utils/geometry.py +136 -19
- doctr/utils/metrics.py +351 -19
- doctr/utils/multithreading.py +6 -3
- doctr/utils/reconstitution.py +697 -133
- doctr/utils/repr.py +1 -1
- doctr/utils/visualization.py +63 -4
- doctr/version.py +1 -1
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.0.dist-info/RECORD +0 -149
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {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-
|
|
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
|
-
|
|
60
|
-
|
|
61
|
-
|
|
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
|
-
|
|
70
|
-
|
|
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 =
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
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,
|
|
145
|
-
|
|
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
|
-
|
|
251
|
+
image = (x + 255 * noise).round().clamp(0, 255).to(dtype=torch.uint8)
|
|
149
252
|
else:
|
|
150
|
-
|
|
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,
|
|
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
|
-
|
|
284
|
+
sample.image.numpy(),
|
|
179
285
|
sigma=sigma,
|
|
180
286
|
mode="reflect",
|
|
181
287
|
truncate=4.0,
|
|
182
288
|
),
|
|
183
|
-
dtype=
|
|
184
|
-
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,
|
|
308
|
+
def forward(self, sample: Sample) -> Sample:
|
|
196
309
|
# Get a random order
|
|
197
|
-
chan_order = torch.rand(
|
|
198
|
-
return
|
|
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
|
|
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
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
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,
|
|
367
|
+
def __call__(self, sample: Sample) -> Sample:
|
|
234
368
|
# Reshape the distribution
|
|
235
369
|
try:
|
|
236
|
-
if
|
|
237
|
-
|
|
370
|
+
if sample.image.dtype == torch.uint8:
|
|
371
|
+
shadowed_image = (
|
|
238
372
|
(
|
|
239
373
|
255
|
|
240
374
|
* random_shadow(
|
|
241
|
-
|
|
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
|
-
|
|
251
|
-
|
|
252
|
-
|
|
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(
|
|
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(
|
|
433
|
+
new_size = (int(sample.image.shape[-2] * scale_h), int(sample.image.shape[-1] * scale_w))
|
|
294
434
|
|
|
295
|
-
|
|
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.
|
|
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
|
-
)(
|
|
304
|
-
|
|
305
|
-
|
|
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
|
doctr/utils/common_types.py
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
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
|
-
|
|
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-
|
|
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
|
-
|
|
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
|
-
|
|
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-
|
|
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
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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()
|