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,208 @@
1
+ """Text-detection metrics."""
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+
6
+ import numpy as np
7
+ import shapely
8
+ from torch import Tensor
9
+
10
+ from .recognition import normalize_text
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class HmeanResult:
15
+ """Dataset-level detection scores under the ICDAR IoU protocol.
16
+
17
+ ``num_gt`` and ``num_pred`` exclude don't-care regions and invalid
18
+ polygons; they are the denominators of ``recall`` and ``precision``.
19
+ """
20
+
21
+ precision: float
22
+ recall: float
23
+ hmean: float
24
+ num_matched: int
25
+ num_gt: int
26
+ num_pred: int
27
+
28
+
29
+ class DetectionHmean:
30
+ """ICDAR-2015 text-detection precision / recall / hmean.
31
+
32
+ Reproduces the official RRC "IoU" evaluation (the protocol behind
33
+ every published ICDAR-2015 detection number, and PaddleOCR's
34
+ ``DetectionIoUEvaluator``):
35
+
36
+ 1. Polygons that are not valid (e.g. self-intersecting) are dropped.
37
+ 2. A prediction is *don't care* if more than ``ignore_threshold`` of
38
+ its own area lies inside a single ignored ground-truth region
39
+ (``###`` transcriptions in ICDAR files).
40
+ 3. Remaining pairs are matched greedily and one-to-one in
41
+ (ground truth, prediction) order whenever IoU > ``iou_threshold``.
42
+ 4. Matches and care counts are summed over all images before the
43
+ ratios are taken, so large images are not averaged away.
44
+
45
+ Usage follows the stateful-metric idiom::
46
+
47
+ metric = DetectionHmean()
48
+ for preds, target in loader:
49
+ metric.update(preds, target.polygons, target.ignore)
50
+ result = metric.compute() # HmeanResult
51
+
52
+ Args:
53
+ iou_threshold: Minimum IoU (exclusive) for a match. Default 0.5.
54
+ ignore_threshold: Fraction (exclusive) of a prediction's area that
55
+ must overlap an ignored region to discard it. Default 0.5.
56
+ """
57
+
58
+ def __init__(self, iou_threshold: float = 0.5, ignore_threshold: float = 0.5) -> None:
59
+ if not 0.0 <= iou_threshold <= 1.0:
60
+ raise ValueError(f"iou_threshold must lie in [0, 1]; got {iou_threshold}.")
61
+ if not 0.0 <= ignore_threshold <= 1.0:
62
+ raise ValueError(f"ignore_threshold must lie in [0, 1]; got {ignore_threshold}.")
63
+ self.iou_threshold = iou_threshold
64
+ self.ignore_threshold = ignore_threshold
65
+ self.reset()
66
+
67
+ def reset(self) -> None:
68
+ self._matched = 0
69
+ self._gt_care = 0
70
+ self._pred_care = 0
71
+
72
+ def update(self, preds: Tensor, targets: Tensor, ignore: Tensor | None = None) -> None:
73
+ """Accumulate one image.
74
+
75
+ Args:
76
+ preds: Predicted regions, either ``(N, P, 2)`` polygons with
77
+ ``P >= 3`` vertices or ``(N, 4)`` ``xyxy`` boxes.
78
+ targets: Ground-truth regions in the same formats.
79
+ ignore: Optional ``(M,)`` bool mask over ``targets`` marking
80
+ don't-care regions. Default: nothing ignored.
81
+ """
82
+ pairs, gt_care, pred_care = self._match(preds, targets, ignore)
83
+ self._matched += len(pairs)
84
+ self._gt_care += gt_care
85
+ self._pred_care += pred_care
86
+
87
+ def _match(
88
+ self, preds: Tensor, targets: Tensor, ignore: Tensor | None
89
+ ) -> tuple[list[tuple[int, int]], int, int]:
90
+ """Return matched ``(target_index, pred_index)`` pairs and the care counts."""
91
+ pred_polys = _to_polygons(preds, "preds")
92
+ gt_polys = _to_polygons(targets, "targets")
93
+ if ignore is None:
94
+ gt_ignore = np.zeros(len(gt_polys), dtype=bool)
95
+ else:
96
+ gt_ignore = ignore.detach().cpu().numpy().astype(bool).reshape(-1)
97
+ if gt_ignore.shape[0] != len(gt_polys):
98
+ raise ValueError(
99
+ f"ignore has {gt_ignore.shape[0]} entries but targets has {len(gt_polys)} regions."
100
+ )
101
+
102
+ gt_index = np.flatnonzero(shapely.is_valid(gt_polys))
103
+ pred_index = np.flatnonzero(shapely.is_valid(pred_polys))
104
+ gt_polys, gt_ignore = gt_polys[gt_index], gt_ignore[gt_index]
105
+ pred_polys = pred_polys[pred_index]
106
+
107
+ pred_ignore = np.zeros(len(pred_polys), dtype=bool)
108
+ if gt_ignore.any() and len(pred_polys):
109
+ dont_care = gt_polys[gt_ignore]
110
+ overlap = shapely.area(shapely.intersection(pred_polys[:, None], dont_care[None, :]))
111
+ pred_area = shapely.area(pred_polys)[:, None]
112
+ with np.errstate(divide="ignore", invalid="ignore"):
113
+ fraction = np.where(pred_area > 0, overlap / pred_area, 0.0)
114
+ pred_ignore = (fraction > self.ignore_threshold).any(axis=1)
115
+
116
+ pairs: list[tuple[int, int]] = []
117
+ if len(gt_polys) and len(pred_polys):
118
+ inter = shapely.area(shapely.intersection(gt_polys[:, None], pred_polys[None, :]))
119
+ union = shapely.area(shapely.union(gt_polys[:, None], pred_polys[None, :]))
120
+ with np.errstate(divide="ignore", invalid="ignore"):
121
+ iou = np.where(union > 0, inter / union, 0.0)
122
+ # Greedy in index order -- intentionally not Hungarian, to stay
123
+ # bit-compatible with the official script.
124
+ pred_taken = pred_ignore.copy()
125
+ for g in np.flatnonzero(~gt_ignore):
126
+ for p in np.flatnonzero(~pred_taken & (iou[g] > self.iou_threshold)):
127
+ pred_taken[p] = True
128
+ pairs.append((int(gt_index[g]), int(pred_index[p])))
129
+ break
130
+ return pairs, int((~gt_ignore).sum()), int((~pred_ignore).sum())
131
+
132
+ def compute(self) -> HmeanResult:
133
+ recall = self._matched / self._gt_care if self._gt_care else 0.0
134
+ precision = self._matched / self._pred_care if self._pred_care else 0.0
135
+ hmean = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
136
+ return HmeanResult(
137
+ precision=precision,
138
+ recall=recall,
139
+ hmean=hmean,
140
+ num_matched=self._matched,
141
+ num_gt=self._gt_care,
142
+ num_pred=self._pred_care,
143
+ )
144
+
145
+
146
+ def _to_polygons(regions: Tensor, name: str) -> np.ndarray:
147
+ """Convert ``(N, P, 2)`` polygons or ``(N, 4)`` xyxy boxes to shapely polygons."""
148
+ coords = regions.detach().cpu().double().numpy()
149
+ if coords.ndim == 2 and coords.shape[1] == 4:
150
+ x1, y1, x2, y2 = coords.T
151
+ coords = np.stack([np.stack([x1, y1], -1), np.stack([x2, y1], -1),
152
+ np.stack([x2, y2], -1), np.stack([x1, y2], -1)], axis=1)
153
+ if coords.ndim != 3 or coords.shape[2] != 2 or coords.shape[1] < 3:
154
+ raise ValueError(
155
+ f"{name} must be (N, P, 2) polygons with P >= 3 or (N, 4) xyxy boxes; "
156
+ f"got {tuple(regions.shape)}."
157
+ )
158
+ if coords.shape[0] == 0:
159
+ return np.empty(0, dtype=object)
160
+ return shapely.polygons(coords)
161
+
162
+
163
+ class EndToEndHmean(DetectionHmean):
164
+ """End-to-end text spotting hmean: a detection counts only if it is also read correctly.
165
+
166
+ Regions are matched exactly as in :class:`DetectionHmean`; a matched pair
167
+ is a true positive only when the normalized transcriptions are equal.
168
+ This follows the ICDAR-2015 end-to-end task with a generic vocabulary
169
+ (no lexicon), simplified: text equality uses
170
+ :class:`~torchocr.metrics.RecognitionAccuracy`'s normalization instead of
171
+ the official script's special-character rules.
172
+
173
+ Args:
174
+ iou_threshold, ignore_threshold: As in :class:`DetectionHmean`.
175
+ case_sensitive, alphanumeric_only: Text normalization before
176
+ comparison. Defaults follow the scene-text convention
177
+ (case-insensitive, letters and digits only).
178
+ """
179
+
180
+ def __init__(
181
+ self,
182
+ iou_threshold: float = 0.5,
183
+ ignore_threshold: float = 0.5,
184
+ case_sensitive: bool = False,
185
+ alphanumeric_only: bool = True,
186
+ ) -> None:
187
+ super().__init__(iou_threshold, ignore_threshold)
188
+ self.case_sensitive = case_sensitive
189
+ self.alphanumeric_only = alphanumeric_only
190
+
191
+ def update( # type: ignore[override]
192
+ self,
193
+ preds: Tensor,
194
+ targets: Tensor,
195
+ ignore: Tensor | None,
196
+ pred_texts: Sequence[str],
197
+ target_texts: Sequence[str],
198
+ ) -> None:
199
+ """Accumulate one image; ``pred_texts`` / ``target_texts`` align with the regions."""
200
+ if len(pred_texts) != preds.shape[0]:
201
+ raise ValueError(f"pred_texts has {len(pred_texts)} entries for {preds.shape[0]} predictions.")
202
+ if len(target_texts) != targets.shape[0]:
203
+ raise ValueError(f"target_texts has {len(target_texts)} entries for {targets.shape[0]} targets.")
204
+ pairs, gt_care, pred_care = self._match(preds, targets, ignore)
205
+ norm = lambda t: normalize_text(t, self.case_sensitive, self.alphanumeric_only) # noqa: E731
206
+ self._matched += sum(norm(pred_texts[p]) == norm(target_texts[g]) for g, p in pairs)
207
+ self._gt_care += gt_care
208
+ self._pred_care += pred_care
@@ -0,0 +1,80 @@
1
+ """Text-recognition metrics."""
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class RecognitionResult:
9
+ """Dataset-level recognition scores.
10
+
11
+ ``char_error_rate`` is the summed edit distance divided by the summed
12
+ target length, so long words weigh more than short ones.
13
+ """
14
+
15
+ word_accuracy: float
16
+ char_error_rate: float
17
+ num_words: int
18
+
19
+
20
+ class RecognitionAccuracy:
21
+ """Word accuracy and character error rate over (prediction, target) string pairs.
22
+
23
+ ``case_sensitive=False, alphanumeric_only=True`` is the usual
24
+ scene-text protocol (ICDAR / IIIT5K / SVT report "case-insensitive
25
+ word accuracy" over letters and digits).
26
+
27
+ Args:
28
+ case_sensitive: Compare strings as-is. Default True.
29
+ alphanumeric_only: Drop every character that is not a letter or
30
+ a digit before comparing. Default False.
31
+ """
32
+
33
+ def __init__(self, case_sensitive: bool = True, alphanumeric_only: bool = False) -> None:
34
+ self.case_sensitive = case_sensitive
35
+ self.alphanumeric_only = alphanumeric_only
36
+ self.reset()
37
+
38
+ def reset(self) -> None:
39
+ self._correct = 0
40
+ self._words = 0
41
+ self._edits = 0
42
+ self._target_chars = 0
43
+
44
+ def _normalize(self, text: str) -> str:
45
+ return normalize_text(text, self.case_sensitive, self.alphanumeric_only)
46
+
47
+ def update(self, preds: Sequence[str], targets: Sequence[str]) -> None:
48
+ if len(preds) != len(targets):
49
+ raise ValueError(f"Got {len(preds)} predictions for {len(targets)} targets.")
50
+ for pred, target in zip(preds, targets):
51
+ pred, target = self._normalize(pred), self._normalize(target)
52
+ self._correct += pred == target
53
+ self._edits += _edit_distance(pred, target)
54
+ self._target_chars += len(target)
55
+ self._words += len(targets)
56
+
57
+ def compute(self) -> RecognitionResult:
58
+ return RecognitionResult(
59
+ word_accuracy=self._correct / self._words if self._words else 0.0,
60
+ char_error_rate=self._edits / self._target_chars if self._target_chars else 0.0,
61
+ num_words=self._words,
62
+ )
63
+
64
+
65
+ def normalize_text(text: str, case_sensitive: bool = True, alphanumeric_only: bool = False) -> str:
66
+ """Optionally drop non-alphanumeric characters and lowercase ``text``."""
67
+ if alphanumeric_only:
68
+ text = "".join(c for c in text if c.isalnum())
69
+ return text if case_sensitive else text.lower()
70
+
71
+
72
+ def _edit_distance(a: str, b: str) -> int:
73
+ """Levenshtein distance (unit-cost insert / delete / substitute)."""
74
+ previous = list(range(len(b) + 1))
75
+ for i, ca in enumerate(a, start=1):
76
+ current = [i]
77
+ for j, cb in enumerate(b, start=1):
78
+ current.append(min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + (ca != cb)))
79
+ previous = current
80
+ return previous[-1]
@@ -0,0 +1,37 @@
1
+ """Model components for text detection and recognition.
2
+
3
+ Mirrors ``torchvision.models``: classes, per-architecture builders,
4
+ ``*_Weights`` enums, and the ``get_model`` / ``list_models`` registry.
5
+ """
6
+
7
+ from .detection import (
8
+ DBNet,
9
+ DBNet_MobileNetV3_Large_05_Weights,
10
+ DBNet_ResNet18_VD_Weights,
11
+ DBNetOutput,
12
+ dbnet_mobilenet_v3_large_05,
13
+ dbnet_resnet18,
14
+ dbnet_resnet18_vd,
15
+ )
16
+ from .hub import Weights, WeightsEnum, get_model, get_model_weights, get_weight, list_models
17
+ from .recognition import CRNN, CRNN_ResNet34_VD_Weights, crnn_resnet34_vd, crnn_vgg
18
+
19
+ __all__ = [
20
+ "CRNN",
21
+ "CRNN_ResNet34_VD_Weights",
22
+ "DBNet",
23
+ "DBNetOutput",
24
+ "DBNet_MobileNetV3_Large_05_Weights",
25
+ "DBNet_ResNet18_VD_Weights",
26
+ "Weights",
27
+ "WeightsEnum",
28
+ "crnn_resnet34_vd",
29
+ "crnn_vgg",
30
+ "dbnet_mobilenet_v3_large_05",
31
+ "dbnet_resnet18",
32
+ "dbnet_resnet18_vd",
33
+ "get_model",
34
+ "get_model_weights",
35
+ "get_weight",
36
+ "list_models",
37
+ ]
@@ -0,0 +1,6 @@
1
+ """Backbone networks for torchocr detectors and recognizers."""
2
+
3
+ from .mobilenet_v3 import MobileNetV3
4
+ from .resnet_vd import ResNetVd
5
+
6
+ __all__ = ["MobileNetV3", "ResNetVd"]
@@ -0,0 +1,314 @@
1
+ """MobileNetV3 backbone matching PaddleOCR's det_mobilenet_v3 structure.
2
+
3
+ Provides the backbone for PP-OCRv2/v3 lightweight detectors and
4
+ recognizers. Compared to ResNet-VD this network uses inverted-residual
5
+ blocks (1x1 expand -> depthwise k×k -> 1x1 project) with optional SE
6
+ attention, ``hard_swish`` and ``hard_sigmoid`` activations, and a
7
+ ``make_divisible`` rounding rule for channel counts.
8
+
9
+ Internal module names mirror PaddleOCR
10
+ (``conv``, ``stages``, ``expand_conv``, ``bottleneck_conv``,
11
+ ``linear_conv``, ``mid_se``, ``conv_last``) so checkpoints port over
12
+ with a small mechanical name remap. The public forward returns the
13
+ same ``c2``/``c3``/``c4``/``c5`` dict the existing detector necks
14
+ already consume.
15
+ """
16
+
17
+ from typing import Literal
18
+
19
+ import torch
20
+ from torch import Tensor, nn
21
+ from torch.nn import functional as F
22
+
23
+
24
+ # torch.fx.wrap only patches the globals of the module that calls it, so each
25
+ # backbone module keeps its own wrapped check (see detection._check_dbnet_input).
26
+ @torch.fx.wrap
27
+ def _check_backbone_input(x: Tensor) -> None:
28
+ if x.ndim != 4:
29
+ raise ValueError(f"Expected (B, C, H, W) input; got shape {tuple(x.shape)}.")
30
+
31
+
32
+ def _hard_swish(x: Tensor, inplace: bool = True) -> Tensor:
33
+ """``x * relu6(x + 3) / 6`` -- HardSwish activation."""
34
+ return x * F.relu6(x + 3.0, inplace=inplace) / 6.0
35
+
36
+
37
+ def _hard_sigmoid(x: Tensor, inplace: bool = True) -> Tensor:
38
+ """``relu6(x + 3) / 6`` -- HardSigmoid for SE gates."""
39
+ return F.relu6(x + 3.0, inplace=inplace) / 6.0
40
+
41
+
42
+ def _make_divisible(v: float, divisor: int = 8, min_value: int | None = None) -> int:
43
+ """Round ``v`` to the nearest multiple of ``divisor`` (>= min_value).
44
+
45
+ Mirrors PaddleOCR's ``make_divisible`` so scaled channel counts agree
46
+ bit-for-bit with the trained weights. Without this exact function,
47
+ rounding differences would produce shape mismatches at scale != 1.0.
48
+ """
49
+ if min_value is None:
50
+ min_value = divisor
51
+ new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
52
+ if new_v < 0.9 * v:
53
+ new_v += divisor
54
+ return new_v
55
+
56
+
57
+ class _ConvBNLayer(nn.Module):
58
+ """Conv -> BN -> optional activation, with submodule names ``conv`` / ``bn``."""
59
+
60
+ def __init__(
61
+ self,
62
+ in_channels: int,
63
+ out_channels: int,
64
+ kernel_size: int,
65
+ stride: int,
66
+ padding: int,
67
+ groups: int = 1,
68
+ if_act: bool = True,
69
+ act: str | None = None,
70
+ ) -> None:
71
+ super().__init__()
72
+ self.if_act = if_act
73
+ self.act_kind = act
74
+ self.conv = nn.Conv2d(
75
+ in_channels,
76
+ out_channels,
77
+ kernel_size=kernel_size,
78
+ stride=stride,
79
+ padding=padding,
80
+ groups=groups,
81
+ bias=False,
82
+ )
83
+ self.bn = nn.BatchNorm2d(out_channels)
84
+
85
+ def forward(self, x: Tensor) -> Tensor:
86
+ x = self.conv(x)
87
+ x = self.bn(x)
88
+ if not self.if_act:
89
+ return x
90
+ if self.act_kind == "relu":
91
+ return F.relu(x, inplace=True)
92
+ if self.act_kind == "hard_swish":
93
+ return _hard_swish(x)
94
+ raise ValueError(f"Unknown activation {self.act_kind!r}; expected 'relu' or 'hard_swish'.")
95
+
96
+
97
+ class _SEModule(nn.Module):
98
+ """Channel-attention block: GAP -> 1x1 -> ReLU -> 1x1 -> HardSigmoid -> mul.
99
+
100
+ Internal submodule names ``conv1`` / ``conv2`` match PaddleOCR's
101
+ ``SEModule`` so weights port over without a remap.
102
+ """
103
+
104
+ def __init__(self, in_channels: int, reduction: int = 4) -> None:
105
+ super().__init__()
106
+ self.avg_pool = nn.AdaptiveAvgPool2d(1)
107
+ self.conv1 = nn.Conv2d(in_channels, in_channels // reduction, kernel_size=1, bias=True)
108
+ self.conv2 = nn.Conv2d(in_channels // reduction, in_channels, kernel_size=1, bias=True)
109
+
110
+ def forward(self, x: Tensor) -> Tensor:
111
+ s = self.avg_pool(x)
112
+ s = F.relu(self.conv1(s), inplace=True)
113
+ s = self.conv2(s)
114
+ s = _hard_sigmoid(s)
115
+ return x * s
116
+
117
+
118
+ class _ResidualUnit(nn.Module):
119
+ """Inverted-residual block: 1x1 expand -> depthwise k×k -> optional SE -> 1x1 project."""
120
+
121
+ def __init__(
122
+ self,
123
+ in_channels: int,
124
+ mid_channels: int,
125
+ out_channels: int,
126
+ kernel_size: int,
127
+ stride: int,
128
+ use_se: bool,
129
+ act: str,
130
+ ) -> None:
131
+ super().__init__()
132
+ self.if_shortcut = stride == 1 and in_channels == out_channels
133
+ self.if_se = use_se
134
+ self.expand_conv = _ConvBNLayer(
135
+ in_channels, mid_channels, kernel_size=1, stride=1, padding=0, act=act
136
+ )
137
+ self.bottleneck_conv = _ConvBNLayer(
138
+ mid_channels,
139
+ mid_channels,
140
+ kernel_size=kernel_size,
141
+ stride=stride,
142
+ padding=(kernel_size - 1) // 2,
143
+ groups=mid_channels,
144
+ act=act,
145
+ )
146
+ if use_se:
147
+ self.mid_se = _SEModule(mid_channels)
148
+ self.linear_conv = _ConvBNLayer(
149
+ mid_channels, out_channels, kernel_size=1, stride=1, padding=0, if_act=False
150
+ )
151
+
152
+ def forward(self, x: Tensor) -> Tensor:
153
+ residual = x
154
+ x = self.expand_conv(x)
155
+ x = self.bottleneck_conv(x)
156
+ if self.if_se:
157
+ x = self.mid_se(x)
158
+ x = self.linear_conv(x)
159
+ if self.if_shortcut:
160
+ x = residual + x
161
+ return x
162
+
163
+
164
+ # --------------------------------------------------------------------------------------
165
+ # Architecture configuration tables (k, exp, c, se, nl, s)
166
+ # Source: PaddleOCR2Pytorch det_mobilenet_v3.MobileNetV3, identical so weights port over.
167
+ # --------------------------------------------------------------------------------------
168
+ _CFG_LARGE: tuple[tuple[int, int, int, bool, str, int], ...] = (
169
+ (3, 16, 16, False, "relu", 1),
170
+ (3, 64, 24, False, "relu", 2),
171
+ (3, 72, 24, False, "relu", 1),
172
+ (5, 72, 40, True, "relu", 2),
173
+ (5, 120, 40, True, "relu", 1),
174
+ (5, 120, 40, True, "relu", 1),
175
+ (3, 240, 80, False, "hard_swish", 2),
176
+ (3, 200, 80, False, "hard_swish", 1),
177
+ (3, 184, 80, False, "hard_swish", 1),
178
+ (3, 184, 80, False, "hard_swish", 1),
179
+ (3, 480, 112, True, "hard_swish", 1),
180
+ (3, 672, 112, True, "hard_swish", 1),
181
+ (5, 672, 160, True, "hard_swish", 2),
182
+ (5, 960, 160, True, "hard_swish", 1),
183
+ (5, 960, 160, True, "hard_swish", 1),
184
+ )
185
+ _CLS_CH_SQUEEZE_LARGE = 960
186
+
187
+ _CFG_SMALL: tuple[tuple[int, int, int, bool, str, int], ...] = (
188
+ (3, 16, 16, True, "relu", 2),
189
+ (3, 72, 24, False, "relu", 2),
190
+ (3, 88, 24, False, "relu", 1),
191
+ (5, 96, 40, True, "hard_swish", 2),
192
+ (5, 240, 40, True, "hard_swish", 1),
193
+ (5, 240, 40, True, "hard_swish", 1),
194
+ (5, 120, 48, True, "hard_swish", 1),
195
+ (5, 144, 48, True, "hard_swish", 1),
196
+ (5, 288, 96, True, "hard_swish", 2),
197
+ (5, 576, 96, True, "hard_swish", 1),
198
+ (5, 576, 96, True, "hard_swish", 1),
199
+ )
200
+ _CLS_CH_SQUEEZE_SMALL = 576
201
+
202
+
203
+ _SUPPORTED_SCALES = (0.35, 0.5, 0.75, 1.0, 1.25)
204
+
205
+
206
+ class MobileNetV3(nn.Module):
207
+ """MobileNetV3 backbone returning a four-level feature pyramid.
208
+
209
+ Args:
210
+ in_channels: Number of input image channels. Default 3.
211
+ model_name: ``"large"`` (default, used by PP-OCRv3 detector) or
212
+ ``"small"``.
213
+ scale: Channel-width multiplier. Must be one of
214
+ ``{0.35, 0.5, 0.75, 1.0, 1.25}``. PP-OCRv3 detector uses
215
+ ``0.5``.
216
+ disable_se: If True, ignore the per-block ``use_se`` flags. The
217
+ PP-OCRv3 *detector* uses this; recognizer keeps SE blocks.
218
+
219
+ Forward signature:
220
+ Input ``(B, in_channels, H, W)`` with H, W divisible by 32.
221
+ Output ``dict[str, Tensor]`` with keys ``c2``, ``c3``, ``c4``,
222
+ ``c5`` at strides 4, 8, 16, 32.
223
+ """
224
+
225
+ def __init__(
226
+ self,
227
+ in_channels: int = 3,
228
+ model_name: Literal["large", "small"] = "large",
229
+ scale: float = 0.5,
230
+ disable_se: bool = False,
231
+ ) -> None:
232
+ super().__init__()
233
+ if scale not in _SUPPORTED_SCALES:
234
+ raise ValueError(
235
+ f"scale must be one of {_SUPPORTED_SCALES}; got {scale}."
236
+ )
237
+ if model_name == "large":
238
+ cfg, cls_ch_squeeze = _CFG_LARGE, _CLS_CH_SQUEEZE_LARGE
239
+ elif model_name == "small":
240
+ cfg, cls_ch_squeeze = _CFG_SMALL, _CLS_CH_SQUEEZE_SMALL
241
+ else:
242
+ raise ValueError(f"model_name must be 'large' or 'small'; got {model_name!r}.")
243
+
244
+ self.disable_se = disable_se
245
+ self.model_name = model_name
246
+ self.scale = scale
247
+
248
+ inplanes = _make_divisible(16 * scale)
249
+ self.conv = _ConvBNLayer(
250
+ in_channels=in_channels,
251
+ out_channels=inplanes,
252
+ kernel_size=3,
253
+ stride=2,
254
+ padding=1,
255
+ act="hard_swish",
256
+ )
257
+
258
+ # Walk the cfg table, breaking into stages whenever a stride-2 unit
259
+ # appears AFTER index 2 (matches PaddleOCR's exact stage segmentation).
260
+ self.stages = nn.ModuleList()
261
+ out_channels: list[int] = []
262
+ block_list: list[nn.Module] = []
263
+ for i, (k, exp, c, use_se, nl, s) in enumerate(cfg):
264
+ if s == 2 and i > 2:
265
+ out_channels.append(inplanes)
266
+ self.stages.append(nn.Sequential(*block_list))
267
+ block_list = []
268
+ block_list.append(
269
+ _ResidualUnit(
270
+ in_channels=inplanes,
271
+ mid_channels=_make_divisible(scale * exp),
272
+ out_channels=_make_divisible(scale * c),
273
+ kernel_size=k,
274
+ stride=s,
275
+ use_se=use_se and not disable_se,
276
+ act=nl,
277
+ )
278
+ )
279
+ inplanes = _make_divisible(scale * c)
280
+
281
+ # The final 1x1 ConvBNLayer (``conv_last``) goes at the tail of the
282
+ # last stage in PaddleOCR's checkpoint layout.
283
+ block_list.append(
284
+ _ConvBNLayer(
285
+ in_channels=inplanes,
286
+ out_channels=_make_divisible(scale * cls_ch_squeeze),
287
+ kernel_size=1,
288
+ stride=1,
289
+ padding=0,
290
+ act="hard_swish",
291
+ )
292
+ )
293
+ out_channels.append(_make_divisible(scale * cls_ch_squeeze))
294
+ self.stages.append(nn.Sequential(*block_list))
295
+ self._out_channels = tuple(out_channels)
296
+
297
+ @property
298
+ def out_channels(self) -> tuple[int, ...]:
299
+ """Channel counts at strides 4, 8, 16, 32."""
300
+ return self._out_channels
301
+
302
+ def forward(self, x: Tensor) -> dict[str, Tensor]:
303
+ _check_backbone_input(x)
304
+ x = self.conv(x)
305
+ feats: list[Tensor] = []
306
+ for stage in self.stages:
307
+ x = stage(x)
308
+ feats.append(x)
309
+ if len(feats) != 4:
310
+ raise RuntimeError(
311
+ f"MobileNetV3 produced {len(feats)} stages; expected 4. "
312
+ "This indicates an architectural drift from PaddleOCR's reference."
313
+ )
314
+ return {"c2": feats[0], "c3": feats[1], "c4": feats[2], "c5": feats[3]}