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
torchocr/models/hub.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Pretrained-weight API and model registry, mirroring ``torchvision.models``.
|
|
2
|
+
|
|
3
|
+
Each architecture with published checkpoints exposes a :class:`WeightsEnum`
|
|
4
|
+
subclass (e.g. ``DBNet_ResNet18_VD_Weights``) whose members bundle the
|
|
5
|
+
checkpoint URL, the preprocessing it was trained with, and metadata
|
|
6
|
+
including benchmark numbers::
|
|
7
|
+
|
|
8
|
+
weights = DBNet_ResNet18_VD_Weights.DEFAULT
|
|
9
|
+
model = dbnet_resnet18_vd(weights=weights).eval()
|
|
10
|
+
preprocess = weights.transforms()
|
|
11
|
+
weights.meta["_metrics"] # reproducible with references/detection/evaluate.py
|
|
12
|
+
|
|
13
|
+
Checkpoint file names embed the first 8 hex digits of their SHA-256
|
|
14
|
+
(``name-<hash>.pth``); downloads are verified against it, so a corrected
|
|
15
|
+
checkpoint always gets a new name and stale ``torch.hub`` caches cannot
|
|
16
|
+
shadow it.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import warnings
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from enum import Enum
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
from typing import Any, TypeVar
|
|
25
|
+
|
|
26
|
+
import torch
|
|
27
|
+
from torch import nn
|
|
28
|
+
from torch.hub import HASH_REGEX, download_url_to_file, load_state_dict_from_url
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
BASE_URL = "https://huggingface.co/BryanBradfo/torchocr-weights/resolve/main"
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"BASE_URL",
|
|
35
|
+
"HASH_REGEX",
|
|
36
|
+
"Weights",
|
|
37
|
+
"WeightsEnum",
|
|
38
|
+
"download_asset",
|
|
39
|
+
"get_model",
|
|
40
|
+
"get_model_weights",
|
|
41
|
+
"get_weight",
|
|
42
|
+
"list_models",
|
|
43
|
+
"register_model",
|
|
44
|
+
"zero_subnormals_",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Weights:
|
|
50
|
+
"""One published checkpoint.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
url: Download URL; the file name carries a SHA-256 prefix.
|
|
54
|
+
transforms: Zero-argument factory for the inference preset the
|
|
55
|
+
checkpoint expects (call it: ``weights.transforms()``).
|
|
56
|
+
meta: Free-form metadata. Keys shared by every torchocr checkpoint:
|
|
57
|
+
``task``, ``backbone``, ``num_params``, ``source``, ``license``,
|
|
58
|
+
``_metrics`` (benchmark -> scores) and ``_docs``.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
url: str
|
|
62
|
+
transforms: Callable[..., nn.Module]
|
|
63
|
+
meta: dict[str, Any]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class WeightsEnum(Enum):
|
|
67
|
+
"""Base class for the per-architecture weights enums.
|
|
68
|
+
|
|
69
|
+
A ``DEFAULT`` member aliases the recommended checkpoint.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def verify(cls, obj: "WeightsEnum | str | None") -> "WeightsEnum | None":
|
|
74
|
+
"""Resolve ``obj`` (member, member name, or ``"Cls.NAME"``) to a member of ``cls``."""
|
|
75
|
+
if obj is None or isinstance(obj, cls):
|
|
76
|
+
return obj
|
|
77
|
+
if isinstance(obj, str):
|
|
78
|
+
name = obj.removeprefix(f"{cls.__name__}.")
|
|
79
|
+
if name in cls.__members__:
|
|
80
|
+
return cls[name]
|
|
81
|
+
raise ValueError(
|
|
82
|
+
f"Unknown weights '{obj}' for {cls.__name__}. Available: {sorted(cls.__members__)}."
|
|
83
|
+
)
|
|
84
|
+
raise ValueError(f"Expected {cls.__name__} or one of its member names; got {obj!r}.")
|
|
85
|
+
|
|
86
|
+
def get_state_dict(self, progress: bool = True) -> dict[str, Any]:
|
|
87
|
+
return load_state_dict_from_url(
|
|
88
|
+
self.url, map_location="cpu", progress=progress, check_hash=True, weights_only=True
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
def __repr__(self) -> str:
|
|
92
|
+
return f"{type(self).__name__}.{self._name_}"
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def url(self) -> str:
|
|
96
|
+
return self.value.url
|
|
97
|
+
|
|
98
|
+
@property
|
|
99
|
+
def transforms(self) -> Callable[..., nn.Module]:
|
|
100
|
+
return self.value.transforms
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def meta(self) -> dict[str, Any]:
|
|
104
|
+
return self.value.meta
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def load_weights(model: nn.Module, weights: WeightsEnum, progress: bool = True) -> None:
|
|
108
|
+
"""Load ``weights`` into ``model``; on network failure, warn and keep random init.
|
|
109
|
+
|
|
110
|
+
Only connectivity errors (``OSError``, which covers ``URLError`` and
|
|
111
|
+
HTTP errors) fall back. Hash mismatches and incompatible checkpoints
|
|
112
|
+
raise, because silently running random weights would hide them.
|
|
113
|
+
"""
|
|
114
|
+
try:
|
|
115
|
+
state_dict = weights.get_state_dict(progress=progress)
|
|
116
|
+
except OSError as exc:
|
|
117
|
+
warnings.warn(
|
|
118
|
+
f"Could not download {weights!r} from {weights.url} ({type(exc).__name__}: {exc}). "
|
|
119
|
+
"Falling back to random initialization.",
|
|
120
|
+
stacklevel=3,
|
|
121
|
+
)
|
|
122
|
+
return
|
|
123
|
+
model.load_state_dict(state_dict)
|
|
124
|
+
zero_subnormals_(model)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
@torch.no_grad()
|
|
128
|
+
def zero_subnormals_(module: nn.Module) -> int:
|
|
129
|
+
"""Replace subnormal floats in ``module``'s parameters and buffers by exact zeros, in place.
|
|
130
|
+
|
|
131
|
+
Weight decay drives dead channels to ~1e-40. Those values are numerically
|
|
132
|
+
zero but hit x86's slow subnormal path on every multiply, and oneDNN
|
|
133
|
+
convolutions ignore ``torch.set_flush_denormal``: PaddleOCR's CRNN runs
|
|
134
|
+
~14x slower on CPU because of them. Outputs are unchanged.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
The number of values zeroed.
|
|
138
|
+
"""
|
|
139
|
+
zeroed = 0
|
|
140
|
+
for tensor in module.state_dict().values():
|
|
141
|
+
if tensor.is_floating_point():
|
|
142
|
+
subnormal = (tensor != 0) & (tensor.abs() < torch.finfo(tensor.dtype).tiny)
|
|
143
|
+
zeroed += int(subnormal.sum())
|
|
144
|
+
tensor.masked_fill_(subnormal, 0)
|
|
145
|
+
return zeroed
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def download_asset(url: str, progress: bool = True) -> Path:
|
|
149
|
+
"""Fetch a non-checkpoint file (e.g. a language model) into the torch.hub cache.
|
|
150
|
+
|
|
151
|
+
Like checkpoints, asset names embed a SHA-256 prefix (``name-<hash>.ext``)
|
|
152
|
+
that is verified on download; cached files are reused as-is.
|
|
153
|
+
"""
|
|
154
|
+
name = url.rsplit("/", 1)[-1]
|
|
155
|
+
destination = Path(torch.hub.get_dir()) / "checkpoints" / name
|
|
156
|
+
if not destination.exists():
|
|
157
|
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
158
|
+
match = HASH_REGEX.search(name)
|
|
159
|
+
download_url_to_file(url, str(destination), hash_prefix=match.group(1) if match else None, progress=progress)
|
|
160
|
+
return destination
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
# === Registry ===
|
|
164
|
+
|
|
165
|
+
M = TypeVar("M", bound=nn.Module)
|
|
166
|
+
|
|
167
|
+
_MODELS: dict[str, Callable[..., nn.Module]] = {}
|
|
168
|
+
_MODEL_WEIGHTS: dict[str, type[WeightsEnum] | None] = {}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def register_model(
|
|
172
|
+
name: str, weights: type[WeightsEnum] | None = None
|
|
173
|
+
) -> Callable[[Callable[..., M]], Callable[..., M]]:
|
|
174
|
+
"""Decorator registering a model builder under ``name``."""
|
|
175
|
+
|
|
176
|
+
def wrapper(builder: Callable[..., M]) -> Callable[..., M]:
|
|
177
|
+
if name in _MODELS:
|
|
178
|
+
raise ValueError(f"Model '{name}' is already registered.")
|
|
179
|
+
_MODELS[name] = builder
|
|
180
|
+
_MODEL_WEIGHTS[name] = weights
|
|
181
|
+
return builder
|
|
182
|
+
|
|
183
|
+
return wrapper
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def list_models() -> list[str]:
|
|
187
|
+
"""Sorted names of every registered model builder."""
|
|
188
|
+
return sorted(_MODELS)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _check_name(name: str) -> None:
|
|
192
|
+
if name not in _MODELS:
|
|
193
|
+
raise ValueError(f"Unknown model '{name}'. Available: {list_models()}.")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def get_model(name: str, **config: Any) -> nn.Module:
|
|
197
|
+
"""Build a registered model, e.g. ``get_model("dbnet_resnet18_vd", weights="DEFAULT")``."""
|
|
198
|
+
_check_name(name)
|
|
199
|
+
return _MODELS[name](**config)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def get_model_weights(name: str) -> type[WeightsEnum] | None:
|
|
203
|
+
"""The weights enum of a registered model, or ``None`` if it has no published weights."""
|
|
204
|
+
_check_name(name)
|
|
205
|
+
return _MODEL_WEIGHTS[name]
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def get_weight(name: str) -> WeightsEnum:
|
|
209
|
+
"""Resolve a fully-qualified ``"Cls.NAME"`` string, e.g. ``"DBNet_ResNet18_VD_Weights.DEFAULT"``."""
|
|
210
|
+
enum_name, _, member = name.partition(".")
|
|
211
|
+
if not member:
|
|
212
|
+
raise ValueError(f"Expected a fully-qualified 'Cls.NAME' weights name; got '{name}'.")
|
|
213
|
+
enums = {e.__name__: e for e in _MODEL_WEIGHTS.values() if e is not None}
|
|
214
|
+
if enum_name not in enums:
|
|
215
|
+
raise ValueError(f"Unknown weights enum '{enum_name}'. Available: {sorted(enums)}.")
|
|
216
|
+
return enums[enum_name].verify(member)
|
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
"""Text recognition model definitions."""
|
|
2
|
+
|
|
3
|
+
from functools import partial
|
|
4
|
+
from typing import Literal
|
|
5
|
+
|
|
6
|
+
import torch
|
|
7
|
+
from torch import Tensor, nn
|
|
8
|
+
|
|
9
|
+
from ..transforms import RecognitionPreset
|
|
10
|
+
from .backbones import ResNetVd
|
|
11
|
+
from .hub import BASE_URL, Weights, WeightsEnum, get_weight, load_weights, register_model
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
BackboneName = Literal["vgg", "resnet34_vd"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
# Shape checks live in module-level functions marked torch.fx.wrap so FX records
|
|
18
|
+
# them as opaque calls rather than tracing Python ifs on proxies (see
|
|
19
|
+
# torchocr.models.detection._check_dbnet_input).
|
|
20
|
+
@torch.fx.wrap
|
|
21
|
+
def _check_crnn_input(images: Tensor) -> None:
|
|
22
|
+
if images.ndim != 4 or images.shape[2] != 32:
|
|
23
|
+
raise ValueError(f"CRNN expects (B, C, 32, W); got {tuple(images.shape)}.")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@torch.fx.wrap
|
|
27
|
+
def _check_im2seq_input(x: Tensor) -> None:
|
|
28
|
+
if x.shape[2] != 1:
|
|
29
|
+
raise ValueError(
|
|
30
|
+
f"Im2Seq expects (B, C, 1, T); got shape {tuple(x.shape)}. "
|
|
31
|
+
"The recognizer backbone must collapse height to 1 before this layer."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class CRNN_ResNet34_VD_Weights(WeightsEnum):
|
|
36
|
+
PPOCR_SERVER_V2 = Weights(
|
|
37
|
+
url=f"{BASE_URL}/crnn_resnet34_vd_ppocr_server_v2-803ba4c9.pth",
|
|
38
|
+
# PaddleOCR rec: BGR pixels, (x - 127.5) / 127.5, height 32.
|
|
39
|
+
transforms=partial(RecognitionPreset, height=32, max_width=320, channel_order="bgr"),
|
|
40
|
+
meta={
|
|
41
|
+
"task": "recognition",
|
|
42
|
+
"backbone": "resnet34_vd",
|
|
43
|
+
"num_params": 27_860_673,
|
|
44
|
+
"num_classes": 6625,
|
|
45
|
+
"charset": "ppocr_keys_v1", # torchocr.charsets.load_charset
|
|
46
|
+
"source": "PaddleOCR ch_ppocr_server_v2.0_rec_train, via scripts/convert_paddle_crnn.py",
|
|
47
|
+
"license": "Apache-2.0",
|
|
48
|
+
"languages": ["ch", "en"],
|
|
49
|
+
"_metrics": {
|
|
50
|
+
"ICDAR2015-test-gt-quads": {"word_accuracy": 0.6649, "char_error_rate": 0.1333},
|
|
51
|
+
},
|
|
52
|
+
"_docs": (
|
|
53
|
+
"Chinese + English line recognizer (CTC, 6623 characters + blank) trained by "
|
|
54
|
+
"PaddleOCR mostly on document and street-sign text lines. Benchmark: the 2077 "
|
|
55
|
+
"alphanumeric care words of ICDAR-2015 test, cropped from the full images with "
|
|
56
|
+
"torchocr.ops.crop_quads on their ground-truth quads, scored case-insensitively "
|
|
57
|
+
"over letters and digits (not the official Task 4.3 crops). Axis-aligned crops of "
|
|
58
|
+
"the same words score 0.5787 -- rotated scene text needs quad rectification. "
|
|
59
|
+
"Reproduce with references/recognition/evaluate.py."
|
|
60
|
+
),
|
|
61
|
+
},
|
|
62
|
+
)
|
|
63
|
+
ICDAR2015 = Weights(
|
|
64
|
+
url=f"{BASE_URL}/crnn_resnet34_vd_ic15-da0782b5.pth",
|
|
65
|
+
transforms=partial(RecognitionPreset, height=32, max_width=320, channel_order="bgr"),
|
|
66
|
+
meta={
|
|
67
|
+
"task": "recognition",
|
|
68
|
+
"backbone": "resnet34_vd",
|
|
69
|
+
"num_params": 27_860_673,
|
|
70
|
+
"num_classes": 6625,
|
|
71
|
+
"charset": "ppocr_keys_v1", # torchocr.charsets.load_charset
|
|
72
|
+
"source": (
|
|
73
|
+
"torchocr: PPOCR_SERVER_V2 fine-tuned 30 epochs on the 4467 legible ICDAR-2015 training "
|
|
74
|
+
"words (crop_quads on jittered ground-truth quads) with references/recognition/train.py"
|
|
75
|
+
),
|
|
76
|
+
"license": "Apache-2.0 (base weights); fine-tuned on ICDAR 2015, released for research use",
|
|
77
|
+
"languages": ["en"],
|
|
78
|
+
"_metrics": {
|
|
79
|
+
"ICDAR2015-test-gt-quads": {"word_accuracy": 0.7376, "char_error_rate": 0.1010},
|
|
80
|
+
},
|
|
81
|
+
"_docs": (
|
|
82
|
+
"Scene-text word recognizer (CTC). Same benchmark protocol as PPOCR_SERVER_V2: the 2077 "
|
|
83
|
+
"alphanumeric care words of ICDAR-2015 test cropped with crop_quads on their ground-truth "
|
|
84
|
+
"quads, case-insensitive. Last epoch, no checkpoint selected on the test set. The charset is "
|
|
85
|
+
"still PaddleOCR's Chinese + Latin one, but fine-tuning used Latin scene text only, so "
|
|
86
|
+
"Chinese accuracy is not guaranteed. Reproduce with references/recognition/evaluate.py."
|
|
87
|
+
),
|
|
88
|
+
},
|
|
89
|
+
)
|
|
90
|
+
ICDAR2015_TOTALTEXT_MLT19 = Weights(
|
|
91
|
+
url=f"{BASE_URL}/crnn_resnet34_vd_scene-38393899.pth",
|
|
92
|
+
transforms=partial(RecognitionPreset, height=32, max_width=320, channel_order="bgr"),
|
|
93
|
+
meta={
|
|
94
|
+
"task": "recognition",
|
|
95
|
+
"backbone": "resnet34_vd",
|
|
96
|
+
"num_params": 27_860_673,
|
|
97
|
+
"num_classes": 6625,
|
|
98
|
+
"charset": "ppocr_keys_v1", # torchocr.charsets.load_charset
|
|
99
|
+
"decoder": {
|
|
100
|
+
"type": "ctc_beam",
|
|
101
|
+
"beam_width": 10,
|
|
102
|
+
"lm_weight": 0.2,
|
|
103
|
+
"lm_url": f"{BASE_URL}/charlm6_scene-883dd7cd.json",
|
|
104
|
+
},
|
|
105
|
+
"source": (
|
|
106
|
+
"torchocr: PPOCR_SERVER_V2 fine-tuned 10 epochs (bf16) on 66k Latin scene words: ICDAR-2015 "
|
|
107
|
+
"train (x2), Total-Text train and MLT-2019 Latin crops, with references/recognition/train.py"
|
|
108
|
+
),
|
|
109
|
+
"license": (
|
|
110
|
+
"Apache-2.0 (base weights); fine-tuned on ICDAR 2015, Total-Text and MLT 2019, released for "
|
|
111
|
+
"research use"
|
|
112
|
+
),
|
|
113
|
+
"languages": ["en", "fr", "de", "it", "es", "pt"],
|
|
114
|
+
"_metrics": {
|
|
115
|
+
"ICDAR2015-test-gt-quads": {"word_accuracy": 0.7906, "char_error_rate": 0.0812},
|
|
116
|
+
"TotalText-test-gt-quads": {"word_accuracy": 0.8018, "char_error_rate": 0.0951},
|
|
117
|
+
},
|
|
118
|
+
"_docs": (
|
|
119
|
+
"Latin scene-text word recognizer. Decoded with CTC beam search (width 10) and a "
|
|
120
|
+
"case-insensitive 6-gram character language model built from the training transcriptions "
|
|
121
|
+
"only; beam width and LM weight were chosen on Total-Text *training* words. Same benchmark "
|
|
122
|
+
"protocol as PPOCR_SERVER_V2 (ground-truth quads cropped with crop_quads, case-insensitive). "
|
|
123
|
+
"Last epoch, no checkpoint selected on any test set. Chinese is no longer supported in "
|
|
124
|
+
"practice. Reproduce with references/recognition/evaluate.py."
|
|
125
|
+
),
|
|
126
|
+
},
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
MJSYNTH_ICDAR2015_TOTALTEXT_MLT19 = Weights(
|
|
130
|
+
url=f"{BASE_URL}/crnn_resnet34_vd_synth-513c0334.pth",
|
|
131
|
+
transforms=partial(RecognitionPreset, height=32, max_width=320, channel_order="bgr"),
|
|
132
|
+
meta={
|
|
133
|
+
"task": "recognition",
|
|
134
|
+
"backbone": "resnet34_vd",
|
|
135
|
+
"num_params": 27_860_673,
|
|
136
|
+
"num_classes": 6625,
|
|
137
|
+
"charset": "ppocr_keys_v1", # torchocr.charsets.load_charset
|
|
138
|
+
"decoder": {
|
|
139
|
+
"type": "ctc_beam",
|
|
140
|
+
"beam_width": 10,
|
|
141
|
+
"lm_weight": 0.2,
|
|
142
|
+
"lm_url": f"{BASE_URL}/charlm6_scene-883dd7cd.json",
|
|
143
|
+
},
|
|
144
|
+
"source": (
|
|
145
|
+
"torchocr: ICDAR2015_TOTALTEXT_MLT19 fine-tuned 6 more epochs (bf16), each drawing 370k words "
|
|
146
|
+
"at random: the 66k real Latin scene words (ICDAR-2015 train x2, Total-Text train, MLT-2019 "
|
|
147
|
+
"Latin crops) once on average, plus 300k of the 7.2M MJSynth synthetic words, with "
|
|
148
|
+
"references/recognition/train.py"
|
|
149
|
+
),
|
|
150
|
+
"license": (
|
|
151
|
+
"Apache-2.0 (base weights); fine-tuned on ICDAR 2015, Total-Text, MLT 2019 and MJSynth, "
|
|
152
|
+
"released for research use"
|
|
153
|
+
),
|
|
154
|
+
"languages": ["en", "fr", "de", "it", "es", "pt"],
|
|
155
|
+
"_metrics": {
|
|
156
|
+
"ICDAR2015-test-gt-quads": {"word_accuracy": 0.7987, "char_error_rate": 0.0789},
|
|
157
|
+
"TotalText-test-gt-quads": {"word_accuracy": 0.8190, "char_error_rate": 0.0924},
|
|
158
|
+
},
|
|
159
|
+
"_docs": (
|
|
160
|
+
"Latin scene-text word recognizer, ICDAR2015_TOTALTEXT_MLT19 further trained with MJSynth "
|
|
161
|
+
"synthetic words mixed into every epoch. Decoded like its parent, with the same CTC beam "
|
|
162
|
+
"search (width 10) and 6-gram character language model (built from real training "
|
|
163
|
+
"transcriptions only; beam width and LM weight were chosen on Total-Text *training* words). "
|
|
164
|
+
"Same benchmark protocol as PPOCR_SERVER_V2 (ground-truth quads cropped with crop_quads, case-insensitive). "
|
|
165
|
+
"Last epoch, no checkpoint selected on any test set. Chinese is no longer supported in "
|
|
166
|
+
"practice. Reproduce with references/recognition/evaluate.py."
|
|
167
|
+
),
|
|
168
|
+
},
|
|
169
|
+
)
|
|
170
|
+
DEFAULT = PPOCR_SERVER_V2
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
_WEIGHTS_BY_BACKBONE: dict[str, type[WeightsEnum]] = {"resnet34_vd": CRNN_ResNet34_VD_Weights}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class _Im2Seq(nn.Module):
|
|
177
|
+
"""Collapse a height-1 feature map into a sequence.
|
|
178
|
+
|
|
179
|
+
Input ``(B, C, 1, T)`` -> output ``(B, T, C)``. PaddleOCR's
|
|
180
|
+
``ppocr.modeling.necks.SequenceEncoder.encoder_reshape`` does the
|
|
181
|
+
same thing; we mirror its module name so weights port over without
|
|
182
|
+
a remap.
|
|
183
|
+
"""
|
|
184
|
+
|
|
185
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
186
|
+
_check_im2seq_input(x)
|
|
187
|
+
return x.squeeze(2).permute(0, 2, 1)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
class _RNNEncoder(nn.Module):
|
|
191
|
+
"""2-layer bidirectional LSTM (batch_first), matching PaddleOCR's EncoderWithRNN."""
|
|
192
|
+
|
|
193
|
+
def __init__(self, in_channels: int, hidden: int) -> None:
|
|
194
|
+
super().__init__()
|
|
195
|
+
self.lstm = nn.LSTM(
|
|
196
|
+
input_size=in_channels,
|
|
197
|
+
hidden_size=hidden,
|
|
198
|
+
num_layers=2,
|
|
199
|
+
batch_first=True,
|
|
200
|
+
bidirectional=True,
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
204
|
+
out, _ = self.lstm(x)
|
|
205
|
+
return out
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
class _SequenceEncoder(nn.Module):
|
|
209
|
+
"""Im2Seq + RNN encoder, structured to match PaddleOCR exactly.
|
|
210
|
+
|
|
211
|
+
State-dict layout: ``encoder_reshape.*`` (no params, just the
|
|
212
|
+
reshape) and ``encoder.lstm.*`` (the LSTM). PyTorch's
|
|
213
|
+
``nn.LSTM`` parameter names (``weight_ih_l0``,
|
|
214
|
+
``weight_hh_l0_reverse``, ...) line up 1:1 with PaddleOCR's flat
|
|
215
|
+
LSTM-export naming, so no transposes are needed.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
def __init__(self, in_channels: int, hidden: int) -> None:
|
|
219
|
+
super().__init__()
|
|
220
|
+
self.encoder_reshape = _Im2Seq()
|
|
221
|
+
self.encoder = _RNNEncoder(in_channels, hidden)
|
|
222
|
+
|
|
223
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
224
|
+
x = self.encoder_reshape(x)
|
|
225
|
+
return self.encoder(x)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class _CTCHead(nn.Module):
|
|
229
|
+
"""Single Linear classifier, matching PaddleOCR's CTCHead (no mid_channels)."""
|
|
230
|
+
|
|
231
|
+
def __init__(self, in_channels: int, num_classes: int) -> None:
|
|
232
|
+
super().__init__()
|
|
233
|
+
self.fc = nn.Linear(in_channels, num_classes)
|
|
234
|
+
|
|
235
|
+
def forward(self, x: Tensor) -> Tensor:
|
|
236
|
+
return self.fc(x)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class CRNN(nn.Module):
|
|
240
|
+
"""CRNN recognizer.
|
|
241
|
+
|
|
242
|
+
Two backbone variants share a single forward contract:
|
|
243
|
+
|
|
244
|
+
- ``backbone="vgg"`` (default): the original Shi et al. 2015
|
|
245
|
+
VGG-style CNN with one deviation -- the final ``conv7`` uses
|
|
246
|
+
``kernel_size=(2, 1)`` so the output width matches ``W // 4``
|
|
247
|
+
exactly. This is what torchocr trains from scratch.
|
|
248
|
+
- ``backbone="resnet34_vd"``: the PaddleOCR-compatible recognizer
|
|
249
|
+
stack -- ResNet-34-VD backbone (with recognizer-style ``(2, 1)``
|
|
250
|
+
strides so width is preserved), 2-layer BiLSTM, single Linear
|
|
251
|
+
head. Parameter shapes and naming align with PaddleOCR weights
|
|
252
|
+
so ``scripts/convert_paddle_crnn.py`` produces drop-in
|
|
253
|
+
checkpoints.
|
|
254
|
+
|
|
255
|
+
Args:
|
|
256
|
+
num_classes: Number of output classes including the CTC blank.
|
|
257
|
+
Required without ``weights`` -- the caller must commit to a
|
|
258
|
+
charset. With ``weights`` it defaults to
|
|
259
|
+
``weights.meta["num_classes"]`` and must equal it if given.
|
|
260
|
+
backbone: ``"vgg"`` or ``"resnet34_vd"``. Default ``None``:
|
|
261
|
+
taken from ``weights`` when it is an enum member, else
|
|
262
|
+
``"vgg"``.
|
|
263
|
+
weights: Pretrained weights -- a :class:`CRNN_ResNet34_VD_Weights`
|
|
264
|
+
member or a member name such as ``"DEFAULT"``. If the download
|
|
265
|
+
fails a ``UserWarning`` is emitted and the model keeps its
|
|
266
|
+
random initialization. Default ``None``.
|
|
267
|
+
input_channels: Channels in the input crops. Default 3.
|
|
268
|
+
rnn_hidden: Hidden size of each BiLSTM direction. Default 256.
|
|
269
|
+
|
|
270
|
+
Forward:
|
|
271
|
+
Inputs are crops of shape ``(B, input_channels, 32, W)`` with
|
|
272
|
+
``W >= 16``. Output is ``(T, B, num_classes)`` logits where
|
|
273
|
+
``T = W // 4``. ``log_softmax`` is not applied -- pass logits
|
|
274
|
+
directly to ``nn.CTCLoss(zero_infinity=True)`` after a
|
|
275
|
+
``log_softmax(dim=-1)`` at training time.
|
|
276
|
+
|
|
277
|
+
Graph capture:
|
|
278
|
+
FX-traceable and ``torch.export``-able with a dynamic batch size. The
|
|
279
|
+
crop width must be static under ``torch.export`` (it specializes
|
|
280
|
+
``nn.LSTM``'s sequence length) -- which matches inference, where
|
|
281
|
+
:func:`torchocr.ops.crop_quads` pads every crop to ``max_width``.
|
|
282
|
+
``torch.compile`` works but graph-breaks at the LSTM (a Dynamo
|
|
283
|
+
limitation), so ``fullgraph=True`` is not supported.
|
|
284
|
+
"""
|
|
285
|
+
|
|
286
|
+
def __init__(
|
|
287
|
+
self,
|
|
288
|
+
num_classes: int | None = None,
|
|
289
|
+
backbone: BackboneName | None = None,
|
|
290
|
+
weights: WeightsEnum | str | None = None,
|
|
291
|
+
input_channels: int = 3,
|
|
292
|
+
rnn_hidden: int = 256,
|
|
293
|
+
) -> None:
|
|
294
|
+
super().__init__()
|
|
295
|
+
if isinstance(weights, str) and "." in weights:
|
|
296
|
+
weights = get_weight(weights) # "Cls.NAME" names the architecture too
|
|
297
|
+
if backbone is None:
|
|
298
|
+
backbone = weights.meta["backbone"] if isinstance(weights, WeightsEnum) else "vgg"
|
|
299
|
+
if weights is not None:
|
|
300
|
+
if backbone not in _WEIGHTS_BY_BACKBONE:
|
|
301
|
+
raise ValueError(
|
|
302
|
+
f"No pretrained weights are published for backbone '{backbone}'. "
|
|
303
|
+
f"Backbones with weights: {sorted(_WEIGHTS_BY_BACKBONE)}."
|
|
304
|
+
)
|
|
305
|
+
weights = _WEIGHTS_BY_BACKBONE[backbone].verify(weights)
|
|
306
|
+
expected = weights.meta["num_classes"]
|
|
307
|
+
if num_classes is None:
|
|
308
|
+
num_classes = expected
|
|
309
|
+
elif num_classes != expected:
|
|
310
|
+
raise ValueError(f"{weights!r} has num_classes={expected}; got num_classes={num_classes}.")
|
|
311
|
+
if num_classes is None:
|
|
312
|
+
raise ValueError("num_classes is required when no pretrained weights are given.")
|
|
313
|
+
self.backbone_name = backbone
|
|
314
|
+
|
|
315
|
+
if backbone == "vgg":
|
|
316
|
+
self.cnn = nn.Sequential(
|
|
317
|
+
nn.Conv2d(input_channels, 64, kernel_size=3, padding=1),
|
|
318
|
+
nn.ReLU(inplace=True),
|
|
319
|
+
nn.MaxPool2d(kernel_size=2, stride=2),
|
|
320
|
+
nn.Conv2d(64, 128, kernel_size=3, padding=1),
|
|
321
|
+
nn.ReLU(inplace=True),
|
|
322
|
+
nn.MaxPool2d(kernel_size=2, stride=2),
|
|
323
|
+
nn.Conv2d(128, 256, kernel_size=3, padding=1, bias=False),
|
|
324
|
+
nn.BatchNorm2d(256),
|
|
325
|
+
nn.ReLU(inplace=True),
|
|
326
|
+
nn.Conv2d(256, 256, kernel_size=3, padding=1),
|
|
327
|
+
nn.ReLU(inplace=True),
|
|
328
|
+
nn.MaxPool2d(kernel_size=(2, 1), stride=(2, 1)),
|
|
329
|
+
nn.Conv2d(256, 512, kernel_size=3, padding=1, bias=False),
|
|
330
|
+
nn.BatchNorm2d(512),
|
|
331
|
+
nn.ReLU(inplace=True),
|
|
332
|
+
nn.Conv2d(512, 512, kernel_size=3, padding=1),
|
|
333
|
+
nn.ReLU(inplace=True),
|
|
334
|
+
nn.MaxPool2d(kernel_size=(2, 1), stride=(2, 1)),
|
|
335
|
+
nn.Conv2d(512, 512, kernel_size=(2, 1)),
|
|
336
|
+
nn.ReLU(inplace=True),
|
|
337
|
+
)
|
|
338
|
+
self.rnn = nn.LSTM(
|
|
339
|
+
input_size=512,
|
|
340
|
+
hidden_size=rnn_hidden,
|
|
341
|
+
num_layers=2,
|
|
342
|
+
bidirectional=True,
|
|
343
|
+
)
|
|
344
|
+
self.classifier = nn.Linear(rnn_hidden * 2, num_classes)
|
|
345
|
+
elif backbone == "resnet34_vd":
|
|
346
|
+
self.backbone = ResNetVd(
|
|
347
|
+
depth=34,
|
|
348
|
+
in_channels=input_channels,
|
|
349
|
+
downsample_stride=(2, 1),
|
|
350
|
+
stem_stride=1, # rec keeps stem at full resolution
|
|
351
|
+
final_pool=True, # rec adds an extra MaxPool(2, 2) at the end
|
|
352
|
+
)
|
|
353
|
+
self.neck = _SequenceEncoder(in_channels=512, hidden=rnn_hidden)
|
|
354
|
+
self.head = _CTCHead(in_channels=rnn_hidden * 2, num_classes=num_classes)
|
|
355
|
+
else:
|
|
356
|
+
raise ValueError(
|
|
357
|
+
f"Unknown backbone '{backbone}'. Known: 'vgg', 'resnet34_vd'."
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
if weights is not None:
|
|
361
|
+
load_weights(self, weights)
|
|
362
|
+
|
|
363
|
+
def forward(self, images: Tensor) -> Tensor:
|
|
364
|
+
_check_crnn_input(images)
|
|
365
|
+
|
|
366
|
+
if self.backbone_name == "vgg":
|
|
367
|
+
features = self.cnn(images)
|
|
368
|
+
sequence = features.squeeze(2).permute(2, 0, 1)
|
|
369
|
+
contextual, _ = self.rnn(sequence)
|
|
370
|
+
return self.classifier(contextual)
|
|
371
|
+
|
|
372
|
+
# resnet34_vd path
|
|
373
|
+
pyramid = self.backbone(images)
|
|
374
|
+
c5 = pyramid["c5"] # (B, 512, 1, T)
|
|
375
|
+
contextual = self.neck(c5) # (B, T, 2*rnn_hidden)
|
|
376
|
+
logits = self.head(contextual) # (B, T, num_classes)
|
|
377
|
+
return logits.permute(1, 0, 2) # (T, B, num_classes) for CTC decoder
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
@register_model("crnn_vgg")
|
|
381
|
+
def crnn_vgg(*, num_classes: int, **kwargs: object) -> CRNN:
|
|
382
|
+
"""CRNN with the original VGG-style CNN (no published weights)."""
|
|
383
|
+
return CRNN(num_classes=num_classes, backbone="vgg", **kwargs)
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
@register_model("crnn_resnet34_vd", weights=CRNN_ResNet34_VD_Weights)
|
|
387
|
+
def crnn_resnet34_vd(
|
|
388
|
+
*, weights: CRNN_ResNet34_VD_Weights | str | None = None, num_classes: int | None = None, **kwargs: object
|
|
389
|
+
) -> CRNN:
|
|
390
|
+
"""PaddleOCR-compatible CRNN (ResNet-34-VD + BiLSTM + CTC); see :class:`CRNN_ResNet34_VD_Weights`."""
|
|
391
|
+
return CRNN(num_classes=num_classes, backbone="resnet34_vd", weights=weights, **kwargs)
|
torchocr/ops/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Batched, device-agnostic geometry ops for OCR, mirroring ``torchvision.ops``."""
|
|
2
|
+
|
|
3
|
+
from .crop import crop_quads
|
|
4
|
+
from .geometry import order_quad_vertices, polygon_area, quad_to_box, reading_order
|
|
5
|
+
|
|
6
|
+
__all__ = ["crop_quads", "order_quad_vertices", "polygon_area", "quad_to_box", "reading_order"]
|