python-doctr 1.0.0__py3-none-any.whl → 1.1.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 +506 -0
- doctr/contrib/artefacts.py +1 -1
- doctr/contrib/base.py +1 -1
- doctr/datasets/__init__.py +2 -0
- doctr/datasets/coco_text.py +5 -3
- doctr/datasets/cord.py +3 -2
- doctr/datasets/datasets/base.py +13 -25
- doctr/datasets/datasets/pytorch.py +15 -5
- doctr/datasets/detection.py +3 -2
- doctr/datasets/doc_artefacts.py +3 -2
- doctr/datasets/funsd.py +3 -2
- doctr/datasets/generator/base.py +6 -5
- doctr/datasets/generator/pytorch.py +5 -6
- doctr/datasets/ic03.py +4 -3
- doctr/datasets/ic13.py +5 -3
- doctr/datasets/iiit5k.py +3 -2
- doctr/datasets/iiithws.py +5 -3
- doctr/datasets/imgur5k.py +5 -3
- doctr/datasets/layout.py +123 -0
- doctr/datasets/mjsynth.py +5 -3
- doctr/datasets/ocr.py +3 -2
- doctr/datasets/orientation.py +3 -2
- doctr/datasets/recognition.py +3 -2
- doctr/datasets/sroie.py +3 -2
- doctr/datasets/svhn.py +3 -2
- doctr/datasets/svt.py +4 -3
- doctr/datasets/synthtext.py +3 -2
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +15 -6
- doctr/datasets/vocabs.py +3 -1
- doctr/datasets/wildreceipt.py +5 -3
- doctr/file_utils.py +4 -2
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +253 -261
- doctr/io/exporters.py +1275 -0
- doctr/io/html.py +1 -1
- doctr/io/image/base.py +4 -3
- doctr/io/image/pytorch.py +6 -4
- doctr/io/pdf.py +1 -1
- doctr/io/reader.py +1 -1
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +111 -25
- doctr/models/builder.py +533 -62
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +2 -2
- doctr/models/classification/mobilenet/pytorch.py +7 -7
- doctr/models/classification/predictor/pytorch.py +7 -3
- doctr/models/classification/resnet/pytorch.py +6 -6
- doctr/models/classification/starnet/__init__.py +1 -0
- doctr/models/classification/starnet/pytorch.py +202 -0
- doctr/models/classification/textnet/pytorch.py +7 -6
- doctr/models/classification/vgg/pytorch.py +4 -3
- doctr/models/classification/vip/layers/pytorch.py +5 -5
- doctr/models/classification/vip/pytorch.py +5 -5
- doctr/models/classification/vit/pytorch.py +4 -4
- 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 +4 -1
- doctr/models/core.py +1 -1
- doctr/models/detection/_utils/base.py +24 -8
- doctr/models/detection/_utils/pytorch.py +1 -1
- doctr/models/detection/core.py +34 -19
- doctr/models/detection/differentiable_binarization/base.py +7 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
- doctr/models/detection/fast/base.py +6 -2
- doctr/models/detection/fast/pytorch.py +4 -4
- doctr/models/detection/linknet/base.py +6 -2
- doctr/models/detection/linknet/pytorch.py +4 -4
- doctr/models/detection/predictor/pytorch.py +4 -3
- doctr/models/detection/zoo.py +3 -3
- doctr/models/factory/hub.py +72 -52
- doctr/models/kie_predictor/base.py +17 -2
- doctr/models/kie_predictor/pytorch.py +42 -11
- 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 +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +140 -4
- doctr/models/modules/transformer/pytorch.py +1 -1
- doctr/models/modules/vision_transformer/pytorch.py +1 -1
- doctr/models/predictor/base.py +138 -16
- doctr/models/predictor/pytorch.py +151 -9
- doctr/models/preprocessor/pytorch.py +78 -23
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/core.py +1 -1
- doctr/models/recognition/crnn/pytorch.py +6 -8
- doctr/models/recognition/master/base.py +1 -1
- doctr/models/recognition/master/pytorch.py +7 -8
- doctr/models/recognition/parseq/base.py +1 -1
- doctr/models/recognition/parseq/pytorch.py +5 -5
- doctr/models/recognition/predictor/_utils.py +1 -1
- doctr/models/recognition/predictor/pytorch.py +2 -2
- doctr/models/recognition/sar/pytorch.py +2 -2
- doctr/models/recognition/utils.py +9 -11
- doctr/models/recognition/viptr/pytorch.py +4 -6
- doctr/models/recognition/vitstr/base.py +1 -1
- doctr/models/recognition/vitstr/pytorch.py +6 -6
- doctr/models/recognition/zoo.py +6 -7
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +316 -16
- doctr/models/zoo.py +91 -3
- doctr/transforms/functional/base.py +3 -2
- doctr/transforms/functional/pytorch.py +1 -1
- doctr/transforms/modules/base.py +248 -83
- doctr/transforms/modules/pytorch.py +213 -74
- doctr/utils/common_types.py +22 -2
- doctr/utils/data.py +5 -4
- doctr/utils/fonts.py +56 -17
- doctr/utils/geometry.py +136 -19
- doctr/utils/metrics.py +351 -19
- doctr/utils/multithreading.py +6 -3
- doctr/utils/reconstitution.py +697 -133
- doctr/utils/repr.py +1 -1
- doctr/utils/visualization.py +63 -4
- doctr/version.py +1 -1
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
- python_doctr-1.0.0.dist-info/RECORD +0 -149
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
doctr/models/utils/pytorch.py
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
2
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
6
|
import logging
|
|
7
|
+
from collections.abc import Iterable
|
|
7
8
|
from typing import Any
|
|
8
9
|
|
|
9
10
|
import torch
|
|
10
11
|
import validators
|
|
12
|
+
from anyascii import anyascii
|
|
11
13
|
from torch import nn
|
|
12
14
|
|
|
13
15
|
from doctr.utils.data import download_from_url
|
|
@@ -17,11 +19,14 @@ __all__ = [
|
|
|
17
19
|
"conv_sequence_pt",
|
|
18
20
|
"set_device_and_dtype",
|
|
19
21
|
"export_model_to_onnx",
|
|
22
|
+
"add_whitelist",
|
|
20
23
|
"_copy_tensor",
|
|
21
24
|
"_bf16_to_float32",
|
|
22
25
|
"_CompiledModule",
|
|
23
26
|
]
|
|
24
27
|
|
|
28
|
+
logger = logging.getLogger(__name__)
|
|
29
|
+
|
|
25
30
|
# torch compiled model type
|
|
26
31
|
_CompiledModule = torch._dynamo.eval_frame.OptimizedModule
|
|
27
32
|
|
|
@@ -55,7 +60,7 @@ def load_pretrained_params(
|
|
|
55
60
|
**kwargs: additional arguments to be passed to `doctr.utils.data.download_from_url`
|
|
56
61
|
"""
|
|
57
62
|
if path_or_url is None:
|
|
58
|
-
|
|
63
|
+
logger.warning("No model URL or Path provided, using default initialization.")
|
|
59
64
|
return
|
|
60
65
|
|
|
61
66
|
archive_path = (
|
|
@@ -86,8 +91,9 @@ def load_pretrained_params(
|
|
|
86
91
|
def conv_sequence_pt(
|
|
87
92
|
in_channels: int,
|
|
88
93
|
out_channels: int,
|
|
89
|
-
|
|
94
|
+
act: bool = False,
|
|
90
95
|
bn: bool = False,
|
|
96
|
+
activation: nn.Module = nn.ReLU(inplace=True),
|
|
91
97
|
**kwargs: Any,
|
|
92
98
|
) -> list[nn.Module]:
|
|
93
99
|
"""Builds a convolutional-based layer sequence
|
|
@@ -99,8 +105,9 @@ def conv_sequence_pt(
|
|
|
99
105
|
Args:
|
|
100
106
|
in_channels: number of input channels
|
|
101
107
|
out_channels: number of output channels
|
|
102
|
-
|
|
108
|
+
act: should an activation layer be added
|
|
103
109
|
bn: should a batch normalization layer be added
|
|
110
|
+
activation: the activation layer to be added if act is True
|
|
104
111
|
**kwargs: additional arguments to be passed to the convolutional layer
|
|
105
112
|
|
|
106
113
|
Returns:
|
|
@@ -114,15 +121,18 @@ def conv_sequence_pt(
|
|
|
114
121
|
if bn:
|
|
115
122
|
conv_seq.append(nn.BatchNorm2d(out_channels))
|
|
116
123
|
|
|
117
|
-
if
|
|
118
|
-
conv_seq.append(
|
|
124
|
+
if act:
|
|
125
|
+
conv_seq.append(activation)
|
|
119
126
|
|
|
120
127
|
return conv_seq
|
|
121
128
|
|
|
122
129
|
|
|
123
130
|
def set_device_and_dtype(
|
|
124
|
-
model: Any,
|
|
125
|
-
|
|
131
|
+
model: Any,
|
|
132
|
+
batches: list[torch.Tensor] | tuple[list[torch.Tensor], list[torch.Tensor]],
|
|
133
|
+
device: str | torch.device,
|
|
134
|
+
dtype: torch.dtype,
|
|
135
|
+
) -> tuple[Any, list[torch.Tensor] | list[tuple[torch.Tensor, torch.Tensor]]]:
|
|
126
136
|
"""Set the device and dtype of a model and its batches
|
|
127
137
|
|
|
128
138
|
>>> import torch
|
|
@@ -141,10 +151,26 @@ def set_device_and_dtype(
|
|
|
141
151
|
Returns:
|
|
142
152
|
the model and batches set
|
|
143
153
|
"""
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
154
|
+
first = next(model.parameters(), None)
|
|
155
|
+
if first is None or first.device != torch.device(device) or first.dtype != dtype:
|
|
156
|
+
model = model.to(device=device, dtype=dtype)
|
|
157
|
+
if isinstance(batches, tuple):
|
|
158
|
+
return model, [
|
|
159
|
+
(img.to(device=device, dtype=dtype), mask.to(device=device, dtype=torch.bool))
|
|
160
|
+
for img, mask in zip(*batches)
|
|
161
|
+
]
|
|
162
|
+
return model, [batch.to(device=device, dtype=dtype) for batch in batches]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def export_model_to_onnx(
|
|
166
|
+
model: nn.Module,
|
|
167
|
+
model_name: str,
|
|
168
|
+
dummy_input: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
|
|
169
|
+
input_names: list[str] | None = None,
|
|
170
|
+
output_names: list[str] | None = None,
|
|
171
|
+
dynamic_axes: dict[str, dict[int, str]] | None = None,
|
|
172
|
+
**kwargs: Any,
|
|
173
|
+
) -> str:
|
|
148
174
|
"""Export model to ONNX format.
|
|
149
175
|
|
|
150
176
|
>>> import torch
|
|
@@ -157,21 +183,295 @@ def export_model_to_onnx(model: nn.Module, model_name: str, dummy_input: torch.T
|
|
|
157
183
|
model: the PyTorch model to be exported
|
|
158
184
|
model_name: the name for the exported model
|
|
159
185
|
dummy_input: the dummy input to the model
|
|
186
|
+
input_names: optional names for the model inputs. Defaults to `["input"]` (or `["input", "masks"]`
|
|
187
|
+
when `dummy_input` is a tuple).
|
|
188
|
+
output_names: optional names for the model outputs. Defaults to `["logits"]` (or
|
|
189
|
+
`["logits", "pred_boxes"]` when `dummy_input` is a tuple). Pass the names of every output when
|
|
190
|
+
the model returns more than one tensor (e.g. a multi-head model).
|
|
191
|
+
dynamic_axes: optional dynamic axes. Defaults to a dynamic batch dimension on every input and output.
|
|
160
192
|
kwargs: additional arguments to be passed to torch.onnx.export
|
|
161
193
|
|
|
162
194
|
Returns:
|
|
163
195
|
the path to the exported model
|
|
164
196
|
"""
|
|
197
|
+
is_tuple = isinstance(dummy_input, tuple)
|
|
198
|
+
if input_names is None:
|
|
199
|
+
input_names = ["input", "masks"] if is_tuple else ["input"]
|
|
200
|
+
if output_names is None:
|
|
201
|
+
output_names = ["logits", "pred_boxes"] if is_tuple else ["logits"]
|
|
202
|
+
if dynamic_axes is None:
|
|
203
|
+
dynamic_axes = {name: {0: "batch_size"} for name in [*input_names, *output_names]}
|
|
204
|
+
|
|
165
205
|
torch.onnx.export(
|
|
166
206
|
model,
|
|
167
207
|
dummy_input, # type: ignore[arg-type]
|
|
168
208
|
f"{model_name}.onnx",
|
|
169
|
-
input_names=
|
|
170
|
-
output_names=
|
|
171
|
-
dynamic_axes=
|
|
209
|
+
input_names=input_names,
|
|
210
|
+
output_names=output_names,
|
|
211
|
+
dynamic_axes=dynamic_axes,
|
|
172
212
|
export_params=True,
|
|
213
|
+
dynamo=False,
|
|
173
214
|
verbose=False,
|
|
174
215
|
**kwargs,
|
|
175
216
|
)
|
|
176
|
-
|
|
217
|
+
logger.info(f"Model exported to {model_name}.onnx")
|
|
177
218
|
return f"{model_name}.onnx"
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
# Location of the final vocabulary-projection layer for each recognition architecture.
|
|
222
|
+
_RECOGNITION_PROJECTIONS: dict[str, str] = {
|
|
223
|
+
"CRNN": "linear",
|
|
224
|
+
"SAR": "decoder.output_dense",
|
|
225
|
+
"MASTER": "linear",
|
|
226
|
+
"ViTSTR": "head",
|
|
227
|
+
"PARSeq": "head",
|
|
228
|
+
"VIPTR": "head",
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class WhitelistHandle:
|
|
233
|
+
"""Removable registration returned by :func:`add_whitelist`.
|
|
234
|
+
|
|
235
|
+
Call :meth:`remove` to restore the model's original, unconstrained decoding. The
|
|
236
|
+
handle can also be used as a context manager, in which case the whitelist is removed
|
|
237
|
+
on exit.
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
def __init__(self, handles: list[torch.utils.hooks.RemovableHandle]) -> None:
|
|
241
|
+
self._handles = handles
|
|
242
|
+
|
|
243
|
+
def remove(self) -> None:
|
|
244
|
+
"""Remove the whitelist and restore the model's unconstrained decoding."""
|
|
245
|
+
for handle in self._handles:
|
|
246
|
+
handle.remove()
|
|
247
|
+
self._handles = []
|
|
248
|
+
|
|
249
|
+
def __enter__(self) -> "WhitelistHandle":
|
|
250
|
+
return self
|
|
251
|
+
|
|
252
|
+
def __exit__(self, *_: Any) -> None:
|
|
253
|
+
self.remove()
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _recognition_model(model: nn.Module) -> nn.Module:
|
|
257
|
+
# Accept an ocr_predictor / kie_predictor / recognition_predictor or a recognition model
|
|
258
|
+
if hasattr(model, "vocab") and hasattr(model, "postprocessor"):
|
|
259
|
+
return model
|
|
260
|
+
reco_predictor = getattr(model, "reco_predictor", model)
|
|
261
|
+
reco_model = getattr(reco_predictor, "model", None)
|
|
262
|
+
if reco_model is None:
|
|
263
|
+
raise TypeError(
|
|
264
|
+
"Expected an ocr_predictor, kie_predictor, recognition_predictor or a recognition "
|
|
265
|
+
f"model, but could not find a recognition model on {type(model).__name__}."
|
|
266
|
+
)
|
|
267
|
+
return reco_model
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _vocab_projections(model: nn.Module, vocab_size: int) -> list[nn.Linear]:
|
|
271
|
+
path = _RECOGNITION_PROJECTIONS.get(type(model).__name__)
|
|
272
|
+
if path is not None:
|
|
273
|
+
layer: Any = model
|
|
274
|
+
for part in path.split("."):
|
|
275
|
+
layer = getattr(layer, part)
|
|
276
|
+
if isinstance(layer, nn.Linear):
|
|
277
|
+
return [layer]
|
|
278
|
+
# Fallback for unknown architectures: any Linear projecting to the vocab (+ up to 3 specials)
|
|
279
|
+
candidates = [
|
|
280
|
+
module
|
|
281
|
+
for module in model.modules()
|
|
282
|
+
if isinstance(module, nn.Linear) and module.out_features in {vocab_size + 1, vocab_size + 2, vocab_size + 3}
|
|
283
|
+
]
|
|
284
|
+
if not candidates:
|
|
285
|
+
raise RuntimeError(f"Could not locate the vocabulary projection layer of {type(model).__name__}.")
|
|
286
|
+
return candidates
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _anyascii_nearest_map(vocab: str, allowed: set[str]) -> dict[str, str]:
|
|
290
|
+
"""Map each forbidden character to the visually closest allowed one via transliteration.
|
|
291
|
+
|
|
292
|
+
Uses `anyascii` to fold characters to their ASCII form (e.g. `ä -> a`, `ł -> l`,
|
|
293
|
+
Cyrillic `а -> a`); a forbidden character is mapped to an allowed character sharing the
|
|
294
|
+
same ASCII form. Forbidden characters without such a match are left unmapped (they fall
|
|
295
|
+
back to plain masking).
|
|
296
|
+
"""
|
|
297
|
+
by_translit: dict[str, str] = {}
|
|
298
|
+
for char in vocab:
|
|
299
|
+
if char not in allowed:
|
|
300
|
+
continue
|
|
301
|
+
key = anyascii(char)
|
|
302
|
+
current = by_translit.get(key)
|
|
303
|
+
# Prefer a pure-ASCII allowed character as the canonical target for a given form.
|
|
304
|
+
if current is None or (char == anyascii(char) and current != anyascii(current)):
|
|
305
|
+
by_translit[key] = char
|
|
306
|
+
|
|
307
|
+
mapping: dict[str, str] = {}
|
|
308
|
+
for char in vocab:
|
|
309
|
+
if char in allowed:
|
|
310
|
+
continue
|
|
311
|
+
form = anyascii(char)
|
|
312
|
+
target = by_translit.get(form) or by_translit.get(form.lower()) or by_translit.get(form[:1])
|
|
313
|
+
if target is not None:
|
|
314
|
+
mapping[char] = target
|
|
315
|
+
return mapping
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def _weights_nearest_map(vocab: str, allowed: set[str], projection: nn.Linear) -> dict[str, str]:
|
|
319
|
+
"""Map each forbidden character to the allowed one whose projection weights are most similar.
|
|
320
|
+
|
|
321
|
+
This uses the model's own learned representation: the nearest allowed character is the one
|
|
322
|
+
the model most confuses the forbidden character with (cosine similarity of the projection
|
|
323
|
+
weight rows).
|
|
324
|
+
"""
|
|
325
|
+
vocab_size = len(vocab)
|
|
326
|
+
rows = nn.functional.normalize(projection.weight.detach()[:vocab_size], dim=1)
|
|
327
|
+
allowed_idx = [i for i, char in enumerate(vocab) if char in allowed]
|
|
328
|
+
forbidden_idx = [i for i, char in enumerate(vocab) if char not in allowed]
|
|
329
|
+
if not allowed_idx or not forbidden_idx:
|
|
330
|
+
return {}
|
|
331
|
+
similarity = rows[forbidden_idx] @ rows[allowed_idx].t()
|
|
332
|
+
nearest = similarity.argmax(dim=1)
|
|
333
|
+
return {vocab[forbidden_idx[k]]: vocab[allowed_idx[int(nearest[k])]] for k in range(len(forbidden_idx))}
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _keep_and_reassign(
|
|
337
|
+
vocab: str, allowed: set[str], out_features: int, char_map: dict[str, str]
|
|
338
|
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
|
339
|
+
"""Build the keep mask and the (forbidden -> allowed) index tensors for one projection."""
|
|
340
|
+
vocab_size = len(vocab)
|
|
341
|
+
keep = torch.zeros(out_features, dtype=torch.bool)
|
|
342
|
+
for idx, char in enumerate(vocab):
|
|
343
|
+
keep[idx] = char in allowed
|
|
344
|
+
keep[vocab_size] = True # sequence terminator (CTC blank / attention <eos>)
|
|
345
|
+
|
|
346
|
+
position = {char: idx for idx, char in enumerate(vocab)}
|
|
347
|
+
src, dst = [], []
|
|
348
|
+
for forbidden_char, allowed_char in char_map.items():
|
|
349
|
+
src_idx, dst_idx = position.get(forbidden_char), position.get(allowed_char)
|
|
350
|
+
# only reassign genuinely-forbidden characters onto genuinely-allowed ones
|
|
351
|
+
if src_idx is not None and dst_idx is not None and not keep[src_idx] and allowed_char in allowed:
|
|
352
|
+
src.append(src_idx)
|
|
353
|
+
dst.append(dst_idx)
|
|
354
|
+
return keep, torch.tensor(src, dtype=torch.long), torch.tensor(dst, dtype=torch.long)
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def add_whitelist(
|
|
358
|
+
model: nn.Module,
|
|
359
|
+
vocabs: str | Iterable[str],
|
|
360
|
+
*,
|
|
361
|
+
strategy: str = "mask",
|
|
362
|
+
mapping: str | dict[str, str] | None = None,
|
|
363
|
+
verbose: bool = False,
|
|
364
|
+
) -> WhitelistHandle:
|
|
365
|
+
"""Restrict a recognition model so it can only predict a subset of its vocabulary.
|
|
366
|
+
|
|
367
|
+
The whitelist is enforced at the model's final projection layer, before the decoding
|
|
368
|
+
`argmax`. Because the projection is the single point every logit flows through, the
|
|
369
|
+
constraint also applies inside the autoregressive decoding loop of SAR, MASTER and PARSeq,
|
|
370
|
+
so a forbidden character can never be produced -- not even fed back mid-word. The sequence
|
|
371
|
+
terminator (CTC `blank` / attention `<eos>`) is always kept so decoding still
|
|
372
|
+
terminates. It works with every recognition architecture and with any predictor wrapping
|
|
373
|
+
one (`ocr_predictor`, `kie_predictor`, `recognition_predictor`).
|
|
374
|
+
|
|
375
|
+
Two strategies are available:
|
|
376
|
+
|
|
377
|
+
* `"mask"` (default): the logits of forbidden characters are set to `-inf`, so decoding
|
|
378
|
+
falls back to the highest-scoring allowed character.
|
|
379
|
+
* `"nearest"`: the score of each forbidden character is first reassigned to the closest
|
|
380
|
+
allowed character (so e.g. `ä` folds onto `a`), then forbidden logits are masked.
|
|
381
|
+
Forbidden characters without a mapping fall back to masking.
|
|
382
|
+
|
|
383
|
+
A whitelist can only restrict a model to characters it already knows: characters that are
|
|
384
|
+
not part of the model's own vocabulary are silently ignored.
|
|
385
|
+
|
|
386
|
+
>>> from doctr.datasets import VOCABS
|
|
387
|
+
>>> from doctr.models import ocr_predictor
|
|
388
|
+
>>> from doctr.models.utils import add_whitelist
|
|
389
|
+
>>> predictor = ocr_predictor(pretrained=True)
|
|
390
|
+
>>> handle = add_whitelist(predictor, [VOCABS["polish"], VOCABS["german"]])
|
|
391
|
+
>>> # ... run the predictor; only Polish/German characters can be predicted ...
|
|
392
|
+
>>> handle.remove() # restore the original, unconstrained decoding
|
|
393
|
+
|
|
394
|
+
Args:
|
|
395
|
+
model: an `ocr_predictor`, `kie_predictor`, `recognition_predictor`, or a recognition model.
|
|
396
|
+
vocabs: a vocabulary string (e.g. `VOCABS["german"]`) or an iterable of vocabulary
|
|
397
|
+
strings (e.g. `[VOCABS["polish"], VOCABS["german"]]`) whose characters are allowed.
|
|
398
|
+
strategy: `"mask"` (default) to drop forbidden characters, or `"nearest"` to fold
|
|
399
|
+
them onto the closest allowed character.
|
|
400
|
+
mapping: only used when `"strategy="nearest"`". `None` or `"anyascii"` builds the
|
|
401
|
+
forbidden-to-allowed map by transliteration (the default); `"weights"` derives it
|
|
402
|
+
from the projection weights (the model's own confusions); a `dict` of
|
|
403
|
+
`{forbidden_char: allowed_char}` overrides specific characters on top of the
|
|
404
|
+
transliteration map.
|
|
405
|
+
verbose: if True, log how many characters were kept, forbidden and reassigned per model.
|
|
406
|
+
|
|
407
|
+
Returns:
|
|
408
|
+
a :class:`WhitelistHandle`; call its :meth:`~WhitelistHandle.remove` method to restore
|
|
409
|
+
the original, unconstrained decoding.
|
|
410
|
+
"""
|
|
411
|
+
if strategy not in {"mask", "nearest"}:
|
|
412
|
+
raise ValueError(f"Unknown strategy {strategy!r}; expected 'mask' or 'nearest'.")
|
|
413
|
+
if strategy == "mask" and mapping is not None:
|
|
414
|
+
raise ValueError("The 'mapping' argument is only used with strategy='nearest'.")
|
|
415
|
+
if isinstance(mapping, str) and mapping not in {"anyascii", "weights"}:
|
|
416
|
+
raise ValueError(f"Unknown mapping {mapping!r}; expected 'anyascii', 'weights', a dict or None.")
|
|
417
|
+
if mapping is not None and not isinstance(mapping, (str, dict)):
|
|
418
|
+
raise ValueError("The 'mapping' argument must be None, 'anyascii', 'weights' or a dict.")
|
|
419
|
+
|
|
420
|
+
allowed = set(vocabs) if isinstance(vocabs, str) else {char for vocab in vocabs for char in vocab}
|
|
421
|
+
|
|
422
|
+
handles: list[torch.utils.hooks.RemovableHandle] = []
|
|
423
|
+
reco_model = _recognition_model(model)
|
|
424
|
+
vocab: str = reco_model.vocab # type: ignore[assignment]
|
|
425
|
+
vocab_size = len(vocab)
|
|
426
|
+
if not any(char in allowed for char in vocab):
|
|
427
|
+
raise ValueError(
|
|
428
|
+
"The whitelist shares no character with the model's vocabulary; the model would "
|
|
429
|
+
"be unable to predict anything."
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
# A vocab-level character map (shared by every projection); the weight-based map is
|
|
433
|
+
# derived per projection further down.
|
|
434
|
+
base_map: dict[str, str] = {}
|
|
435
|
+
if strategy == "nearest" and mapping != "weights":
|
|
436
|
+
base_map = _anyascii_nearest_map(vocab, allowed)
|
|
437
|
+
if isinstance(mapping, dict):
|
|
438
|
+
base_map = {**base_map, **mapping}
|
|
439
|
+
|
|
440
|
+
reassigned = 0
|
|
441
|
+
for projection in _vocab_projections(reco_model, vocab_size):
|
|
442
|
+
char_map = (
|
|
443
|
+
_weights_nearest_map(vocab, allowed, projection)
|
|
444
|
+
if strategy == "nearest" and mapping == "weights"
|
|
445
|
+
else base_map
|
|
446
|
+
)
|
|
447
|
+
keep, src, dst = _keep_and_reassign(vocab, allowed, projection.out_features, char_map)
|
|
448
|
+
reassigned = max(reassigned, src.numel())
|
|
449
|
+
|
|
450
|
+
def _constrain_logits(
|
|
451
|
+
_module: nn.Module,
|
|
452
|
+
_inputs: Any,
|
|
453
|
+
output: torch.Tensor,
|
|
454
|
+
keep: torch.Tensor = keep,
|
|
455
|
+
src: torch.Tensor = src,
|
|
456
|
+
dst: torch.Tensor = dst,
|
|
457
|
+
):
|
|
458
|
+
output = output.clone()
|
|
459
|
+
if src.numel():
|
|
460
|
+
# move each forbidden character's score onto its nearest allowed character
|
|
461
|
+
values = output[..., src.to(output.device)]
|
|
462
|
+
index = dst.to(output.device).view(*([1] * (output.dim() - 1)), -1).expand(*output.shape[:-1], -1)
|
|
463
|
+
output.scatter_reduce_(-1, index, values, reduce="amax", include_self=True)
|
|
464
|
+
output[..., ~keep.to(output.device)] = float("-inf")
|
|
465
|
+
return output
|
|
466
|
+
|
|
467
|
+
handles.append(projection.register_forward_hook(_constrain_logits))
|
|
468
|
+
|
|
469
|
+
if verbose: # pragma: no cover
|
|
470
|
+
kept = sum(char in allowed for char in vocab)
|
|
471
|
+
logger.info(
|
|
472
|
+
f"add_whitelist: {type(reco_model).__name__} - kept {kept}/{vocab_size} vocabulary "
|
|
473
|
+
f"characters, forbade {vocab_size - kept}"
|
|
474
|
+
+ (f", reassigned {reassigned} to a nearest allowed character." if strategy == "nearest" else ".")
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
return WhitelistHandle(handles)
|
doctr/models/zoo.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
2
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
@@ -7,8 +7,10 @@ from typing import Any
|
|
|
7
7
|
|
|
8
8
|
from .detection.zoo import detection_predictor
|
|
9
9
|
from .kie_predictor import KIEPredictor
|
|
10
|
+
from .layout.zoo import layout_predictor
|
|
10
11
|
from .predictor import OCRPredictor
|
|
11
12
|
from .recognition.zoo import recognition_predictor
|
|
13
|
+
from .table_structure.zoo import table_predictor
|
|
12
14
|
|
|
13
15
|
__all__ = ["ocr_predictor", "kie_predictor"]
|
|
14
16
|
|
|
@@ -26,6 +28,10 @@ def _predictor(
|
|
|
26
28
|
detect_orientation: bool = False,
|
|
27
29
|
straighten_pages: bool = False,
|
|
28
30
|
detect_language: bool = False,
|
|
31
|
+
detect_layout: bool = False,
|
|
32
|
+
layout_arch: Any = "lw_detr_s",
|
|
33
|
+
ignore_regions: list[str] | None = None,
|
|
34
|
+
detect_tables: bool = False,
|
|
29
35
|
**kwargs,
|
|
30
36
|
) -> OCRPredictor:
|
|
31
37
|
# Detection
|
|
@@ -47,6 +53,34 @@ def _predictor(
|
|
|
47
53
|
batch_size=reco_bs,
|
|
48
54
|
)
|
|
49
55
|
|
|
56
|
+
# Layout - required for table detection, so build it whenever layout or tables are requested
|
|
57
|
+
layout_pred = (
|
|
58
|
+
layout_predictor(
|
|
59
|
+
layout_arch,
|
|
60
|
+
pretrained=pretrained,
|
|
61
|
+
assume_straight_pages=assume_straight_pages,
|
|
62
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
63
|
+
symmetric_pad=symmetric_pad,
|
|
64
|
+
batch_size=det_bs,
|
|
65
|
+
)
|
|
66
|
+
if (detect_layout or detect_tables)
|
|
67
|
+
else None
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
# Table structure - optional, applied on the cropped table regions found by the layout model
|
|
71
|
+
table_pred = (
|
|
72
|
+
table_predictor(
|
|
73
|
+
"tablecenternet",
|
|
74
|
+
pretrained=pretrained,
|
|
75
|
+
assume_straight_pages=assume_straight_pages,
|
|
76
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
77
|
+
symmetric_pad=symmetric_pad,
|
|
78
|
+
batch_size=det_bs,
|
|
79
|
+
)
|
|
80
|
+
if detect_tables
|
|
81
|
+
else None
|
|
82
|
+
)
|
|
83
|
+
|
|
50
84
|
return OCRPredictor(
|
|
51
85
|
det_predictor,
|
|
52
86
|
reco_predictor,
|
|
@@ -56,6 +90,9 @@ def _predictor(
|
|
|
56
90
|
detect_orientation=detect_orientation,
|
|
57
91
|
straighten_pages=straighten_pages,
|
|
58
92
|
detect_language=detect_language,
|
|
93
|
+
layout_predictor=layout_pred,
|
|
94
|
+
table_predictor=table_pred,
|
|
95
|
+
ignore_regions=ignore_regions,
|
|
59
96
|
**kwargs,
|
|
60
97
|
)
|
|
61
98
|
|
|
@@ -72,6 +109,10 @@ def ocr_predictor(
|
|
|
72
109
|
detect_orientation: bool = False,
|
|
73
110
|
straighten_pages: bool = False,
|
|
74
111
|
detect_language: bool = False,
|
|
112
|
+
detect_layout: bool = False,
|
|
113
|
+
layout_arch: Any = "lw_detr_s",
|
|
114
|
+
ignore_regions: list[str] | None = None,
|
|
115
|
+
detect_tables: bool = False,
|
|
75
116
|
**kwargs: Any,
|
|
76
117
|
) -> OCRPredictor:
|
|
77
118
|
"""End-to-end OCR architecture using one model for localization, and another for text recognition.
|
|
@@ -104,6 +145,17 @@ def ocr_predictor(
|
|
|
104
145
|
Doing so will improve performances for documents with page-uniform rotations.
|
|
105
146
|
detect_language: if True, the language prediction will be added to the predictions for each
|
|
106
147
|
page. Doing so will slightly deteriorate the overall latency.
|
|
148
|
+
detect_layout: if True, a layout detection model is run on each page and the detected regions are attached
|
|
149
|
+
to each page.
|
|
150
|
+
Doing so will slightly deteriorate the overall latency.
|
|
151
|
+
layout_arch: name of the layout architecture or the model itself to use.
|
|
152
|
+
ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
|
|
153
|
+
layout model will be used to locate the regions of the specified classes, and these regions will
|
|
154
|
+
be masked out (filled with black) before passing the pages to the detection/recognition modules.
|
|
155
|
+
detect_tables: if True, table regions found by the layout model are cropped and passed to a table
|
|
156
|
+
structure model. Words falling inside a detected table are regrouped into a structured table
|
|
157
|
+
(accessible via `page.tables`) and removed from the regular text output. This enables the layout
|
|
158
|
+
model and slightly deteriorates the overall latency.
|
|
107
159
|
kwargs: keyword args of `OCRPredictor`
|
|
108
160
|
|
|
109
161
|
Returns:
|
|
@@ -121,6 +173,10 @@ def ocr_predictor(
|
|
|
121
173
|
detect_orientation=detect_orientation,
|
|
122
174
|
straighten_pages=straighten_pages,
|
|
123
175
|
detect_language=detect_language,
|
|
176
|
+
detect_layout=detect_layout,
|
|
177
|
+
layout_arch=layout_arch,
|
|
178
|
+
detect_tables=detect_tables,
|
|
179
|
+
ignore_regions=ignore_regions,
|
|
124
180
|
**kwargs,
|
|
125
181
|
)
|
|
126
182
|
|
|
@@ -138,6 +194,9 @@ def _kie_predictor(
|
|
|
138
194
|
detect_orientation: bool = False,
|
|
139
195
|
straighten_pages: bool = False,
|
|
140
196
|
detect_language: bool = False,
|
|
197
|
+
detect_layout: bool = False,
|
|
198
|
+
layout_arch: Any = "lw_detr_s",
|
|
199
|
+
ignore_regions: list[str] | None = None,
|
|
141
200
|
**kwargs,
|
|
142
201
|
) -> KIEPredictor:
|
|
143
202
|
# Detection
|
|
@@ -159,6 +218,20 @@ def _kie_predictor(
|
|
|
159
218
|
batch_size=reco_bs,
|
|
160
219
|
)
|
|
161
220
|
|
|
221
|
+
# Layout - optional
|
|
222
|
+
layout_pred = (
|
|
223
|
+
layout_predictor(
|
|
224
|
+
layout_arch,
|
|
225
|
+
pretrained=pretrained,
|
|
226
|
+
assume_straight_pages=assume_straight_pages,
|
|
227
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
228
|
+
symmetric_pad=symmetric_pad,
|
|
229
|
+
batch_size=det_bs,
|
|
230
|
+
)
|
|
231
|
+
if detect_layout
|
|
232
|
+
else None
|
|
233
|
+
)
|
|
234
|
+
|
|
162
235
|
return KIEPredictor(
|
|
163
236
|
det_predictor,
|
|
164
237
|
reco_predictor,
|
|
@@ -168,6 +241,8 @@ def _kie_predictor(
|
|
|
168
241
|
detect_orientation=detect_orientation,
|
|
169
242
|
straighten_pages=straighten_pages,
|
|
170
243
|
detect_language=detect_language,
|
|
244
|
+
layout_predictor=layout_pred,
|
|
245
|
+
ignore_regions=ignore_regions,
|
|
171
246
|
**kwargs,
|
|
172
247
|
)
|
|
173
248
|
|
|
@@ -184,13 +259,16 @@ def kie_predictor(
|
|
|
184
259
|
detect_orientation: bool = False,
|
|
185
260
|
straighten_pages: bool = False,
|
|
186
261
|
detect_language: bool = False,
|
|
262
|
+
detect_layout: bool = False,
|
|
263
|
+
layout_arch: Any = "lw_detr_s",
|
|
264
|
+
ignore_regions: list[str] | None = None,
|
|
187
265
|
**kwargs: Any,
|
|
188
266
|
) -> KIEPredictor:
|
|
189
267
|
"""End-to-end KIE architecture using one model for localization, and another for text recognition.
|
|
190
268
|
|
|
191
269
|
>>> import numpy as np
|
|
192
|
-
>>> from doctr.models import
|
|
193
|
-
>>> model =
|
|
270
|
+
>>> from doctr.models import kie_predictor
|
|
271
|
+
>>> model = kie_predictor('db_resnet50', 'crnn_vgg16_bn', pretrained=True)
|
|
194
272
|
>>> input_page = (255 * np.random.rand(600, 800, 3)).astype(np.uint8)
|
|
195
273
|
>>> out = model([input_page])
|
|
196
274
|
|
|
@@ -216,6 +294,13 @@ def kie_predictor(
|
|
|
216
294
|
Doing so will improve performances for documents with page-uniform rotations.
|
|
217
295
|
detect_language: if True, the language prediction will be added to the predictions for each
|
|
218
296
|
page. Doing so will slightly deteriorate the overall latency.
|
|
297
|
+
detect_layout: if True, a layout detection model is run on each page and the detected regions are attached
|
|
298
|
+
to each page.
|
|
299
|
+
Doing so will slightly deteriorate the overall latency.
|
|
300
|
+
layout_arch: name of the layout architecture or the model itself to use.
|
|
301
|
+
ignore_regions: optional list of layout class names to ignore during detection/recognition. If provided, the
|
|
302
|
+
layout model will be used to locate the regions of the specified classes, and these regions will
|
|
303
|
+
be masked out (filled with black) before passing the pages to the detection/recognition modules.
|
|
219
304
|
kwargs: keyword args of `OCRPredictor`
|
|
220
305
|
|
|
221
306
|
Returns:
|
|
@@ -233,5 +318,8 @@ def kie_predictor(
|
|
|
233
318
|
detect_orientation=detect_orientation,
|
|
234
319
|
straighten_pages=straighten_pages,
|
|
235
320
|
detect_language=detect_language,
|
|
321
|
+
detect_layout=detect_layout,
|
|
322
|
+
layout_arch=layout_arch,
|
|
323
|
+
ignore_regions=ignore_regions,
|
|
236
324
|
**kwargs,
|
|
237
325
|
)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Copyright (C) 2021-
|
|
1
|
+
# Copyright (C) 2021-2026, Mindee.
|
|
2
2
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
@@ -145,7 +145,8 @@ def create_shadow_mask(
|
|
|
145
145
|
|
|
146
146
|
# Convert to absolute coords
|
|
147
147
|
abs_contour: np.ndarray = (
|
|
148
|
-
np
|
|
148
|
+
np
|
|
149
|
+
.stack(
|
|
149
150
|
(contour[:, 0] * target_shape[1], contour[:, 1] * target_shape[0]),
|
|
150
151
|
axis=-1,
|
|
151
152
|
)
|