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.
@@ -0,0 +1,519 @@
1
+ """Text detection model definitions."""
2
+
3
+ from dataclasses import dataclass
4
+ from functools import partial
5
+ from typing import Literal
6
+
7
+ import torch
8
+ from torch import Tensor, nn
9
+ from torch.nn import functional as F
10
+ from torchvision.models import ResNet18_Weights, resnet18
11
+ from torchvision.models.feature_extraction import create_feature_extractor
12
+
13
+ from ..transforms import DetectionPreset
14
+ from .backbones import MobileNetV3, ResNetVd
15
+ from .backbones.mobilenet_v3 import _SEModule
16
+ from .hub import BASE_URL, Weights, WeightsEnum, get_weight, load_weights, register_model
17
+
18
+
19
+ _BACKBONE_TAPS = {"layer1": "c2", "layer2": "c3", "layer3": "c4", "layer4": "c5"}
20
+ _BACKBONE_CHANNELS = (64, 128, 256, 512)
21
+ _BACKBONE_KEYS = ("c2", "c3", "c4", "c5")
22
+
23
+
24
+ @dataclass
25
+ class DBNetOutput:
26
+ """Probability and threshold maps from a DBNet forward pass."""
27
+
28
+ probability: Tensor
29
+ threshold: Tensor
30
+
31
+
32
+ # Lets torch.export flatten and rebuild the typed output (it is a pytree node).
33
+ torch.export.register_dataclass(DBNetOutput, serialized_type_name="torchocr.models.detection.DBNetOutput")
34
+
35
+
36
+ @torch.fx.wrap
37
+ def _check_dbnet_input(images: Tensor) -> None:
38
+ """Raise ``ValueError`` unless ``images`` is ``(B, 3, H, W)`` with ``H, W`` multiples of 32.
39
+
40
+ A module-level function marked ``torch.fx.wrap``: FX records it as an opaque
41
+ call instead of tracing its Python ``if``s on proxies, so the model stays
42
+ FX-traceable while every run (eager, traced, exported) still checks shapes.
43
+ """
44
+ if images.ndim != 4 or images.shape[1] != 3:
45
+ raise ValueError(f"Expected (B, 3, H, W) images; got {tuple(images.shape)}.")
46
+ height, width = images.shape[-2:]
47
+ if height % 32 or width % 32:
48
+ raise ValueError(f"Height and width must be divisible by 32; got {height}x{width}.")
49
+
50
+
51
+ class _FPN(nn.Module):
52
+ """Top-down Feature Pyramid Network with lateral connections.
53
+
54
+ This is the original torchocr FPN, paired with the torchvision
55
+ ``resnet18`` backbone path. The PaddleOCR-compatible
56
+ :class:`_DBFPN` is used with the ``resnet18_vd`` path instead.
57
+ """
58
+
59
+ def __init__(self, in_channels: tuple[int, ...], out_channels: int) -> None:
60
+ super().__init__()
61
+ self.lateral = nn.ModuleList(
62
+ nn.Conv2d(c, out_channels, kernel_size=1, bias=False) for c in in_channels
63
+ )
64
+ self.smooth = nn.ModuleList(
65
+ nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1, bias=False)
66
+ for _ in in_channels
67
+ )
68
+
69
+ def forward(self, features: list[Tensor]) -> list[Tensor]:
70
+ laterals = [conv(f) for conv, f in zip(self.lateral, features)]
71
+ for i in range(len(laterals) - 1, 0, -1):
72
+ laterals[i - 1] = laterals[i - 1] + F.interpolate(
73
+ laterals[i], scale_factor=2.0, mode="nearest"
74
+ )
75
+ return [smooth(lat) for smooth, lat in zip(self.smooth, laterals)]
76
+
77
+
78
+ class _DBFPN(nn.Module):
79
+ """PaddleOCR-compatible DBFPN with cascaded top-down adds.
80
+
81
+ Produces a single fused tensor at 1/4 resolution shaped
82
+ ``(B, out_channels, H/4, W/4)``. Each pyramid level is reduced to
83
+ ``out_channels // 4`` and concatenated to recover the full
84
+ ``out_channels`` count -- this matches PaddleOCR's
85
+ ``ppocr.modeling.necks.db_fpn.DBFPN`` exactly so weights port over
86
+ with a small mechanical name remap.
87
+
88
+ Submodule names (``in2_conv``, ``p2_conv``, ...) match PaddleOCR.
89
+ """
90
+
91
+ def __init__(self, in_channels: tuple[int, ...], out_channels: int) -> None:
92
+ super().__init__()
93
+ if len(in_channels) != 4:
94
+ raise ValueError(f"DBFPN expects 4 input scales; got {len(in_channels)}.")
95
+ c2, c3, c4, c5 = in_channels
96
+ self.in2_conv = nn.Conv2d(c2, out_channels, kernel_size=1, bias=False)
97
+ self.in3_conv = nn.Conv2d(c3, out_channels, kernel_size=1, bias=False)
98
+ self.in4_conv = nn.Conv2d(c4, out_channels, kernel_size=1, bias=False)
99
+ self.in5_conv = nn.Conv2d(c5, out_channels, kernel_size=1, bias=False)
100
+ smooth = out_channels // 4
101
+ self.p2_conv = nn.Conv2d(out_channels, smooth, kernel_size=3, padding=1, bias=False)
102
+ self.p3_conv = nn.Conv2d(out_channels, smooth, kernel_size=3, padding=1, bias=False)
103
+ self.p4_conv = nn.Conv2d(out_channels, smooth, kernel_size=3, padding=1, bias=False)
104
+ self.p5_conv = nn.Conv2d(out_channels, smooth, kernel_size=3, padding=1, bias=False)
105
+
106
+ def forward(self, features: dict[str, Tensor]) -> Tensor:
107
+ c2, c3, c4, c5 = (features[name] for name in _BACKBONE_KEYS)
108
+ in5 = self.in5_conv(c5)
109
+ in4 = self.in4_conv(c4)
110
+ in3 = self.in3_conv(c3)
111
+ in2 = self.in2_conv(c2)
112
+
113
+ out4 = in4 + F.interpolate(in5, scale_factor=2.0, mode="nearest")
114
+ out3 = in3 + F.interpolate(out4, scale_factor=2.0, mode="nearest")
115
+ out2 = in2 + F.interpolate(out3, scale_factor=2.0, mode="nearest")
116
+
117
+ p5 = F.interpolate(self.p5_conv(in5), scale_factor=8.0, mode="nearest")
118
+ p4 = F.interpolate(self.p4_conv(out4), scale_factor=4.0, mode="nearest")
119
+ p3 = F.interpolate(self.p3_conv(out3), scale_factor=2.0, mode="nearest")
120
+ p2 = self.p2_conv(out2)
121
+ return torch.cat([p5, p4, p3, p2], dim=1)
122
+
123
+
124
+ class _RSELayer(nn.Module):
125
+ """1x1 (or 3x3) conv -> SE block, with optional shortcut.
126
+
127
+ Used by :class:`_RSEFPN` to inject channel attention at every FPN
128
+ convolution. Submodule names match PaddleOCR (``in_conv``,
129
+ ``se_block``).
130
+ """
131
+
132
+ def __init__(self, in_channels: int, out_channels: int, kernel_size: int, shortcut: bool = True) -> None:
133
+ super().__init__()
134
+ self.in_conv = nn.Conv2d(
135
+ in_channels,
136
+ out_channels,
137
+ kernel_size=kernel_size,
138
+ padding=kernel_size // 2,
139
+ bias=False,
140
+ )
141
+ self.se_block = _SEModule(out_channels)
142
+ self.shortcut = shortcut
143
+
144
+ def forward(self, x: Tensor) -> Tensor:
145
+ x = self.in_conv(x)
146
+ return x + self.se_block(x) if self.shortcut else self.se_block(x)
147
+
148
+
149
+ class _RSEFPN(nn.Module):
150
+ """PP-OCRv3 RSEFPN: DBFPN cascade with SE attention at every conv.
151
+
152
+ Same top-down + concat structure as :class:`_DBFPN` but every
153
+ 1x1 lateral and 3x3 smooth conv is replaced by an :class:`_RSELayer`.
154
+ Default ``out_channels`` is 96, the value PP-OCRv3 ships with.
155
+ """
156
+
157
+ def __init__(self, in_channels: tuple[int, ...], out_channels: int = 96, shortcut: bool = True) -> None:
158
+ super().__init__()
159
+ if len(in_channels) != 4:
160
+ raise ValueError(f"RSEFPN expects 4 input scales; got {len(in_channels)}.")
161
+ smooth = out_channels // 4
162
+ # PaddleOCR stores the 4 scales as ModuleLists indexed c2..c5 (i=0..3).
163
+ self.ins_conv = nn.ModuleList(
164
+ _RSELayer(in_channels[i], out_channels, kernel_size=1, shortcut=shortcut)
165
+ for i in range(4)
166
+ )
167
+ self.inp_conv = nn.ModuleList(
168
+ _RSELayer(out_channels, smooth, kernel_size=3, shortcut=shortcut)
169
+ for _ in range(4)
170
+ )
171
+
172
+ def forward(self, features: dict[str, Tensor]) -> Tensor:
173
+ c2, c3, c4, c5 = (features[name] for name in _BACKBONE_KEYS)
174
+ in5 = self.ins_conv[3](c5)
175
+ in4 = self.ins_conv[2](c4)
176
+ in3 = self.ins_conv[1](c3)
177
+ in2 = self.ins_conv[0](c2)
178
+
179
+ out4 = in4 + F.interpolate(in5, scale_factor=2.0, mode="nearest")
180
+ out3 = in3 + F.interpolate(out4, scale_factor=2.0, mode="nearest")
181
+ out2 = in2 + F.interpolate(out3, scale_factor=2.0, mode="nearest")
182
+
183
+ p5 = F.interpolate(self.inp_conv[3](in5), scale_factor=8.0, mode="nearest")
184
+ p4 = F.interpolate(self.inp_conv[2](out4), scale_factor=4.0, mode="nearest")
185
+ p3 = F.interpolate(self.inp_conv[1](out3), scale_factor=2.0, mode="nearest")
186
+ p2 = self.inp_conv[0](out2)
187
+ return torch.cat([p5, p4, p3, p2], dim=1)
188
+
189
+
190
+ class _DBHead(nn.Module):
191
+ """One head (binarize or threshold) of a DBNet.
192
+
193
+ Module layout matches PaddleOCR's ``ppocr.modeling.heads.det_db_head.Head``:
194
+ ``conv1`` -> ``conv_bn1`` -> ReLU -> ``conv2`` (transpose, x2) ->
195
+ ``conv_bn2`` -> ReLU -> ``conv3`` (transpose, x2) -> sigmoid.
196
+ Sigmoid is applied in forward and is not a registered module, so
197
+ the state_dict has exactly the same parameter names as PaddleOCR's
198
+ head once the converter strips its ``head.binarize.`` /
199
+ ``head.thresh.`` prefixes.
200
+ """
201
+
202
+ def __init__(self, in_channels: int) -> None:
203
+ super().__init__()
204
+ inner = in_channels // 4
205
+ self.conv1 = nn.Conv2d(in_channels, inner, kernel_size=3, padding=1, bias=False)
206
+ self.conv_bn1 = nn.BatchNorm2d(inner)
207
+ self.conv2 = nn.ConvTranspose2d(inner, inner, kernel_size=2, stride=2)
208
+ self.conv_bn2 = nn.BatchNorm2d(inner)
209
+ self.conv3 = nn.ConvTranspose2d(inner, 1, kernel_size=2, stride=2)
210
+
211
+ def forward(self, x: Tensor) -> Tensor:
212
+ x = F.relu(self.conv_bn1(self.conv1(x)), inplace=True)
213
+ x = F.relu(self.conv_bn2(self.conv2(x)), inplace=True)
214
+ return torch.sigmoid(self.conv3(x))
215
+
216
+
217
+ BackboneName = Literal["resnet18", "resnet18_vd", "mobilenet_v3_large_05"]
218
+
219
+
220
+ # PaddleOCR detectors saw cv2-decoded BGR pixels normalized with RGB-ordered
221
+ # ImageNet statistics; on ICDAR-2015 "bgr" beats "rgb" for every checkpoint.
222
+ _PADDLE_DET_PRESET = partial(DetectionPreset, max_side=960, channel_order="bgr")
223
+
224
+ # PaddleOCR's DB post-processing defaults, under which the converted checkpoints were scored.
225
+ _PADDLE_DB_POSTPROCESS = {"threshold": 0.3, "box_thresh": 0.6, "unclip_ratio": 1.5}
226
+
227
+ _ICDAR2015_PROTOCOL = (
228
+ "ICDAR-2015 test (500 images, 2077 care words), official IoU protocol on rotated quads; "
229
+ "transforms() preset, DBPostProcessor(**meta['postprocess']). "
230
+ "Reproduce with references/detection/evaluate.py --weights <this enum>."
231
+ )
232
+ _LINE_LEVEL_CAVEAT = (
233
+ "Trained by PaddleOCR on line-level annotations of mostly Chinese/English document and "
234
+ "scene text, then converted to PyTorch. ICDAR-2015 scores *word* boxes in low-resolution "
235
+ "street scenes, so adjacent words merged into one line count as misses; use this number "
236
+ "to compare checkpoints, not as the accuracy you will see on documents."
237
+ )
238
+
239
+
240
+ class DBNet_ResNet18_VD_Weights(WeightsEnum):
241
+ PPOCR_SERVER_V2 = Weights(
242
+ url=f"{BASE_URL}/dbnet_resnet18_vd_ppocr_server_v2-59d99b11.pth",
243
+ transforms=_PADDLE_DET_PRESET,
244
+ meta={
245
+ "task": "detection",
246
+ "backbone": "resnet18_vd",
247
+ "num_params": 12_364_386,
248
+ "source": "PaddleOCR ch_ppocr_server_v2.0_det_train, via scripts/convert_paddle_dbnet.py",
249
+ "license": "Apache-2.0",
250
+ "languages": ["ch", "en"],
251
+ "postprocess": _PADDLE_DB_POSTPROCESS,
252
+ "_metrics": {"ICDAR2015-test": {"precision": 0.5814, "recall": 0.3216, "hmean": 0.4141}},
253
+ "_docs": f"{_LINE_LEVEL_CAVEAT} {_ICDAR2015_PROTOCOL}",
254
+ },
255
+ )
256
+ ICDAR2015 = Weights(
257
+ url=f"{BASE_URL}/dbnet_resnet18_vd_ic15-d803cec9.pth",
258
+ # Trained and scored at PaddleOCR's ICDAR-2015 test size (736 x 1280).
259
+ transforms=partial(DetectionPreset, max_side=1280, channel_order="bgr"),
260
+ meta={
261
+ "task": "detection",
262
+ "backbone": "resnet18_vd",
263
+ "num_params": 12_364_386,
264
+ "source": (
265
+ "torchocr: PPOCR_SERVER_V2 fine-tuned 300 epochs on the 1000 ICDAR-2015 training images "
266
+ "with references/detection/train.py"
267
+ ),
268
+ "license": "Apache-2.0 (base weights); fine-tuned on ICDAR 2015, released for research use",
269
+ "languages": ["en"],
270
+ "postprocess": {"threshold": 0.3, "box_thresh": 0.5, "unclip_ratio": 1.5},
271
+ "_metrics": {"ICDAR2015-test": {"precision": 0.8485, "recall": 0.7737, "hmean": 0.8094}},
272
+ "_docs": (
273
+ "Word-level detector for incidental scene text (street-level photos, Latin script). "
274
+ "box_thresh=0.5 maximizes hmean on the *training* split "
275
+ "(references/detection/calibrate.py) and was applied once to the test split; with "
276
+ "PaddleOCR's box_thresh=0.6 this checkpoint scores 0.794. Weights are the last "
277
+ "epoch -- no checkpoint was selected on the test set. Expect lower recall on dense "
278
+ f"documents and on non-Latin scripts. {_ICDAR2015_PROTOCOL}"
279
+ ),
280
+ },
281
+ )
282
+ DEFAULT = PPOCR_SERVER_V2
283
+
284
+
285
+ class DBNet_MobileNetV3_Large_05_Weights(WeightsEnum):
286
+ PPOCR_V3_CH = Weights(
287
+ url=f"{BASE_URL}/dbnet_mobilenet_v3_large_05_ppocr_v3_ch-fc000d1e.pth",
288
+ transforms=_PADDLE_DET_PRESET,
289
+ meta={
290
+ "task": "detection",
291
+ "backbone": "mobilenet_v3_large_05",
292
+ "num_params": 603_418,
293
+ "source": "PaddleOCR ch_PP-OCRv3_det_distill_train (Student), via scripts/convert_paddle_dbnet_v3.py",
294
+ "license": "Apache-2.0",
295
+ "languages": ["ch", "en"],
296
+ "postprocess": _PADDLE_DB_POSTPROCESS,
297
+ "_metrics": {"ICDAR2015-test": {"precision": 0.5641, "recall": 0.3370, "hmean": 0.4219}},
298
+ "_docs": f"{_LINE_LEVEL_CAVEAT} {_ICDAR2015_PROTOCOL}",
299
+ },
300
+ )
301
+ PPOCR_V3_EN = Weights(
302
+ url=f"{BASE_URL}/dbnet_mobilenet_v3_large_05_ppocr_v3_en-9bfd3b59.pth",
303
+ transforms=_PADDLE_DET_PRESET,
304
+ meta={
305
+ "task": "detection",
306
+ "backbone": "mobilenet_v3_large_05",
307
+ "num_params": 603_418,
308
+ "source": "PaddleOCR en_PP-OCRv3_det_distill_train (Student), via scripts/convert_paddle_dbnet_v3.py",
309
+ "license": "Apache-2.0",
310
+ "languages": ["en"],
311
+ "postprocess": _PADDLE_DB_POSTPROCESS,
312
+ "_metrics": {"ICDAR2015-test": {"precision": 0.5342, "recall": 0.3755, "hmean": 0.4411}},
313
+ "_docs": f"{_LINE_LEVEL_CAVEAT} {_ICDAR2015_PROTOCOL}",
314
+ },
315
+ )
316
+ ICDAR2015 = Weights(
317
+ url=f"{BASE_URL}/dbnet_mobilenet_v3_large_05_ic15-d9d17ae7.pth",
318
+ # Trained and scored at PaddleOCR's ICDAR-2015 test size (736 x 1280).
319
+ transforms=partial(DetectionPreset, max_side=1280, channel_order="bgr"),
320
+ meta={
321
+ "task": "detection",
322
+ "backbone": "mobilenet_v3_large_05",
323
+ "num_params": 603_418,
324
+ "source": (
325
+ "torchocr: PPOCR_V3_EN fine-tuned 300 epochs on the 1000 ICDAR-2015 training images "
326
+ "with references/detection/train.py"
327
+ ),
328
+ "license": "Apache-2.0 (base weights); fine-tuned on ICDAR 2015, released for research use",
329
+ "languages": ["en"],
330
+ "postprocess": {"threshold": 0.3, "box_thresh": 0.45, "unclip_ratio": 1.5},
331
+ "_metrics": {"ICDAR2015-test": {"precision": 0.7845, "recall": 0.6890, "hmean": 0.7337}},
332
+ "_docs": (
333
+ "Word-level detector for incidental scene text (street-level photos, Latin script). "
334
+ "box_thresh=0.45 maximizes hmean on the *training* split "
335
+ "(references/detection/calibrate.py) and was applied once to the test split; with "
336
+ "PaddleOCR's box_thresh=0.6 this checkpoint scores 0.688. Weights are the last "
337
+ "epoch -- no checkpoint was selected on the test set. Expect lower recall on dense "
338
+ f"documents and on non-Latin scripts. {_ICDAR2015_PROTOCOL}"
339
+ ),
340
+ },
341
+ )
342
+ DEFAULT = PPOCR_V3_CH
343
+
344
+
345
+ _WEIGHTS_BY_BACKBONE: dict[str, type[WeightsEnum]] = {
346
+ "resnet18_vd": DBNet_ResNet18_VD_Weights,
347
+ "mobilenet_v3_large_05": DBNet_MobileNetV3_Large_05_Weights,
348
+ }
349
+
350
+
351
+ class DBNet(nn.Module):
352
+ """DBNet text detector.
353
+
354
+ The model produces a probability map and a threshold map at the
355
+ input resolution. The differentiable-binarization combination of
356
+ the two maps is a training-time loss helper and lives outside this
357
+ module.
358
+
359
+ Args:
360
+ backbone: Which backbone to instantiate. ``"resnet18"`` uses
361
+ torchvision's ResNet-18 with its 7x7 stem and is what
362
+ torchocr trains from scratch (no published OCR weights).
363
+ ``"resnet18_vd"`` and ``"mobilenet_v3_large_05"`` mirror
364
+ PaddleOCR's detectors so converted checkpoints load as-is.
365
+ Default ``None``: taken from ``weights`` when it is an enum
366
+ member, else ``"resnet18"``.
367
+ weights: Pretrained OCR weights -- a member of
368
+ :class:`DBNet_ResNet18_VD_Weights` or
369
+ :class:`DBNet_MobileNetV3_Large_05_Weights`, or a member name
370
+ such as ``"DEFAULT"`` resolved against ``backbone``. If the
371
+ download fails a ``UserWarning`` is emitted and the model
372
+ keeps its random initialization. Pair with
373
+ ``weights.transforms()`` for the matching preprocessing.
374
+ Default ``None`` (random init).
375
+ ``pretrained_backbone`` is ignored for the PaddleOCR-style
376
+ backbones since no canonical ImageNet weights ship with
377
+ torchvision for them.
378
+ pretrained_backbone: If True and ``backbone="resnet18"``, load
379
+ ImageNet weights for the torchvision ResNet-18 backbone.
380
+ Default False to keep instantiation offline-safe.
381
+ fpn_out_channels: Channels per FPN level. Default 256.
382
+ head_inner_channels: Inner channels of the probability and
383
+ threshold heads. Used only on the ``resnet18`` path; the
384
+ ``resnet18_vd`` path uses ``fpn_out_channels // 4`` to
385
+ match PaddleOCR.
386
+
387
+ Note:
388
+ The ``resnet18`` backbone is wrapped via
389
+ ``create_feature_extractor`` (FX-traced). Custom backbones with
390
+ data-dependent control flow may fail to trace. The
391
+ ``resnet18_vd`` path bypasses FX tracing.
392
+ """
393
+
394
+ def __init__(
395
+ self,
396
+ backbone: BackboneName | None = None,
397
+ weights: WeightsEnum | str | None = None,
398
+ pretrained_backbone: bool = False,
399
+ fpn_out_channels: int = 256,
400
+ head_inner_channels: int = 64,
401
+ ) -> None:
402
+ super().__init__()
403
+ if isinstance(weights, str) and "." in weights:
404
+ weights = get_weight(weights) # "Cls.NAME" names the architecture too
405
+ if backbone is None:
406
+ backbone = weights.meta["backbone"] if isinstance(weights, WeightsEnum) else "resnet18"
407
+ if weights is not None:
408
+ if backbone not in _WEIGHTS_BY_BACKBONE:
409
+ raise ValueError(
410
+ f"No pretrained weights are published for backbone '{backbone}'. "
411
+ f"Backbones with weights: {sorted(_WEIGHTS_BY_BACKBONE)}."
412
+ )
413
+ weights = _WEIGHTS_BY_BACKBONE[backbone].verify(weights)
414
+ self.backbone_name = backbone
415
+
416
+ if backbone == "resnet18":
417
+ backbone_weights = ResNet18_Weights.DEFAULT if pretrained_backbone else None
418
+ torchvision_backbone = resnet18(weights=backbone_weights)
419
+ self.backbone = create_feature_extractor(
420
+ torchvision_backbone, return_nodes=_BACKBONE_TAPS
421
+ )
422
+ self.fpn = _FPN(_BACKBONE_CHANNELS, fpn_out_channels)
423
+ self.fuse = nn.Sequential(
424
+ nn.Conv2d(
425
+ fpn_out_channels * 4,
426
+ fpn_out_channels,
427
+ kernel_size=3,
428
+ padding=1,
429
+ bias=False,
430
+ ),
431
+ nn.BatchNorm2d(fpn_out_channels),
432
+ nn.ReLU(inplace=True),
433
+ )
434
+ self.probability_head = self._make_legacy_head(
435
+ fpn_out_channels, head_inner_channels
436
+ )
437
+ self.threshold_head = self._make_legacy_head(
438
+ fpn_out_channels, head_inner_channels
439
+ )
440
+ elif backbone == "resnet18_vd":
441
+ self.backbone = ResNetVd(depth=18)
442
+ self.fpn = _DBFPN(self.backbone.out_channels, fpn_out_channels)
443
+ self.binarize = _DBHead(fpn_out_channels)
444
+ self.thresh = _DBHead(fpn_out_channels)
445
+ elif backbone == "mobilenet_v3_large_05":
446
+ # PP-OCRv3 detector: MobileNetV3-large scale=0.5 with SE *disabled*
447
+ # in the backbone (SE only lives in the RSEFPN). Default neck width
448
+ # is 96 for v3 instead of the 256 used by the ResNet-VD detector.
449
+ self.backbone = MobileNetV3(model_name="large", scale=0.5, disable_se=True)
450
+ v3_fpn_channels = 96 if fpn_out_channels == 256 else fpn_out_channels
451
+ self.fpn = _RSEFPN(self.backbone.out_channels, out_channels=v3_fpn_channels)
452
+ self.binarize = _DBHead(v3_fpn_channels)
453
+ self.thresh = _DBHead(v3_fpn_channels)
454
+ else:
455
+ raise ValueError(
456
+ f"Unknown backbone '{backbone}'. "
457
+ "Known: 'resnet18', 'resnet18_vd', 'mobilenet_v3_large_05'."
458
+ )
459
+
460
+ if weights is not None:
461
+ load_weights(self, weights)
462
+
463
+ @staticmethod
464
+ def _make_legacy_head(in_channels: int, inner_channels: int) -> nn.Sequential:
465
+ return nn.Sequential(
466
+ nn.Conv2d(in_channels, inner_channels, kernel_size=3, padding=1, bias=False),
467
+ nn.BatchNorm2d(inner_channels),
468
+ nn.ReLU(inplace=True),
469
+ nn.ConvTranspose2d(inner_channels, inner_channels, kernel_size=2, stride=2),
470
+ nn.BatchNorm2d(inner_channels),
471
+ nn.ReLU(inplace=True),
472
+ nn.ConvTranspose2d(inner_channels, 1, kernel_size=2, stride=2),
473
+ nn.Sigmoid(),
474
+ )
475
+
476
+ def forward(self, images: Tensor) -> DBNetOutput:
477
+ _check_dbnet_input(images)
478
+
479
+ feature_maps = self.backbone(images)
480
+
481
+ if self.backbone_name == "resnet18":
482
+ pyramid = self.fpn([feature_maps[name] for name in _BACKBONE_KEYS])
483
+ target_size = pyramid[0].shape[-2:]
484
+ upsampled = [pyramid[0]] + [
485
+ F.interpolate(level, size=target_size, mode="nearest") for level in pyramid[1:]
486
+ ]
487
+ fused = self.fuse(torch.cat(upsampled, dim=1))
488
+ return DBNetOutput(
489
+ probability=self.probability_head(fused),
490
+ threshold=self.threshold_head(fused),
491
+ )
492
+
493
+ # ResNet-VD and MobileNetV3 paths share the same forward shape:
494
+ # backbone -> FPN/RSEFPN (single fused tensor) -> two DBHead modules.
495
+ fused = self.fpn(feature_maps)
496
+ return DBNetOutput(
497
+ probability=self.binarize(fused),
498
+ threshold=self.thresh(fused),
499
+ )
500
+
501
+
502
+ @register_model("dbnet_resnet18")
503
+ def dbnet_resnet18(**kwargs: object) -> DBNet:
504
+ """DBNet with torchvision's ResNet-18 backbone (no published OCR weights)."""
505
+ return DBNet(backbone="resnet18", **kwargs)
506
+
507
+
508
+ @register_model("dbnet_resnet18_vd", weights=DBNet_ResNet18_VD_Weights)
509
+ def dbnet_resnet18_vd(*, weights: DBNet_ResNet18_VD_Weights | str | None = None, **kwargs: object) -> DBNet:
510
+ """DBNet with PaddleOCR's ResNet-18-VD backbone; see :class:`DBNet_ResNet18_VD_Weights`."""
511
+ return DBNet(backbone="resnet18_vd", weights=weights, **kwargs)
512
+
513
+
514
+ @register_model("dbnet_mobilenet_v3_large_05", weights=DBNet_MobileNetV3_Large_05_Weights)
515
+ def dbnet_mobilenet_v3_large_05(
516
+ *, weights: DBNet_MobileNetV3_Large_05_Weights | str | None = None, **kwargs: object
517
+ ) -> DBNet:
518
+ """PP-OCRv3 detector (MobileNetV3-large x0.5 + RSEFPN); see :class:`DBNet_MobileNetV3_Large_05_Weights`."""
519
+ return DBNet(backbone="mobilenet_v3_large_05", weights=weights, **kwargs)