torchocr 0.4.1__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.
- torchocr/__init__.py +26 -0
- torchocr/charsets.py +67 -0
- torchocr/core/__init__.py +1 -0
- torchocr/core/structures.py +72 -0
- torchocr/data/__init__.py +5 -0
- torchocr/data/ppocr_keys_v1.txt +6623 -0
- torchocr/datasets/__init__.py +9 -0
- torchocr/datasets/funsd.py +90 -0
- torchocr/datasets/icdar.py +116 -0
- torchocr/datasets/lmdb_words.py +73 -0
- torchocr/datasets/totaltext.py +118 -0
- torchocr/decoders.py +283 -0
- torchocr/io/__init__.py +21 -0
- torchocr/io/pdf.py +45 -0
- torchocr/losses.py +208 -0
- torchocr/metrics/__init__.py +6 -0
- torchocr/metrics/detection.py +208 -0
- torchocr/metrics/recognition.py +80 -0
- torchocr/models/__init__.py +37 -0
- torchocr/models/backbones/__init__.py +6 -0
- torchocr/models/backbones/mobilenet_v3.py +314 -0
- torchocr/models/backbones/resnet_vd.py +248 -0
- torchocr/models/detection.py +519 -0
- torchocr/models/hub.py +216 -0
- torchocr/models/recognition.py +391 -0
- torchocr/ops/__init__.py +6 -0
- torchocr/ops/crop.py +113 -0
- torchocr/ops/geometry.py +99 -0
- torchocr/pipelines.py +219 -0
- torchocr/postprocess.py +175 -0
- torchocr/transforms/__init__.py +13 -0
- torchocr/transforms/_presets.py +137 -0
- torchocr/transforms/db_targets.py +166 -0
- torchocr/transforms/v2.py +182 -0
- torchocr-0.4.1.dist-info/METADATA +257 -0
- torchocr-0.4.1.dist-info/RECORD +39 -0
- torchocr-0.4.1.dist-info/WHEEL +5 -0
- torchocr-0.4.1.dist-info/licenses/LICENSE +28 -0
- torchocr-0.4.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""ResNet-VD backbone matching PaddleOCR's det_resnet_vd / rec_resnet_vd.
|
|
2
|
+
|
|
3
|
+
The "VD" variant differs from torchvision's ResNet in two places:
|
|
4
|
+
|
|
5
|
+
1. The stem replaces the single 7x7 conv with three stacked 3x3 convs
|
|
6
|
+
(32 -> 32 -> 64), giving a richer low-level representation at the
|
|
7
|
+
same downsampling factor.
|
|
8
|
+
2. Stride-2 shortcuts on residual blocks use a 2x2 average-pool
|
|
9
|
+
followed by a 1x1 conv instead of a 1x1 strided conv. This avoids
|
|
10
|
+
discarding 3 of every 4 input pixels at the shortcut.
|
|
11
|
+
|
|
12
|
+
The same module powers both detection (depth=18, downsample_stride=2)
|
|
13
|
+
and recognition (depth=34, downsample_stride=(2, 1) so width is
|
|
14
|
+
preserved for CTC decoding).
|
|
15
|
+
|
|
16
|
+
Internal module naming intentionally mirrors PaddleOCR
|
|
17
|
+
(``conv1_1``, ``stages``, ``_conv``, ``_batch_norm``) so PaddleOCR
|
|
18
|
+
checkpoints translate to torchocr state_dicts with a small mechanical
|
|
19
|
+
name remap. This is the only place in torchocr we accept Paddle-style
|
|
20
|
+
names; the public forward contract returns idiomatic PyTorch outputs.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from typing import Literal
|
|
24
|
+
|
|
25
|
+
import torch
|
|
26
|
+
from torch import Tensor, nn
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# torch.fx.wrap only patches the globals of the module that calls it, so each
|
|
30
|
+
# backbone module keeps its own wrapped check (see detection._check_dbnet_input).
|
|
31
|
+
@torch.fx.wrap
|
|
32
|
+
def _check_backbone_input(x: Tensor) -> None:
|
|
33
|
+
if x.ndim != 4:
|
|
34
|
+
raise ValueError(f"Expected (B, C, H, W) input; got shape {tuple(x.shape)}.")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_BACKBONE_OUT_CHANNELS = (64, 128, 256, 512)
|
|
38
|
+
|
|
39
|
+
_BLOCK_COUNTS_BY_DEPTH: dict[int, tuple[int, int, int, int]] = {
|
|
40
|
+
18: (2, 2, 2, 2),
|
|
41
|
+
34: (3, 4, 6, 3),
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
StrideArg = int | tuple[int, int]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class _ConvBNLayer(nn.Module):
|
|
49
|
+
"""Conv -> BatchNorm -> optional ReLU, with the VD avg-pool trick.
|
|
50
|
+
|
|
51
|
+
When ``is_vd_mode`` is True a ``stride``-sized average pool is
|
|
52
|
+
applied before the (now-stride-1) convolution. This is the VD
|
|
53
|
+
shortcut trick on stride-2 blocks. The pool's kernel and stride
|
|
54
|
+
both equal the constructor's ``stride`` argument so the same
|
|
55
|
+
layer works for stride 2 (detection) and stride (2, 1)
|
|
56
|
+
(recognition). The internal submodule names ``_conv`` and
|
|
57
|
+
``_batch_norm`` match PaddleOCR's checkpoints.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
in_channels: int,
|
|
63
|
+
out_channels: int,
|
|
64
|
+
kernel_size: int,
|
|
65
|
+
stride: StrideArg = 1,
|
|
66
|
+
is_vd_mode: bool = False,
|
|
67
|
+
act: bool = False,
|
|
68
|
+
) -> None:
|
|
69
|
+
super().__init__()
|
|
70
|
+
self.is_vd_mode = is_vd_mode
|
|
71
|
+
self.act = act
|
|
72
|
+
if is_vd_mode:
|
|
73
|
+
self._pool2d_avg = nn.AvgPool2d(
|
|
74
|
+
kernel_size=stride, stride=stride, padding=0, ceil_mode=True
|
|
75
|
+
)
|
|
76
|
+
self._conv = nn.Conv2d(
|
|
77
|
+
in_channels=in_channels,
|
|
78
|
+
out_channels=out_channels,
|
|
79
|
+
kernel_size=kernel_size,
|
|
80
|
+
stride=1 if is_vd_mode else stride,
|
|
81
|
+
padding=(kernel_size - 1) // 2,
|
|
82
|
+
bias=False,
|
|
83
|
+
)
|
|
84
|
+
self._batch_norm = nn.BatchNorm2d(out_channels)
|
|
85
|
+
|
|
86
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
87
|
+
if self.is_vd_mode:
|
|
88
|
+
x = self._pool2d_avg(x)
|
|
89
|
+
x = self._conv(x)
|
|
90
|
+
x = self._batch_norm(x)
|
|
91
|
+
if self.act:
|
|
92
|
+
x = nn.functional.relu(x, inplace=True)
|
|
93
|
+
return x
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class _BasicBlock(nn.Module):
|
|
97
|
+
"""ResNet-VD basic block (two 3x3 convs + identity-or-VD shortcut).
|
|
98
|
+
|
|
99
|
+
Both conv0 and the shortcut use the same downsample stride so that
|
|
100
|
+
feature-map shapes line up at the residual addition.
|
|
101
|
+
"""
|
|
102
|
+
|
|
103
|
+
def __init__(
|
|
104
|
+
self,
|
|
105
|
+
in_channels: int,
|
|
106
|
+
out_channels: int,
|
|
107
|
+
stride: StrideArg,
|
|
108
|
+
shortcut: bool,
|
|
109
|
+
if_first: bool,
|
|
110
|
+
) -> None:
|
|
111
|
+
super().__init__()
|
|
112
|
+
self.conv0 = _ConvBNLayer(
|
|
113
|
+
in_channels=in_channels,
|
|
114
|
+
out_channels=out_channels,
|
|
115
|
+
kernel_size=3,
|
|
116
|
+
stride=stride,
|
|
117
|
+
act=True,
|
|
118
|
+
)
|
|
119
|
+
self.conv1 = _ConvBNLayer(
|
|
120
|
+
in_channels=out_channels,
|
|
121
|
+
out_channels=out_channels,
|
|
122
|
+
kernel_size=3,
|
|
123
|
+
act=False,
|
|
124
|
+
)
|
|
125
|
+
self.shortcut = shortcut
|
|
126
|
+
if not shortcut:
|
|
127
|
+
self.short = _ConvBNLayer(
|
|
128
|
+
in_channels=in_channels,
|
|
129
|
+
out_channels=out_channels,
|
|
130
|
+
kernel_size=1,
|
|
131
|
+
stride=stride,
|
|
132
|
+
is_vd_mode=not if_first,
|
|
133
|
+
act=False,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
137
|
+
y = self.conv0(x)
|
|
138
|
+
y = self.conv1(y)
|
|
139
|
+
identity = x if self.shortcut else self.short(x)
|
|
140
|
+
return nn.functional.relu(identity + y, inplace=True)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class ResNetVd(nn.Module):
|
|
144
|
+
"""ResNet-VD backbone returning a four-level feature pyramid.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
depth: 18 (default, used by DBNet detector) or 34 (used by the
|
|
148
|
+
CRNN recognizer). Both are BasicBlock-based; bottleneck
|
|
149
|
+
depths 50+ are deferred.
|
|
150
|
+
in_channels: Number of input image channels. Default 3.
|
|
151
|
+
downsample_stride: Stride applied to the first block of stages
|
|
152
|
+
1, 2, 3 (stage 0 is always stride 1). ``2`` for detection
|
|
153
|
+
(default), ``(2, 1)`` for recognition so width is preserved
|
|
154
|
+
for CTC decoding. The VD avg-pool stride matches.
|
|
155
|
+
stem_stride: Stride of the first stem conv (``conv1_1``).
|
|
156
|
+
``2`` for detection (default), ``1`` for recognition --
|
|
157
|
+
PaddleOCR's ``rec_resnet_vd`` keeps the stem at full
|
|
158
|
+
resolution so the recognizer's feature maps line up with
|
|
159
|
+
the trained weights.
|
|
160
|
+
final_pool: If True, append a ``MaxPool(2, 2)`` after the last
|
|
161
|
+
stage. Required for recognition (matches PaddleOCR's
|
|
162
|
+
``out_pool``); detection leaves it off.
|
|
163
|
+
|
|
164
|
+
Forward signature:
|
|
165
|
+
Input ``(B, in_channels, H, W)``. With ``downsample_stride=2``,
|
|
166
|
+
H and W must be divisible by 32 and the four output strides
|
|
167
|
+
are 4, 8, 16, 32. With ``downsample_stride=(2, 1)`` the width
|
|
168
|
+
is preserved through stages 1-3 (only the stem and pool reduce
|
|
169
|
+
it), so output width is W/4 and final height is H/32.
|
|
170
|
+
|
|
171
|
+
Output ``dict[str, Tensor]`` with keys ``c2``, ``c3``, ``c4``,
|
|
172
|
+
``c5`` and channels (64, 128, 256, 512).
|
|
173
|
+
|
|
174
|
+
Note:
|
|
175
|
+
Each stage's blocks are exposed as ``stages[i].bb_<i>_<j>``
|
|
176
|
+
matching PaddleOCR's checkpoint layout. This is what enables
|
|
177
|
+
``scripts/convert_paddle_dbnet.py`` and
|
|
178
|
+
``scripts/convert_paddle_crnn.py`` to do small mechanical name
|
|
179
|
+
remaps rather than full re-architecture.
|
|
180
|
+
"""
|
|
181
|
+
|
|
182
|
+
def __init__(
|
|
183
|
+
self,
|
|
184
|
+
depth: Literal[18, 34] = 18,
|
|
185
|
+
in_channels: int = 3,
|
|
186
|
+
downsample_stride: StrideArg = 2,
|
|
187
|
+
stem_stride: int = 2,
|
|
188
|
+
final_pool: bool = False,
|
|
189
|
+
) -> None:
|
|
190
|
+
super().__init__()
|
|
191
|
+
if depth not in _BLOCK_COUNTS_BY_DEPTH:
|
|
192
|
+
supported = sorted(_BLOCK_COUNTS_BY_DEPTH)
|
|
193
|
+
raise NotImplementedError(
|
|
194
|
+
f"Supported depths: {supported}. Got depth={depth}. "
|
|
195
|
+
"Bottleneck depths (50, 101, ...) are planned for a follow-up."
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
self.depth = depth
|
|
199
|
+
self.downsample_stride = downsample_stride
|
|
200
|
+
block_counts = _BLOCK_COUNTS_BY_DEPTH[depth]
|
|
201
|
+
in_per_stage = (64, 64, 128, 256)
|
|
202
|
+
out_per_stage = _BACKBONE_OUT_CHANNELS
|
|
203
|
+
|
|
204
|
+
self.conv1_1 = _ConvBNLayer(in_channels, 32, kernel_size=3, stride=stem_stride, act=True)
|
|
205
|
+
self.conv1_2 = _ConvBNLayer(32, 32, kernel_size=3, stride=1, act=True)
|
|
206
|
+
self.conv1_3 = _ConvBNLayer(32, 64, kernel_size=3, stride=1, act=True)
|
|
207
|
+
self.pool2d_max = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
|
|
208
|
+
# Some PaddleOCR recipes (rec_resnet_vd) append a final pool to halve
|
|
209
|
+
# the remaining height/width after the last stage. Detection skips it.
|
|
210
|
+
self.out_pool = nn.MaxPool2d(kernel_size=2, stride=2) if final_pool else None
|
|
211
|
+
|
|
212
|
+
self.stages = nn.ModuleList()
|
|
213
|
+
for stage_idx, (n_blocks, c_in, c_out) in enumerate(
|
|
214
|
+
zip(block_counts, in_per_stage, out_per_stage)
|
|
215
|
+
):
|
|
216
|
+
stage = nn.Sequential()
|
|
217
|
+
for block_idx in range(n_blocks):
|
|
218
|
+
first_in_stage = block_idx == 0
|
|
219
|
+
first_overall = stage_idx == 0 and first_in_stage
|
|
220
|
+
# stage 0 is stride 1; later stages downsample on their first block.
|
|
221
|
+
stride: StrideArg = 1 if stage_idx == 0 or not first_in_stage else downsample_stride
|
|
222
|
+
block = _BasicBlock(
|
|
223
|
+
in_channels=c_in if first_in_stage else c_out,
|
|
224
|
+
out_channels=c_out,
|
|
225
|
+
stride=stride,
|
|
226
|
+
shortcut=not first_in_stage,
|
|
227
|
+
if_first=first_overall,
|
|
228
|
+
)
|
|
229
|
+
stage.add_module(f"bb_{stage_idx}_{block_idx}", block)
|
|
230
|
+
self.stages.append(stage)
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def out_channels(self) -> tuple[int, ...]:
|
|
234
|
+
return _BACKBONE_OUT_CHANNELS
|
|
235
|
+
|
|
236
|
+
def forward(self, x: Tensor) -> dict[str, Tensor]:
|
|
237
|
+
_check_backbone_input(x)
|
|
238
|
+
x = self.conv1_1(x)
|
|
239
|
+
x = self.conv1_2(x)
|
|
240
|
+
x = self.conv1_3(x)
|
|
241
|
+
x = self.pool2d_max(x)
|
|
242
|
+
c2 = self.stages[0](x)
|
|
243
|
+
c3 = self.stages[1](c2)
|
|
244
|
+
c4 = self.stages[2](c3)
|
|
245
|
+
c5 = self.stages[3](c4)
|
|
246
|
+
if self.out_pool is not None:
|
|
247
|
+
c5 = self.out_pool(c5)
|
|
248
|
+
return {"c2": c2, "c3": c3, "c4": c4, "c5": c5}
|