python-doctr 1.0.1__py3-none-any.whl → 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +669 -0
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +4 -2
- doctr/datasets/cord.py +2 -1
- doctr/datasets/datasets/base.py +12 -24
- doctr/datasets/datasets/pytorch.py +14 -4
- doctr/datasets/detection.py +14 -3
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +121 -37
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +9 -7
- doctr/datasets/ic13.py +4 -2
- doctr/datasets/iiit5k.py +2 -1
- doctr/datasets/iiithws.py +4 -2
- doctr/datasets/imgur5k.py +4 -2
- doctr/datasets/layout.py +129 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +5 -4
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +10 -8
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +104 -21
- doctr/datasets/vocabs.py +320 -148
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +3 -0
- doctr/io/elements.py +381 -271
- doctr/io/exporters.py +1915 -0
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -7
- doctr/io/image/pytorch.py +13 -5
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +3 -0
- doctr/models/_utils.py +206 -13
- doctr/models/builder.py +590 -137
- doctr/models/classification/__init__.py +3 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +34 -2
- doctr/models/classification/resnet/pytorch.py +5 -5
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +6 -5
- doctr/models/classification/vgg/pytorch.py +3 -2
- doctr/models/classification/vip/layers/pytorch.py +4 -4
- doctr/models/classification/vip/pytorch.py +4 -4
- doctr/models/classification/vit/pytorch.py +3 -3
- 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 +14 -2
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +32 -18
- doctr/models/detection/differentiable_binarization/base.py +23 -9
- doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
- doctr/models/detection/fast/base.py +22 -6
- doctr/models/detection/fast/pytorch.py +24 -11
- doctr/models/detection/linknet/base.py +22 -6
- doctr/models/detection/linknet/pytorch.py +10 -3
- doctr/models/detection/predictor/pytorch.py +43 -2
- doctr/models/detection/zoo.py +6 -2
- doctr/models/factory/hub.py +59 -41
- 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 +23 -1
- doctr/models/kie_predictor/pytorch.py +87 -15
- 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 +895 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +114 -0
- doctr/models/layout/zoo.py +94 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +415 -17
- doctr/models/predictor/pytorch.py +109 -12
- doctr/models/preprocessor/pytorch.py +82 -25
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +1127 -0
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +40 -16
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +84 -22
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +126 -25
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +68 -12
- doctr/models/recognition/sar/pytorch.py +21 -7
- doctr/models/recognition/utils.py +80 -50
- doctr/models/recognition/viptr/pytorch.py +38 -14
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +11 -7
- doctr/models/recognition/zoo.py +36 -9
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +231 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +675 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
- doctr/models/table_structure/zoo.py +87 -0
- doctr/models/utils/pytorch.py +381 -25
- doctr/models/zoo.py +141 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +261 -82
- doctr/transforms/modules/pytorch.py +396 -76
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +24 -11
- doctr/utils/fonts.py +64 -17
- doctr/utils/geometry.py +167 -28
- doctr/utils/metrics.py +481 -19
- doctr/utils/multithreading.py +127 -4
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +73 -10
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
- python_doctr-1.2.0.dist-info/RECORD +191 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.1.dist-info/RECORD +0 -149
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.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
|
+
)
|
|
@@ -152,7 +152,7 @@ def magc_resnet31(pretrained: bool = False, **kwargs: Any) -> ResNet:
|
|
|
152
152
|
>>> out = model(input_tensor)
|
|
153
153
|
|
|
154
154
|
Args:
|
|
155
|
-
pretrained:
|
|
155
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
156
156
|
**kwargs: keyword arguments of the ResNet architecture
|
|
157
157
|
|
|
158
158
|
Returns:
|
|
@@ -137,7 +137,7 @@ def mobilenet_v3_small(pretrained: bool = False, **kwargs: Any) -> mobilenetv3.M
|
|
|
137
137
|
>>> out = model(input_tensor)
|
|
138
138
|
|
|
139
139
|
Args:
|
|
140
|
-
pretrained:
|
|
140
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
141
141
|
**kwargs: keyword arguments of the MobileNetV3 architecture
|
|
142
142
|
|
|
143
143
|
Returns:
|
|
@@ -160,7 +160,7 @@ def mobilenet_v3_small_r(pretrained: bool = False, **kwargs: Any) -> mobilenetv3
|
|
|
160
160
|
>>> out = model(input_tensor)
|
|
161
161
|
|
|
162
162
|
Args:
|
|
163
|
-
pretrained:
|
|
163
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
164
164
|
**kwargs: keyword arguments of the MobileNetV3 architecture
|
|
165
165
|
|
|
166
166
|
Returns:
|
|
@@ -187,7 +187,7 @@ def mobilenet_v3_large(pretrained: bool = False, **kwargs: Any) -> mobilenetv3.M
|
|
|
187
187
|
>>> out = model(input_tensor)
|
|
188
188
|
|
|
189
189
|
Args:
|
|
190
|
-
pretrained:
|
|
190
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
191
191
|
**kwargs: keyword arguments of the MobileNetV3 architecture
|
|
192
192
|
|
|
193
193
|
Returns:
|
|
@@ -213,7 +213,7 @@ def mobilenet_v3_large_r(pretrained: bool = False, **kwargs: Any) -> mobilenetv3
|
|
|
213
213
|
>>> out = model(input_tensor)
|
|
214
214
|
|
|
215
215
|
Args:
|
|
216
|
-
pretrained:
|
|
216
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
217
217
|
**kwargs: keyword arguments of the MobileNetV3 architecture
|
|
218
218
|
|
|
219
219
|
Returns:
|
|
@@ -240,7 +240,7 @@ def mobilenet_v3_small_crop_orientation(pretrained: bool = False, **kwargs: Any)
|
|
|
240
240
|
>>> out = model(input_tensor)
|
|
241
241
|
|
|
242
242
|
Args:
|
|
243
|
-
pretrained:
|
|
243
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
244
244
|
**kwargs: keyword arguments of the MobileNetV3 architecture
|
|
245
245
|
|
|
246
246
|
Returns:
|
|
@@ -266,7 +266,7 @@ def mobilenet_v3_small_page_orientation(pretrained: bool = False, **kwargs: Any)
|
|
|
266
266
|
>>> out = model(input_tensor)
|
|
267
267
|
|
|
268
268
|
Args:
|
|
269
|
-
pretrained:
|
|
269
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
270
270
|
**kwargs: keyword arguments of the MobileNetV3 architecture
|
|
271
271
|
|
|
272
272
|
Returns:
|
|
@@ -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,22 +24,50 @@ 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]]:
|
|
68
|
+
if len(inputs) == 0:
|
|
69
|
+
return [[], [], []]
|
|
70
|
+
|
|
40
71
|
# Dimension check
|
|
41
72
|
if any(input.ndim != 3 for input in inputs):
|
|
42
73
|
raise ValueError("incorrect input shape: all inputs are expected to be multi-channel 2D images.")
|
|
@@ -47,13 +78,14 @@ class OrientationPredictor(nn.Module):
|
|
|
47
78
|
|
|
48
79
|
processed_batches = self.pre_processor(inputs)
|
|
49
80
|
_params = next(self.model.parameters())
|
|
50
|
-
self.model, processed_batches = set_device_and_dtype(
|
|
81
|
+
self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
|
|
51
82
|
self.model, processed_batches, _params.device, _params.dtype
|
|
52
83
|
)
|
|
53
84
|
predicted_batches = [self.model(batch) for batch in processed_batches]
|
|
54
85
|
# confidence
|
|
55
86
|
probs = [
|
|
56
|
-
torch.max(torch.softmax(batch, dim=1), dim=1).values.cpu().detach().numpy()
|
|
87
|
+
torch.max(torch.softmax(batch.float(), dim=1), dim=1).values.cpu().detach().numpy()
|
|
88
|
+
for batch in predicted_batches
|
|
57
89
|
]
|
|
58
90
|
# Postprocess predictions
|
|
59
91
|
predicted_batches = [out_batch.argmax(dim=1).cpu().detach().numpy() for out_batch in predicted_batches]
|
|
@@ -247,7 +247,7 @@ def resnet18(pretrained: bool = False, **kwargs: Any) -> TVResNet:
|
|
|
247
247
|
>>> out = model(input_tensor)
|
|
248
248
|
|
|
249
249
|
Args:
|
|
250
|
-
pretrained:
|
|
250
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
251
251
|
**kwargs: keyword arguments of the ResNet architecture
|
|
252
252
|
|
|
253
253
|
Returns:
|
|
@@ -274,7 +274,7 @@ def resnet31(pretrained: bool = False, **kwargs: Any) -> ResNet:
|
|
|
274
274
|
>>> out = model(input_tensor)
|
|
275
275
|
|
|
276
276
|
Args:
|
|
277
|
-
pretrained:
|
|
277
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
278
278
|
**kwargs: keyword arguments of the ResNet architecture
|
|
279
279
|
|
|
280
280
|
Returns:
|
|
@@ -306,7 +306,7 @@ def resnet34(pretrained: bool = False, **kwargs: Any) -> TVResNet:
|
|
|
306
306
|
>>> out = model(input_tensor)
|
|
307
307
|
|
|
308
308
|
Args:
|
|
309
|
-
pretrained:
|
|
309
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
310
310
|
**kwargs: keyword arguments of the ResNet architecture
|
|
311
311
|
|
|
312
312
|
Returns:
|
|
@@ -332,7 +332,7 @@ def resnet34_wide(pretrained: bool = False, **kwargs: Any) -> ResNet:
|
|
|
332
332
|
>>> out = model(input_tensor)
|
|
333
333
|
|
|
334
334
|
Args:
|
|
335
|
-
pretrained:
|
|
335
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
336
336
|
**kwargs: keyword arguments of the ResNet architecture
|
|
337
337
|
|
|
338
338
|
Returns:
|
|
@@ -364,7 +364,7 @@ def resnet50(pretrained: bool = False, **kwargs: Any) -> TVResNet:
|
|
|
364
364
|
>>> out = model(input_tensor)
|
|
365
365
|
|
|
366
366
|
Args:
|
|
367
|
-
pretrained:
|
|
367
|
+
pretrained: If True, returns a model pre-trained on our classification dataset
|
|
368
368
|
**kwargs: keyword arguments of the ResNet architecture
|
|
369
369
|
|
|
370
370
|
Returns:
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|