python-doctr 1.1.0__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.
- doctr/cli/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- doctr/models/formula/__init__.py +2 -0
- doctr/models/formula/formulanet/__init__.py +2 -0
- doctr/models/formula/formulanet/base.py +70 -0
- doctr/models/formula/formulanet/pytorch.py +587 -0
- doctr/models/formula/predictor/__init__.py +1 -0
- doctr/models/formula/predictor/pytorch.py +132 -0
- doctr/models/formula/zoo.py +102 -0
- doctr/models/kie_predictor/base.py +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
|
+
|
|
3
|
+
# This program is licensed under the Apache License 2.0.
|
|
4
|
+
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
|
+
|
|
6
|
+
# Credits: architecture of PP-HGNetV2 from PaddleClas / PaddleOCR (https://github.com/PaddlePaddle/PaddleOCR,
|
|
7
|
+
# Apache 2.0), as also used by D-FINE (https://github.com/Peterande/D-FINE, Apache 2.0).
|
|
8
|
+
|
|
9
|
+
from copy import deepcopy
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
import torch
|
|
13
|
+
from torch import nn
|
|
14
|
+
from torch.nn import functional as F
|
|
15
|
+
|
|
16
|
+
from doctr.datasets import VOCABS
|
|
17
|
+
|
|
18
|
+
from ...modules.layers import DropPath
|
|
19
|
+
from ...utils import load_pretrained_params
|
|
20
|
+
|
|
21
|
+
__all__ = ["HGNetV2", "hgnetv2_b4"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
default_cfgs: dict[str, dict[str, Any]] = {
|
|
25
|
+
"hgnetv2_b4": {
|
|
26
|
+
"mean": (0.694, 0.695, 0.693),
|
|
27
|
+
"std": (0.299, 0.296, 0.301),
|
|
28
|
+
"input_shape": (3, 32, 32),
|
|
29
|
+
"classes": list(VOCABS["french"]),
|
|
30
|
+
"url": "https://github.com/mindee/doctr/releases/download/v1.1.0/hgnetv2_b4-0f90b8d0.pt",
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class ConvBNAct(nn.Sequential):
|
|
36
|
+
"""A convolution (without bias) followed by batch-norm and an optional ReLU
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
in_channels: number of input channels
|
|
40
|
+
out_channels: number of output channels
|
|
41
|
+
kernel_size: size of the convolution kernel
|
|
42
|
+
stride: stride of the convolution
|
|
43
|
+
groups: number of groups of the convolution
|
|
44
|
+
use_act: whether to add the ReLU activation
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
in_channels: int,
|
|
50
|
+
out_channels: int,
|
|
51
|
+
kernel_size: int = 3,
|
|
52
|
+
stride: int = 1,
|
|
53
|
+
groups: int = 1,
|
|
54
|
+
use_act: bool = True,
|
|
55
|
+
) -> None:
|
|
56
|
+
layers: list[nn.Module] = [
|
|
57
|
+
nn.Conv2d(
|
|
58
|
+
in_channels,
|
|
59
|
+
out_channels,
|
|
60
|
+
kernel_size,
|
|
61
|
+
stride=stride,
|
|
62
|
+
padding=(kernel_size - 1) // 2,
|
|
63
|
+
groups=groups,
|
|
64
|
+
bias=False,
|
|
65
|
+
),
|
|
66
|
+
nn.BatchNorm2d(out_channels),
|
|
67
|
+
]
|
|
68
|
+
if use_act:
|
|
69
|
+
layers.append(nn.ReLU(inplace=True))
|
|
70
|
+
super().__init__(*layers)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class LightConvBNAct(nn.Sequential):
|
|
74
|
+
"""A point-wise convolution followed by a depth-wise convolution
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
in_channels: number of input channels
|
|
78
|
+
out_channels: number of output channels
|
|
79
|
+
kernel_size: size of the depth-wise convolution kernel
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(self, in_channels: int, out_channels: int, kernel_size: int) -> None:
|
|
83
|
+
super().__init__(
|
|
84
|
+
ConvBNAct(in_channels, out_channels, kernel_size=1, use_act=False),
|
|
85
|
+
ConvBNAct(out_channels, out_channels, kernel_size=kernel_size, groups=out_channels),
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class StemBlock(nn.Module):
|
|
90
|
+
"""Stem of HGNetV2 (stride 4): a strided convolution, then a two-branch (convolutions | max-pooling) block
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
in_channels: number of input channels
|
|
94
|
+
mid_channels: number of intermediate channels
|
|
95
|
+
out_channels: number of output channels
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None:
|
|
99
|
+
super().__init__()
|
|
100
|
+
self.stem1 = ConvBNAct(in_channels, mid_channels, kernel_size=3, stride=2)
|
|
101
|
+
# 2x2 kernels, padded on the bottom-right to keep the resolution
|
|
102
|
+
self.stem2a = nn.Sequential(
|
|
103
|
+
nn.Conv2d(mid_channels, mid_channels // 2, 2, bias=False), nn.BatchNorm2d(mid_channels // 2), nn.ReLU(True)
|
|
104
|
+
)
|
|
105
|
+
self.stem2b = nn.Sequential(
|
|
106
|
+
nn.Conv2d(mid_channels // 2, mid_channels, 2, bias=False), nn.BatchNorm2d(mid_channels), nn.ReLU(True)
|
|
107
|
+
)
|
|
108
|
+
self.pool = nn.MaxPool2d(kernel_size=2, stride=1, ceil_mode=True)
|
|
109
|
+
self.stem3 = ConvBNAct(mid_channels * 2, mid_channels, kernel_size=3, stride=2)
|
|
110
|
+
self.stem4 = ConvBNAct(mid_channels, out_channels, kernel_size=1)
|
|
111
|
+
|
|
112
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
113
|
+
x = F.pad(self.stem1(x), (0, 1, 0, 1))
|
|
114
|
+
x2 = self.stem2b(F.pad(self.stem2a(x), (0, 1, 0, 1)))
|
|
115
|
+
x1 = self.pool(x)
|
|
116
|
+
return self.stem4(self.stem3(torch.cat([x1, x2], dim=1)))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class HGBlock(nn.Module):
|
|
120
|
+
"""HGNetV2 block: a chain of convolutions whose outputs are all concatenated (with the input) and aggregated by
|
|
121
|
+
point-wise convolutions, with an optional residual connection
|
|
122
|
+
|
|
123
|
+
Args:
|
|
124
|
+
in_channels: number of input channels
|
|
125
|
+
mid_channels: number of channels of each convolution of the chain
|
|
126
|
+
out_channels: number of output channels
|
|
127
|
+
layer_num: number of convolutions in the chain
|
|
128
|
+
kernel_size: size of the convolution kernels
|
|
129
|
+
residual: whether to add a residual connection
|
|
130
|
+
light_block: whether to use light (point-wise + depth-wise) convolutions
|
|
131
|
+
drop_path: stochastic depth rate of the residual branch
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
def __init__(
|
|
135
|
+
self,
|
|
136
|
+
in_channels: int,
|
|
137
|
+
mid_channels: int,
|
|
138
|
+
out_channels: int,
|
|
139
|
+
layer_num: int,
|
|
140
|
+
kernel_size: int = 3,
|
|
141
|
+
residual: bool = False,
|
|
142
|
+
light_block: bool = False,
|
|
143
|
+
drop_path: float = 0.0,
|
|
144
|
+
) -> None:
|
|
145
|
+
super().__init__()
|
|
146
|
+
self.residual = residual
|
|
147
|
+
self.layers = nn.ModuleList([
|
|
148
|
+
(LightConvBNAct if light_block else ConvBNAct)(
|
|
149
|
+
in_channels if idx == 0 else mid_channels, mid_channels, kernel_size=kernel_size
|
|
150
|
+
)
|
|
151
|
+
for idx in range(layer_num)
|
|
152
|
+
])
|
|
153
|
+
total_channels = in_channels + layer_num * mid_channels
|
|
154
|
+
self.aggregation = nn.Sequential(
|
|
155
|
+
ConvBNAct(total_channels, out_channels // 2, kernel_size=1),
|
|
156
|
+
ConvBNAct(out_channels // 2, out_channels, kernel_size=1),
|
|
157
|
+
)
|
|
158
|
+
self.drop_path = DropPath(drop_path) if drop_path > 0 else nn.Identity()
|
|
159
|
+
|
|
160
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
161
|
+
identity = x
|
|
162
|
+
outputs = [x]
|
|
163
|
+
for layer in self.layers:
|
|
164
|
+
x = layer(x)
|
|
165
|
+
outputs.append(x)
|
|
166
|
+
x = self.aggregation(torch.cat(outputs, dim=1))
|
|
167
|
+
return self.drop_path(x) + identity if self.residual else x
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class HGStage(nn.Sequential):
|
|
171
|
+
"""HGNetV2 stage: an optional depth-wise strided convolution, then a sequence of HGBlocks
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
in_channels: number of input channels
|
|
175
|
+
mid_channels: number of channels of the convolutions of the blocks
|
|
176
|
+
out_channels: number of output channels
|
|
177
|
+
num_blocks: number of blocks
|
|
178
|
+
downsample: whether to downsample the input by 2 first
|
|
179
|
+
light_block: whether the blocks use light convolutions
|
|
180
|
+
kernel_size: size of the convolution kernels of the blocks
|
|
181
|
+
layer_num: number of convolutions per block
|
|
182
|
+
drop_path: stochastic depth rate of each block
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
def __init__(
|
|
186
|
+
self,
|
|
187
|
+
in_channels: int,
|
|
188
|
+
mid_channels: int,
|
|
189
|
+
out_channels: int,
|
|
190
|
+
num_blocks: int,
|
|
191
|
+
downsample: bool,
|
|
192
|
+
light_block: bool,
|
|
193
|
+
kernel_size: int,
|
|
194
|
+
layer_num: int,
|
|
195
|
+
drop_path: list[float],
|
|
196
|
+
) -> None:
|
|
197
|
+
super().__init__(
|
|
198
|
+
ConvBNAct(in_channels, in_channels, kernel_size=3, stride=2, groups=in_channels, use_act=False)
|
|
199
|
+
if downsample
|
|
200
|
+
else nn.Identity(),
|
|
201
|
+
*[
|
|
202
|
+
HGBlock(
|
|
203
|
+
in_channels if idx == 0 else out_channels,
|
|
204
|
+
mid_channels,
|
|
205
|
+
out_channels,
|
|
206
|
+
layer_num,
|
|
207
|
+
kernel_size=kernel_size,
|
|
208
|
+
residual=idx > 0,
|
|
209
|
+
light_block=light_block,
|
|
210
|
+
drop_path=drop_path[idx],
|
|
211
|
+
)
|
|
212
|
+
for idx in range(num_blocks)
|
|
213
|
+
],
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class HGNetV2(nn.Sequential):
|
|
218
|
+
"""Implements the HGNetV2 architecture from PaddlePaddle's `PP-HGNetV2
|
|
219
|
+
<https://github.com/PaddlePaddle/PaddleClas/blob/release/2.6/docs/en/models/PP-HGNetV2_en.md>`_.
|
|
220
|
+
|
|
221
|
+
The model is a stem (stride 4) followed by 4 stages (strides 4, 8, 16 and 32).
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
stem_channels: the input, intermediate and output channels of the stem
|
|
225
|
+
stages: the configuration of each stage `(in_channels, mid_channels, out_channels, num_blocks, downsample,
|
|
226
|
+
light_block, kernel_size, layer_num)`
|
|
227
|
+
drop_path_rate: maximum stochastic depth rate (linearly scaled across blocks)
|
|
228
|
+
num_classes: number of output classes of the classification head
|
|
229
|
+
include_top: whether to add the classification head
|
|
230
|
+
cfg: the configuration dict of the model
|
|
231
|
+
"""
|
|
232
|
+
|
|
233
|
+
def __init__(
|
|
234
|
+
self,
|
|
235
|
+
stem_channels: tuple[int, int, int],
|
|
236
|
+
stages: list[tuple[int, int, int, int, bool, bool, int, int]],
|
|
237
|
+
drop_path_rate: float = 0.0,
|
|
238
|
+
num_classes: int = 1000,
|
|
239
|
+
include_top: bool = True,
|
|
240
|
+
cfg: dict[str, Any] | None = None,
|
|
241
|
+
) -> None:
|
|
242
|
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(stage[3] for stage in stages))]
|
|
243
|
+
_layers: list[nn.Module] = [StemBlock(*stem_channels)]
|
|
244
|
+
cur = 0
|
|
245
|
+
for in_ch, mid_ch, out_ch, num_blocks, downsample, light_block, kernel_size, layer_num in stages:
|
|
246
|
+
_layers.append(
|
|
247
|
+
HGStage(
|
|
248
|
+
in_ch,
|
|
249
|
+
mid_ch,
|
|
250
|
+
out_ch,
|
|
251
|
+
num_blocks,
|
|
252
|
+
downsample,
|
|
253
|
+
light_block,
|
|
254
|
+
kernel_size,
|
|
255
|
+
layer_num,
|
|
256
|
+
dpr[cur : cur + num_blocks],
|
|
257
|
+
)
|
|
258
|
+
)
|
|
259
|
+
cur += num_blocks
|
|
260
|
+
|
|
261
|
+
if include_top:
|
|
262
|
+
_layers.append(
|
|
263
|
+
nn.Sequential(
|
|
264
|
+
nn.AdaptiveAvgPool2d(1),
|
|
265
|
+
nn.Flatten(1),
|
|
266
|
+
nn.Linear(stages[-1][2], num_classes),
|
|
267
|
+
)
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
super().__init__(*_layers)
|
|
271
|
+
# Output channels of the stem and of each stage
|
|
272
|
+
self.channels = [stem_channels[2], *(stage[2] for stage in stages)]
|
|
273
|
+
self.cfg = cfg
|
|
274
|
+
|
|
275
|
+
for m in self.modules():
|
|
276
|
+
if isinstance(m, nn.Conv2d):
|
|
277
|
+
nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
|
|
278
|
+
elif isinstance(m, nn.BatchNorm2d):
|
|
279
|
+
nn.init.ones_(m.weight)
|
|
280
|
+
nn.init.zeros_(m.bias)
|
|
281
|
+
elif isinstance(m, nn.Linear):
|
|
282
|
+
nn.init.trunc_normal_(m.weight, std=0.02)
|
|
283
|
+
nn.init.zeros_(m.bias)
|
|
284
|
+
|
|
285
|
+
def from_pretrained(self, path_or_url: str, **kwargs: Any) -> None:
|
|
286
|
+
"""Load pretrained parameters onto the model
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
path_or_url: the path or URL to the model parameters (checkpoint)
|
|
290
|
+
**kwargs: additional arguments to be passed to `doctr.models.utils.load_pretrained_params`
|
|
291
|
+
"""
|
|
292
|
+
load_pretrained_params(self, path_or_url, **kwargs)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _hgnetv2(
|
|
296
|
+
arch: str,
|
|
297
|
+
pretrained: bool,
|
|
298
|
+
ignore_keys: list[str] | None = None,
|
|
299
|
+
**kwargs: Any,
|
|
300
|
+
) -> HGNetV2:
|
|
301
|
+
kwargs["num_classes"] = kwargs.get("num_classes", len(default_cfgs[arch]["classes"]))
|
|
302
|
+
kwargs["classes"] = kwargs.get("classes", default_cfgs[arch]["classes"])
|
|
303
|
+
|
|
304
|
+
_cfg = deepcopy(default_cfgs[arch])
|
|
305
|
+
_cfg["num_classes"] = kwargs["num_classes"]
|
|
306
|
+
_cfg["classes"] = kwargs["classes"]
|
|
307
|
+
kwargs.pop("classes")
|
|
308
|
+
|
|
309
|
+
# Build the model
|
|
310
|
+
model = HGNetV2(**kwargs)
|
|
311
|
+
# Load pretrained parameters
|
|
312
|
+
if pretrained:
|
|
313
|
+
# The number of classes is not the same as the number of classes in the pretrained model =>
|
|
314
|
+
# remove the last layer weights
|
|
315
|
+
_ignore_keys = ignore_keys if kwargs["num_classes"] != len(default_cfgs[arch]["classes"]) else None
|
|
316
|
+
model.from_pretrained(default_cfgs[arch]["url"], ignore_keys=_ignore_keys)
|
|
317
|
+
|
|
318
|
+
model.cfg = _cfg
|
|
319
|
+
|
|
320
|
+
return model
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def hgnetv2_b4(pretrained: bool = False, **kwargs: Any) -> HGNetV2:
|
|
324
|
+
"""HGNetV2-B4 from PaddlePaddle's `PP-HGNetV2
|
|
325
|
+
<https://github.com/PaddlePaddle/PaddleClas/blob/release/2.6/docs/en/models/PP-HGNetV2_en.md>`_.
|
|
326
|
+
|
|
327
|
+
>>> import torch
|
|
328
|
+
>>> from doctr.models import hgnetv2_b4
|
|
329
|
+
>>> model = hgnetv2_b4(pretrained=False)
|
|
330
|
+
>>> input_tensor = torch.rand((1, 3, 32, 32), dtype=torch.float32)
|
|
331
|
+
>>> out = model(input_tensor)
|
|
332
|
+
|
|
333
|
+
Args:
|
|
334
|
+
pretrained: boolean, True if model is pretrained
|
|
335
|
+
**kwargs: keyword arguments of the HGNetV2 architecture
|
|
336
|
+
|
|
337
|
+
Returns:
|
|
338
|
+
A HGNetV2-B4 model
|
|
339
|
+
"""
|
|
340
|
+
return _hgnetv2(
|
|
341
|
+
"hgnetv2_b4",
|
|
342
|
+
pretrained,
|
|
343
|
+
stem_channels=(3, 32, 48),
|
|
344
|
+
stages=[
|
|
345
|
+
(48, 48, 128, 1, False, False, 3, 6),
|
|
346
|
+
(128, 96, 512, 1, True, False, 3, 6),
|
|
347
|
+
(512, 192, 1024, 3, True, True, 5, 6),
|
|
348
|
+
(1024, 384, 2048, 1, True, True, 5, 6),
|
|
349
|
+
],
|
|
350
|
+
ignore_keys=["5.2.weight", "5.2.bias"],
|
|
351
|
+
**kwargs,
|
|
352
|
+
)
|
|
@@ -4,10 +4,13 @@
|
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
6
|
|
|
7
|
+
from collections.abc import Iterable, Sequence
|
|
8
|
+
|
|
7
9
|
import numpy as np
|
|
8
10
|
import torch
|
|
9
11
|
from torch import nn
|
|
10
12
|
|
|
13
|
+
from doctr.models._utils import merge_columns, predict_by_chunks
|
|
11
14
|
from doctr.models.preprocessor import PreProcessor
|
|
12
15
|
from doctr.models.utils import set_device_and_dtype
|
|
13
16
|
|
|
@@ -21,19 +24,44 @@ class OrientationPredictor(nn.Module):
|
|
|
21
24
|
Args:
|
|
22
25
|
pre_processor: transform inputs for easier batched model inference
|
|
23
26
|
model: core classification architecture (backbone + classification head)
|
|
27
|
+
chunk_size: the maximum number of images decoded and processed at once (32 by default). Longer
|
|
28
|
+
inputs, lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) and iterators are processed
|
|
29
|
+
chunk by chunk, with a memory footprint that does not grow with the number of images. It is rounded
|
|
30
|
+
up to a multiple of the batch size, so that the predictions are the same as in a single pass.
|
|
24
31
|
"""
|
|
25
32
|
|
|
26
33
|
def __init__(
|
|
27
34
|
self,
|
|
28
35
|
pre_processor: PreProcessor | None,
|
|
29
36
|
model: nn.Module | None,
|
|
37
|
+
chunk_size: int = 32,
|
|
30
38
|
) -> None:
|
|
31
39
|
super().__init__()
|
|
40
|
+
if chunk_size < 1:
|
|
41
|
+
raise ValueError("`chunk_size` must be a positive integer")
|
|
42
|
+
self.chunk_size = chunk_size
|
|
32
43
|
self.pre_processor = pre_processor if isinstance(pre_processor, PreProcessor) else None
|
|
33
44
|
self.model = model.eval() if isinstance(model, nn.Module) else None
|
|
34
45
|
|
|
35
46
|
@torch.inference_mode()
|
|
36
47
|
def forward(
|
|
48
|
+
self,
|
|
49
|
+
inputs: Sequence[np.ndarray] | Iterable[np.ndarray],
|
|
50
|
+
) -> list[list[int] | list[float]]:
|
|
51
|
+
"""Classify the orientation of pages or crops
|
|
52
|
+
|
|
53
|
+
Args:
|
|
54
|
+
inputs: a list of images (numpy arrays of shape H x W x C), a lazy page source
|
|
55
|
+
(cf. `DocumentFile.from_pdf(..., lazy=True)`) or any iterable of images
|
|
56
|
+
|
|
57
|
+
Returns:
|
|
58
|
+
the lists of class indices, orientation angles and confidences, aligned with the inputs
|
|
59
|
+
"""
|
|
60
|
+
batch_size = self.pre_processor.batch_size if self.pre_processor is not None else 1
|
|
61
|
+
return predict_by_chunks(self._predict, inputs, self.chunk_size, batch_size, merge=merge_columns)
|
|
62
|
+
|
|
63
|
+
@torch.inference_mode()
|
|
64
|
+
def _predict(
|
|
37
65
|
self,
|
|
38
66
|
inputs: list[np.ndarray],
|
|
39
67
|
) -> list[list[int] | list[float]]:
|
|
@@ -35,6 +35,7 @@ ARCHS: list[str] = [
|
|
|
35
35
|
"vit_det_s",
|
|
36
36
|
"vit_det_m",
|
|
37
37
|
"starnet_s3",
|
|
38
|
+
"hgnetv2_b4",
|
|
38
39
|
]
|
|
39
40
|
|
|
40
41
|
ORIENTATION_ARCHS: list[str] = ["mobilenet_v3_small_crop_orientation", "mobilenet_v3_small_page_orientation"]
|
|
@@ -45,7 +46,7 @@ def _orientation_predictor(
|
|
|
45
46
|
) -> OrientationPredictor:
|
|
46
47
|
if disabled:
|
|
47
48
|
# Case where the orientation predictor is disabled
|
|
48
|
-
return OrientationPredictor(None, None)
|
|
49
|
+
return OrientationPredictor(None, None, chunk_size=kwargs.get("chunk_size", 32))
|
|
49
50
|
|
|
50
51
|
if isinstance(arch, str):
|
|
51
52
|
if arch not in ORIENTATION_ARCHS:
|
|
@@ -64,9 +65,13 @@ def _orientation_predictor(
|
|
|
64
65
|
kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
|
|
65
66
|
kwargs["std"] = kwargs.get("std", _model.cfg["std"])
|
|
66
67
|
kwargs["batch_size"] = kwargs.get("batch_size", 128 if model_type == "crop" else 4)
|
|
68
|
+
# Crops are much smaller than pages: many more of them fit in memory at once
|
|
69
|
+
chunk_size = kwargs.pop("chunk_size", 1024 if model_type == "crop" else 32)
|
|
67
70
|
input_shape = _model.cfg["input_shape"][1:]
|
|
68
71
|
predictor = OrientationPredictor(
|
|
69
|
-
PreProcessor(input_shape, preserve_aspect_ratio=True, symmetric_pad=True, **kwargs),
|
|
72
|
+
PreProcessor(input_shape, preserve_aspect_ratio=True, symmetric_pad=True, **kwargs),
|
|
73
|
+
_model,
|
|
74
|
+
chunk_size=chunk_size,
|
|
70
75
|
)
|
|
71
76
|
return predictor
|
|
72
77
|
|
|
@@ -86,6 +91,8 @@ def crop_orientation_predictor(
|
|
|
86
91
|
arch: name of the architecture to use (e.g. 'mobilenet_v3_small_crop_orientation')
|
|
87
92
|
pretrained: If True, returns a model pre-trained on our recognition crops dataset
|
|
88
93
|
batch_size: number of samples the model processes in parallel
|
|
94
|
+
chunk_size: maximum number of crops decoded and processed at once (1024 by default): longer inputs and
|
|
95
|
+
lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
|
|
89
96
|
**kwargs: keyword arguments to be passed to the OrientationPredictor
|
|
90
97
|
|
|
91
98
|
Returns:
|
|
@@ -109,6 +116,8 @@ def page_orientation_predictor(
|
|
|
109
116
|
arch: name of the architecture to use (e.g. 'mobilenet_v3_small_page_orientation')
|
|
110
117
|
pretrained: If True, returns a model pre-trained on our recognition crops dataset
|
|
111
118
|
batch_size: number of samples the model processes in parallel
|
|
119
|
+
chunk_size: maximum number of pages decoded and processed at once (32 by default): longer inputs and
|
|
120
|
+
lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
|
|
112
121
|
**kwargs: keyword arguments to be passed to the OrientationPredictor
|
|
113
122
|
|
|
114
123
|
Returns:
|
doctr/models/detection/core.py
CHANGED
|
@@ -7,7 +7,6 @@
|
|
|
7
7
|
import cv2
|
|
8
8
|
import numpy as np
|
|
9
9
|
|
|
10
|
-
from doctr.utils.multithreading import multithread_exec
|
|
11
10
|
from doctr.utils.repr import NestedObject
|
|
12
11
|
|
|
13
12
|
__all__ = ["DetectionPostProcessor"]
|
|
@@ -107,4 +106,4 @@ class DetectionPostProcessor(NestedObject):
|
|
|
107
106
|
"""
|
|
108
107
|
if proba_map.ndim != 4:
|
|
109
108
|
raise AssertionError(f"arg `proba_map` is expected to be 4-dimensional, got {proba_map.ndim}.")
|
|
110
|
-
return
|
|
109
|
+
return [self._process_sample(sample) for sample in proba_map]
|
|
@@ -95,8 +95,6 @@ class DBPostProcessor(DetectionPostProcessor):
|
|
|
95
95
|
Args:
|
|
96
96
|
pred: Pred map from differentiable binarization output
|
|
97
97
|
bitmap: Bitmap map computed from pred (binarized)
|
|
98
|
-
angle_tol: Comparison tolerance of the angle with the median angle across the page
|
|
99
|
-
ratio_tol: Under this limit aspect ratio, we cannot resolve the direction of the crop
|
|
100
98
|
|
|
101
99
|
Returns:
|
|
102
100
|
np tensor boxes for the bitmap, each box is a 5-element list
|
|
@@ -168,6 +166,8 @@ class _DBNet:
|
|
|
168
166
|
thresh_max = 0.7
|
|
169
167
|
min_size_box = 3
|
|
170
168
|
assume_straight_pages: bool = True
|
|
169
|
+
mask_empty_classes: bool = False
|
|
170
|
+
class_names: list[str] # set by the framework model
|
|
171
171
|
|
|
172
172
|
@staticmethod
|
|
173
173
|
def compute_distance(
|
|
@@ -291,10 +291,22 @@ class _DBNet:
|
|
|
291
291
|
thresh_mask: np.ndarray = np.zeros(target_shape, dtype=np.uint8)
|
|
292
292
|
|
|
293
293
|
for idx, tgt in enumerate(target):
|
|
294
|
-
|
|
294
|
+
unknown = set(tgt) - set(self.class_names)
|
|
295
|
+
missing = set(self.class_names) - set(tgt)
|
|
296
|
+
if unknown or missing:
|
|
297
|
+
raise ValueError(
|
|
298
|
+
f"target classes {sorted(tgt)} do not match the model classes {list(self.class_names)}"
|
|
299
|
+
+ (f" (unknown: {sorted(unknown)})" if unknown else "")
|
|
300
|
+
+ (f" (missing: {sorted(missing)})" if missing else "")
|
|
301
|
+
)
|
|
302
|
+
# Channels follow the order of the model's class names, whatever the order of the target dict
|
|
303
|
+
for class_idx, class_name in enumerate(self.class_names):
|
|
304
|
+
_tgt = tgt[class_name]
|
|
295
305
|
# Draw each polygon on gt
|
|
296
|
-
if _tgt.shape[0] == 0:
|
|
297
|
-
#
|
|
306
|
+
if _tgt.shape[0] == 0 and self.mask_empty_classes:
|
|
307
|
+
# No box for this class: with `mask_empty_classes` the channel is ignored by the loss (partially
|
|
308
|
+
# annotated data); by default it is supervised as background, an image without any box being
|
|
309
|
+
# a true negative
|
|
298
310
|
seg_mask[idx, class_idx] = False
|
|
299
311
|
|
|
300
312
|
# Absolute bounding boxes
|
|
@@ -106,6 +106,8 @@ class DBNet(_DBNet, nn.Module):
|
|
|
106
106
|
exportable: onnx exportable returns only logits
|
|
107
107
|
cfg: the configuration dict of the model
|
|
108
108
|
class_names: list of class names
|
|
109
|
+
mask_empty_classes: if True, a class without any box in an image is masked out of the loss (use it for
|
|
110
|
+
partially annotated data); by default the absence is supervised as background
|
|
109
111
|
"""
|
|
110
112
|
|
|
111
113
|
def __init__(
|
|
@@ -119,9 +121,11 @@ class DBNet(_DBNet, nn.Module):
|
|
|
119
121
|
exportable: bool = False,
|
|
120
122
|
cfg: dict[str, Any] | None = None,
|
|
121
123
|
class_names: list[str] = [CLASS_NAME],
|
|
124
|
+
mask_empty_classes: bool = False,
|
|
122
125
|
) -> None:
|
|
123
126
|
super().__init__()
|
|
124
127
|
self.class_names = class_names
|
|
128
|
+
self.mask_empty_classes = mask_empty_classes
|
|
125
129
|
num_classes: int = len(self.class_names)
|
|
126
130
|
self.cfg = cfg
|
|
127
131
|
|
|
@@ -268,9 +272,11 @@ class DBNet(_DBNet, nn.Module):
|
|
|
268
272
|
thresh_target, thresh_mask = torch.from_numpy(targets[2]), torch.from_numpy(targets[3])
|
|
269
273
|
thresh_target, thresh_mask = thresh_target.to(out_map.device), thresh_mask.to(out_map.device)
|
|
270
274
|
|
|
275
|
+
# Every term defaults to a zero that keeps the graph, so a fully masked batch does not crash
|
|
276
|
+
focal_loss = dice_loss = l1_loss = out_map.sum() * 0
|
|
277
|
+
focal_scale = 10.0
|
|
271
278
|
if torch.any(seg_mask):
|
|
272
279
|
# Focal loss
|
|
273
|
-
focal_scale = 10.0
|
|
274
280
|
bce_loss = F.binary_cross_entropy_with_logits(out_map, seg_target, reduction="none")
|
|
275
281
|
|
|
276
282
|
p_t = prob_map * seg_target + (1 - prob_map) * (1 - seg_target)
|
|
@@ -92,8 +92,6 @@ class FASTPostProcessor(DetectionPostProcessor):
|
|
|
92
92
|
Args:
|
|
93
93
|
pred: Pred map from differentiable linknet output
|
|
94
94
|
bitmap: Bitmap map computed from pred (binarized)
|
|
95
|
-
angle_tol: Comparison tolerance of the angle with the median angle across the page
|
|
96
|
-
ratio_tol: Under this limit aspect ratio, we cannot resolve the direction of the crop
|
|
97
95
|
|
|
98
96
|
Returns:
|
|
99
97
|
np tensor boxes for the bitmap, each box is a 6-element list
|
|
@@ -150,6 +148,8 @@ class _FAST(BaseModel):
|
|
|
150
148
|
"""
|
|
151
149
|
|
|
152
150
|
min_size_box: int = 3
|
|
151
|
+
mask_empty_classes: bool = False
|
|
152
|
+
class_names: list[str] # set by the framework model
|
|
153
153
|
assume_straight_pages: bool = True
|
|
154
154
|
shrink_ratio = 0.4
|
|
155
155
|
|
|
@@ -183,10 +183,22 @@ class _FAST(BaseModel):
|
|
|
183
183
|
shrunken_kernel: np.ndarray = np.zeros(target_shape, dtype=np.uint8)
|
|
184
184
|
|
|
185
185
|
for idx, tgt in enumerate(target):
|
|
186
|
-
|
|
186
|
+
unknown = set(tgt) - set(self.class_names)
|
|
187
|
+
missing = set(self.class_names) - set(tgt)
|
|
188
|
+
if unknown or missing:
|
|
189
|
+
raise ValueError(
|
|
190
|
+
f"target classes {sorted(tgt)} do not match the model classes {list(self.class_names)}"
|
|
191
|
+
+ (f" (unknown: {sorted(unknown)})" if unknown else "")
|
|
192
|
+
+ (f" (missing: {sorted(missing)})" if missing else "")
|
|
193
|
+
)
|
|
194
|
+
# Channels follow the order of the model's class names, whatever the order of the target dict
|
|
195
|
+
for class_idx, class_name in enumerate(self.class_names):
|
|
196
|
+
_tgt = tgt[class_name]
|
|
187
197
|
# Draw each polygon on gt
|
|
188
|
-
if _tgt.shape[0] == 0:
|
|
189
|
-
#
|
|
198
|
+
if _tgt.shape[0] == 0 and self.mask_empty_classes:
|
|
199
|
+
# No box for this class: with `mask_empty_classes` the channel is ignored by the loss (partially
|
|
200
|
+
# annotated data); by default it is supervised as background, an image without any box being
|
|
201
|
+
# a true negative
|
|
190
202
|
seg_mask[idx, class_idx] = False
|
|
191
203
|
|
|
192
204
|
# Absolute bounding boxes
|
|
@@ -112,6 +112,8 @@ class FAST(_FAST, nn.Module):
|
|
|
112
112
|
exportable: onnx exportable returns only logits
|
|
113
113
|
cfg: the configuration dict of the model
|
|
114
114
|
class_names: list of class names
|
|
115
|
+
mask_empty_classes: if True, a class without any box in an image is masked out of the loss (use it for
|
|
116
|
+
partially annotated data); by default the absence is supervised as background
|
|
115
117
|
"""
|
|
116
118
|
|
|
117
119
|
def __init__(
|
|
@@ -125,9 +127,11 @@ class FAST(_FAST, nn.Module):
|
|
|
125
127
|
exportable: bool = False,
|
|
126
128
|
cfg: dict[str, Any] = {},
|
|
127
129
|
class_names: list[str] = [CLASS_NAME],
|
|
130
|
+
mask_empty_classes: bool = False,
|
|
128
131
|
) -> None:
|
|
129
132
|
super().__init__()
|
|
130
133
|
self.class_names = class_names
|
|
134
|
+
self.mask_empty_classes = mask_empty_classes
|
|
131
135
|
num_classes: int = len(self.class_names)
|
|
132
136
|
self.cfg = cfg
|
|
133
137
|
|
|
@@ -265,12 +269,13 @@ class FAST(_FAST, nn.Module):
|
|
|
265
269
|
# combine all masks to shape (len(masks), H, W)
|
|
266
270
|
return torch.stack(masks).unsqueeze(0).float()
|
|
267
271
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
272
|
+
pooled_logits = self.pooling(out_map)
|
|
273
|
+
kernels = torch.sigmoid(out_map)
|
|
274
|
+
prob_map = torch.sigmoid(pooled_logits)
|
|
275
|
+
|
|
276
|
+
def masked_class_mean(per_class: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:
|
|
277
|
+
# Average over the classes that have something to supervise; a graph-preserving zero if none has
|
|
278
|
+
return (per_class * valid).sum() / valid.sum().clamp(min=1)
|
|
274
279
|
|
|
275
280
|
# As described in the paper, we use the Dice loss for the text segmentation map and the Dice loss scaled by 0.5.
|
|
276
281
|
selected_masks = torch.cat(
|
|
@@ -278,13 +283,21 @@ class FAST(_FAST, nn.Module):
|
|
|
278
283
|
).float()
|
|
279
284
|
inter = (selected_masks * prob_map * seg_target).sum((0, 2, 3))
|
|
280
285
|
cardinality = (selected_masks * (prob_map + seg_target)).sum((0, 2, 3))
|
|
281
|
-
|
|
286
|
+
text_dice = 1 - 2 * inter / (cardinality + eps)
|
|
287
|
+
# With no positive pixel in the batch, Dice is a constant with zero gradient: false positives of that class
|
|
288
|
+
# would never be penalised. Supervise such classes as background with a BCE on the selected pixels instead.
|
|
289
|
+
num_selected = selected_masks.sum((0, 2, 3))
|
|
290
|
+
has_pos = (selected_masks * seg_target).sum((0, 2, 3)) > 0
|
|
291
|
+
neg_bce = (selected_masks * F.softplus(pooled_logits)).sum((0, 2, 3)) / num_selected.clamp(min=1)
|
|
292
|
+
text_loss = masked_class_mean(torch.where(has_pos, text_dice, neg_bce), num_selected > 0) * 0.5
|
|
282
293
|
|
|
283
294
|
# As described in the paper, we use the Dice loss for the text kernel map.
|
|
284
295
|
selected_masks = seg_target * seg_mask
|
|
285
296
|
inter = (selected_masks * kernels * shrunken_kernel).sum((0, 2, 3)) # noqa
|
|
286
297
|
cardinality = (selected_masks * (kernels + shrunken_kernel)).sum((0, 2, 3)) # noqa
|
|
287
|
-
|
|
298
|
+
# The kernel map is only defined inside text regions: skip the classes without any in the batch
|
|
299
|
+
kernel_dice = 1 - 2 * inter / (cardinality + eps)
|
|
300
|
+
kernel_loss = masked_class_mean(kernel_dice, selected_masks.sum((0, 2, 3)) > 0)
|
|
288
301
|
|
|
289
302
|
return text_loss + kernel_loss
|
|
290
303
|
|