python-doctr 1.0.1__py3-none-any.whl → 1.2.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.
Files changed (143) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +669 -0
  3. doctr/datasets/__init__.py +2 -0
  4. doctr/datasets/coco_text.py +4 -2
  5. doctr/datasets/cord.py +2 -1
  6. doctr/datasets/datasets/base.py +12 -24
  7. doctr/datasets/datasets/pytorch.py +14 -4
  8. doctr/datasets/detection.py +14 -3
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +121 -37
  12. doctr/datasets/generator/pytorch.py +5 -6
  13. doctr/datasets/ic03.py +9 -7
  14. doctr/datasets/ic13.py +4 -2
  15. doctr/datasets/iiit5k.py +2 -1
  16. doctr/datasets/iiithws.py +4 -2
  17. doctr/datasets/imgur5k.py +4 -2
  18. doctr/datasets/layout.py +129 -0
  19. doctr/datasets/mjsynth.py +4 -2
  20. doctr/datasets/ocr.py +2 -1
  21. doctr/datasets/orientation.py +2 -1
  22. doctr/datasets/recognition.py +5 -4
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +10 -8
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +104 -21
  29. doctr/datasets/vocabs.py +320 -148
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +3 -0
  33. doctr/io/elements.py +381 -271
  34. doctr/io/exporters.py +1915 -0
  35. doctr/io/figures.py +313 -0
  36. doctr/io/image/base.py +54 -7
  37. doctr/io/image/pytorch.py +13 -5
  38. doctr/io/pdf.py +6 -5
  39. doctr/io/reader.py +268 -18
  40. doctr/io/sources.py +636 -0
  41. doctr/models/__init__.py +3 -0
  42. doctr/models/_utils.py +206 -13
  43. doctr/models/builder.py +590 -137
  44. doctr/models/classification/__init__.py +3 -0
  45. doctr/models/classification/hgnetv2/__init__.py +1 -0
  46. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  47. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  48. doctr/models/classification/mobilenet/pytorch.py +6 -6
  49. doctr/models/classification/predictor/pytorch.py +34 -2
  50. doctr/models/classification/resnet/pytorch.py +5 -5
  51. doctr/models/classification/starnet/__init__.py +1 -0
  52. doctr/models/classification/starnet/pytorch.py +202 -0
  53. doctr/models/classification/textnet/pytorch.py +6 -5
  54. doctr/models/classification/vgg/pytorch.py +3 -2
  55. doctr/models/classification/vip/layers/pytorch.py +4 -4
  56. doctr/models/classification/vip/pytorch.py +4 -4
  57. doctr/models/classification/vit/pytorch.py +3 -3
  58. doctr/models/classification/vit_det/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  60. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  61. doctr/models/classification/vit_det/pytorch.py +346 -0
  62. doctr/models/classification/zoo.py +14 -2
  63. doctr/models/detection/_utils/base.py +23 -7
  64. doctr/models/detection/core.py +32 -18
  65. doctr/models/detection/differentiable_binarization/base.py +23 -9
  66. doctr/models/detection/differentiable_binarization/pytorch.py +10 -4
  67. doctr/models/detection/fast/base.py +22 -6
  68. doctr/models/detection/fast/pytorch.py +24 -11
  69. doctr/models/detection/linknet/base.py +22 -6
  70. doctr/models/detection/linknet/pytorch.py +10 -3
  71. doctr/models/detection/predictor/pytorch.py +43 -2
  72. doctr/models/detection/zoo.py +6 -2
  73. doctr/models/factory/hub.py +59 -41
  74. doctr/models/formula/__init__.py +2 -0
  75. doctr/models/formula/formulanet/__init__.py +2 -0
  76. doctr/models/formula/formulanet/base.py +70 -0
  77. doctr/models/formula/formulanet/pytorch.py +587 -0
  78. doctr/models/formula/predictor/__init__.py +1 -0
  79. doctr/models/formula/predictor/pytorch.py +132 -0
  80. doctr/models/formula/zoo.py +102 -0
  81. doctr/models/kie_predictor/base.py +23 -1
  82. doctr/models/kie_predictor/pytorch.py +87 -15
  83. doctr/models/layout/__init__.py +2 -0
  84. doctr/models/layout/lw_detr/__init__.py +1 -0
  85. doctr/models/layout/lw_detr/base.py +309 -0
  86. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  87. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  88. doctr/models/layout/lw_detr/pytorch.py +895 -0
  89. doctr/models/layout/predictor/__init__.py +1 -0
  90. doctr/models/layout/predictor/pytorch.py +114 -0
  91. doctr/models/layout/zoo.py +94 -0
  92. doctr/models/modules/layers/pytorch.py +139 -3
  93. doctr/models/modules/transformer/pytorch.py +151 -31
  94. doctr/models/predictor/base.py +415 -17
  95. doctr/models/predictor/pytorch.py +109 -12
  96. doctr/models/preprocessor/pytorch.py +82 -25
  97. doctr/models/reading_order/__init__.py +1 -0
  98. doctr/models/reading_order/base.py +1127 -0
  99. doctr/models/recognition/core.py +14 -1
  100. doctr/models/recognition/crnn/pytorch.py +40 -16
  101. doctr/models/recognition/master/base.py +4 -1
  102. doctr/models/recognition/master/pytorch.py +84 -22
  103. doctr/models/recognition/parseq/base.py +4 -1
  104. doctr/models/recognition/parseq/pytorch.py +126 -25
  105. doctr/models/recognition/predictor/_utils.py +131 -14
  106. doctr/models/recognition/predictor/pytorch.py +68 -12
  107. doctr/models/recognition/sar/pytorch.py +21 -7
  108. doctr/models/recognition/utils.py +80 -50
  109. doctr/models/recognition/viptr/pytorch.py +38 -14
  110. doctr/models/recognition/vitstr/base.py +4 -1
  111. doctr/models/recognition/vitstr/pytorch.py +11 -7
  112. doctr/models/recognition/zoo.py +36 -9
  113. doctr/models/table_structure/__init__.py +2 -0
  114. doctr/models/table_structure/grid.py +430 -0
  115. doctr/models/table_structure/predictor/__init__.py +1 -0
  116. doctr/models/table_structure/predictor/pytorch.py +231 -0
  117. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  118. doctr/models/table_structure/tablecenternet/base.py +675 -0
  119. doctr/models/table_structure/tablecenternet/pytorch.py +525 -0
  120. doctr/models/table_structure/zoo.py +87 -0
  121. doctr/models/utils/pytorch.py +381 -25
  122. doctr/models/zoo.py +141 -4
  123. doctr/transforms/functional/base.py +6 -0
  124. doctr/transforms/functional/pytorch.py +134 -6
  125. doctr/transforms/modules/base.py +261 -82
  126. doctr/transforms/modules/pytorch.py +396 -76
  127. doctr/utils/common_types.py +21 -1
  128. doctr/utils/data.py +24 -11
  129. doctr/utils/fonts.py +64 -17
  130. doctr/utils/geometry.py +167 -28
  131. doctr/utils/metrics.py +481 -19
  132. doctr/utils/multithreading.py +127 -4
  133. doctr/utils/reconstitution.py +696 -132
  134. doctr/utils/visualization.py +73 -10
  135. doctr/version.py +1 -1
  136. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/METADATA +119 -249
  137. python_doctr-1.2.0.dist-info/RECORD +191 -0
  138. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  139. python_doctr-1.2.0.dist-info/entry_points.txt +2 -0
  140. python_doctr-1.0.1.dist-info/RECORD +0 -149
  141. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  142. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  143. {python_doctr-1.0.1.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
@@ -4,12 +4,16 @@
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
8
+ from contextlib import nullcontext
7
9
  from typing import Any
8
10
 
9
11
  import torch
10
12
  import validators
13
+ from anyascii import anyascii
11
14
  from torch import nn
12
15
 
16
+ from doctr.file_utils import requires_package
13
17
  from doctr.utils.data import download_from_url
14
18
 
15
19
  __all__ = [
@@ -17,11 +21,14 @@ __all__ = [
17
21
  "conv_sequence_pt",
18
22
  "set_device_and_dtype",
19
23
  "export_model_to_onnx",
24
+ "add_whitelist",
20
25
  "_copy_tensor",
21
26
  "_bf16_to_float32",
22
27
  "_CompiledModule",
23
28
  ]
24
29
 
30
+ logger = logging.getLogger(__name__)
31
+
25
32
  # torch compiled model type
26
33
  _CompiledModule = torch._dynamo.eval_frame.OptimizedModule
27
34
 
@@ -55,7 +62,7 @@ def load_pretrained_params(
55
62
  **kwargs: additional arguments to be passed to `doctr.utils.data.download_from_url`
56
63
  """
57
64
  if path_or_url is None:
58
- logging.warning("No model URL or Path provided, using default initialization.")
65
+ logger.warning("No model URL or Path provided, using default initialization.")
59
66
  return
60
67
 
61
68
  archive_path = (
@@ -65,7 +72,7 @@ def load_pretrained_params(
65
72
  )
66
73
 
67
74
  # Read state_dict
68
- state_dict = torch.load(archive_path, map_location="cpu")
75
+ state_dict = torch.load(archive_path, map_location="cpu", weights_only=True)
69
76
 
70
77
  # Remove weights from the state_dict
71
78
  if ignore_keys is not None and len(ignore_keys) > 0:
@@ -86,8 +93,9 @@ def load_pretrained_params(
86
93
  def conv_sequence_pt(
87
94
  in_channels: int,
88
95
  out_channels: int,
89
- relu: bool = False,
96
+ act: bool = False,
90
97
  bn: bool = False,
98
+ activation: nn.Module | None = None,
91
99
  **kwargs: Any,
92
100
  ) -> list[nn.Module]:
93
101
  """Builds a convolutional-based layer sequence
@@ -99,8 +107,11 @@ def conv_sequence_pt(
99
107
  Args:
100
108
  in_channels: number of input channels
101
109
  out_channels: number of output channels
102
- relu: whether ReLU should be used
110
+ act: should an activation layer be added
103
111
  bn: should a batch normalization layer be added
112
+ activation: the activation layer to be added if act is True. Defaults to a new ``nn.ReLU(inplace=True)``
113
+ per call. When passing one, use a new instance per call: a module shared between layers is kept only
114
+ once by ``named_children`` (e.g. in ``IntermediateLayerGetter``)
104
115
  **kwargs: additional arguments to be passed to the convolutional layer
105
116
 
106
117
  Returns:
@@ -114,15 +125,20 @@ def conv_sequence_pt(
114
125
  if bn:
115
126
  conv_seq.append(nn.BatchNorm2d(out_channels))
116
127
 
117
- if relu:
118
- conv_seq.append(nn.ReLU(inplace=True))
128
+ if act:
129
+ # A new module per call: a default ``nn.ReLU`` instance would be shared by every layer, and modules
130
+ # that appear twice in a model are kept once by ``named_children`` (e.g. in ``IntermediateLayerGetter``).
131
+ conv_seq.append(nn.ReLU(inplace=True) if activation is None else activation)
119
132
 
120
133
  return conv_seq
121
134
 
122
135
 
123
136
  def set_device_and_dtype(
124
- model: Any, batches: list[torch.Tensor], device: str | torch.device, dtype: torch.dtype
125
- ) -> tuple[Any, list[torch.Tensor]]:
137
+ model: Any,
138
+ batches: list[torch.Tensor] | tuple[list[torch.Tensor], list[torch.Tensor]],
139
+ device: str | torch.device,
140
+ dtype: torch.dtype,
141
+ ) -> tuple[Any, list[torch.Tensor] | list[tuple[torch.Tensor, torch.Tensor]]]:
126
142
  """Set the device and dtype of a model and its batches
127
143
 
128
144
  >>> import torch
@@ -141,10 +157,27 @@ def set_device_and_dtype(
141
157
  Returns:
142
158
  the model and batches set
143
159
  """
144
- return model.to(device=device, dtype=dtype), [batch.to(device=device, dtype=dtype) for batch in batches]
145
-
146
-
147
- def export_model_to_onnx(model: nn.Module, model_name: str, dummy_input: torch.Tensor, **kwargs: Any) -> str:
160
+ first = next(model.parameters(), None)
161
+ if first is None or first.device != torch.device(device) or first.dtype != dtype:
162
+ model = model.to(device=device, dtype=dtype)
163
+ if isinstance(batches, tuple):
164
+ return model, [
165
+ (img.to(device=device, dtype=dtype), mask.to(device=device, dtype=torch.bool))
166
+ for img, mask in zip(*batches)
167
+ ]
168
+ return model, [batch.to(device=device, dtype=dtype) for batch in batches]
169
+
170
+
171
+ def export_model_to_onnx(
172
+ model: nn.Module,
173
+ model_name: str,
174
+ dummy_input: torch.Tensor | tuple[torch.Tensor, torch.Tensor],
175
+ input_names: list[str] | None = None,
176
+ output_names: list[str] | None = None,
177
+ dynamic_axes: dict[str, dict[int, str]] | None = None,
178
+ dynamo: bool = False,
179
+ **kwargs: Any,
180
+ ) -> str:
148
181
  """Export model to ONNX format.
149
182
 
150
183
  >>> import torch
@@ -157,22 +190,345 @@ def export_model_to_onnx(model: nn.Module, model_name: str, dummy_input: torch.T
157
190
  model: the PyTorch model to be exported
158
191
  model_name: the name for the exported model
159
192
  dummy_input: the dummy input to the model
193
+ input_names: optional names for the model inputs. Defaults to `["input"]` (or `["input", "masks"]`
194
+ when `dummy_input` is a tuple).
195
+ output_names: optional names for the model outputs. Defaults to `["logits"]` (or
196
+ `["logits", "pred_boxes"]` when `dummy_input` is a tuple). Pass the names of every output when
197
+ the model returns more than one tensor (e.g. a multi-head model).
198
+ dynamic_axes: optional dynamic axes. Defaults to a dynamic batch dimension on every input and output.
199
+ dynamo: whether to export with the `torch.export`-based exporter of PyTorch (requires `onnxscript`) instead of
200
+ the TorchScript-based one (default). Required for `formulanet`: its decoding is then exported as ONNX
201
+ `Loop` nodes, which stop once every formula of the batch is complete, instead of `max_decode_length`
202
+ unrolled steps. `parseq` and `master` are exported with such a loop as well. The model is saved as a
203
+ single file.
160
204
  kwargs: additional arguments to be passed to torch.onnx.export
161
205
 
162
206
  Returns:
163
207
  the path to the exported model
164
208
  """
165
- torch.onnx.export(
166
- model,
167
- dummy_input, # type: ignore[arg-type]
168
- f"{model_name}.onnx",
169
- input_names=["input"],
170
- output_names=["logits"],
171
- dynamic_axes={"input": {0: "batch_size"}, "logits": {0: "batch_size"}},
172
- export_params=True,
173
- dynamo=False,
174
- verbose=False,
175
- **kwargs,
176
- )
177
- logging.info(f"Model exported to {model_name}.onnx")
209
+ is_tuple = isinstance(dummy_input, tuple)
210
+ if input_names is None:
211
+ input_names = ["input", "masks"] if is_tuple else ["input"]
212
+ if output_names is None:
213
+ output_names = ["logits", "pred_boxes"] if is_tuple else ["logits"]
214
+ if dynamic_axes is None:
215
+ dynamic_axes = {name: {0: "batch_size"} for name in [*input_names, *output_names]}
216
+
217
+ if dynamo:
218
+ requires_package("onnxscript", "`dynamo=True` requires onnxscript installed.")
219
+ # A single file, as with the TorchScript-based exporter (the weights are otherwise saved in a separate file)
220
+ kwargs.setdefault("external_data", False)
221
+ # torch.export specializes the dimensions of size 1 (e.g. a reshape would keep a batch size of 1): trace with a
222
+ # batch of 2 so that the batch dimension stays dynamic
223
+ if (dummy_input[0] if is_tuple else dummy_input).shape[0] == 1: # type: ignore[union-attr]
224
+ dummy_input = (
225
+ tuple(torch.cat([t, t]) for t in dummy_input) # type: ignore[assignment]
226
+ if is_tuple
227
+ else torch.cat([dummy_input, dummy_input]) # type: ignore[list-item]
228
+ )
229
+
230
+ # The TorchScript-based exporter otherwise traces with autograd: the same file, with up to twice the memory
231
+ with nullcontext() if dynamo else torch.no_grad():
232
+ torch.onnx.export(
233
+ model,
234
+ dummy_input, # type: ignore[arg-type]
235
+ f"{model_name}.onnx",
236
+ input_names=input_names,
237
+ output_names=output_names,
238
+ dynamic_axes=dynamic_axes,
239
+ export_params=True,
240
+ dynamo=dynamo,
241
+ verbose=False,
242
+ **kwargs,
243
+ )
244
+ if dynamo:
245
+ _strip_onnx_node_metadata(f"{model_name}.onnx")
246
+ logger.info(f"Model exported to {model_name}.onnx")
178
247
  return f"{model_name}.onnx"
248
+
249
+
250
+ def _strip_onnx_node_metadata(path: str) -> None:
251
+ """Remove the metadata the `torch.export`-based exporter attaches to every node (e.g. the Python stack trace that
252
+ created it, with the paths of the local files), which makes up most of the file for models with loops, and the
253
+ initializers no node uses (ONNX Runtime warns about them): neither has any effect on the inference"""
254
+ import onnx
255
+
256
+ used: set[str] = set()
257
+
258
+ def _strip(graph: onnx.GraphProto) -> None:
259
+ for node in graph.node:
260
+ del node.metadata_props[:]
261
+ used.update(node.input)
262
+ for attr in node.attribute:
263
+ if attr.type == onnx.AttributeProto.GRAPH:
264
+ _strip(attr.g)
265
+ elif attr.type == onnx.AttributeProto.GRAPHS:
266
+ for subgraph in attr.graphs:
267
+ _strip(subgraph)
268
+
269
+ model = onnx.load(path)
270
+ _strip(model.graph)
271
+ used.update(output.name for output in model.graph.output)
272
+ unused = [init for init in model.graph.initializer if init.name not in used]
273
+ for init in unused:
274
+ model.graph.initializer.remove(init)
275
+ onnx.save(model, path)
276
+
277
+
278
+ # Location of the final vocabulary-projection layer for each recognition architecture.
279
+ _RECOGNITION_PROJECTIONS: dict[str, str] = {
280
+ "CRNN": "linear",
281
+ "SAR": "decoder.output_dense",
282
+ "MASTER": "linear",
283
+ "ViTSTR": "head",
284
+ "PARSeq": "head",
285
+ "VIPTR": "head",
286
+ }
287
+
288
+
289
+ class WhitelistHandle:
290
+ """Removable registration returned by :func:`add_whitelist`.
291
+
292
+ Call :meth:`remove` to restore the model's original, unconstrained decoding. The
293
+ handle can also be used as a context manager, in which case the whitelist is removed
294
+ on exit.
295
+ """
296
+
297
+ def __init__(self, handles: list[torch.utils.hooks.RemovableHandle]) -> None:
298
+ self._handles = handles
299
+
300
+ def remove(self) -> None:
301
+ """Remove the whitelist and restore the model's unconstrained decoding."""
302
+ for handle in self._handles:
303
+ handle.remove()
304
+ self._handles = []
305
+
306
+ def __enter__(self) -> "WhitelistHandle":
307
+ return self
308
+
309
+ def __exit__(self, *_: Any) -> None:
310
+ self.remove()
311
+
312
+
313
+ def _recognition_model(model: nn.Module) -> nn.Module:
314
+ # Accept an ocr_predictor / kie_predictor / recognition_predictor or a recognition model
315
+ if hasattr(model, "vocab") and hasattr(model, "postprocessor"):
316
+ return model
317
+ reco_predictor = getattr(model, "reco_predictor", model)
318
+ reco_model = getattr(reco_predictor, "model", None)
319
+ if reco_model is None:
320
+ raise TypeError(
321
+ "Expected an ocr_predictor, kie_predictor, recognition_predictor or a recognition "
322
+ f"model, but could not find a recognition model on {type(model).__name__}."
323
+ )
324
+ return reco_model
325
+
326
+
327
+ def _vocab_projections(model: nn.Module, vocab_size: int) -> list[nn.Linear]:
328
+ path = _RECOGNITION_PROJECTIONS.get(type(model).__name__)
329
+ if path is not None:
330
+ layer: Any = model
331
+ for part in path.split("."):
332
+ layer = getattr(layer, part)
333
+ if isinstance(layer, nn.Linear):
334
+ return [layer]
335
+ # Fallback for unknown architectures: any Linear projecting to the vocab (+ up to 3 specials)
336
+ candidates = [
337
+ module
338
+ for module in model.modules()
339
+ if isinstance(module, nn.Linear) and module.out_features in {vocab_size + 1, vocab_size + 2, vocab_size + 3}
340
+ ]
341
+ if not candidates:
342
+ raise RuntimeError(f"Could not locate the vocabulary projection layer of {type(model).__name__}.")
343
+ return candidates
344
+
345
+
346
+ def _anyascii_nearest_map(vocab: str, allowed: set[str]) -> dict[str, str]:
347
+ """Map each forbidden character to the visually closest allowed one via transliteration.
348
+
349
+ Uses `anyascii` to fold characters to their ASCII form (e.g. `ä -> a`, `ł -> l`,
350
+ Cyrillic `а -> a`); a forbidden character is mapped to an allowed character sharing the
351
+ same ASCII form. Forbidden characters without such a match are left unmapped (they fall
352
+ back to plain masking).
353
+ """
354
+ by_translit: dict[str, str] = {}
355
+ for char in vocab:
356
+ if char not in allowed:
357
+ continue
358
+ key = anyascii(char)
359
+ current = by_translit.get(key)
360
+ # Prefer a pure-ASCII allowed character as the canonical target for a given form.
361
+ if current is None or (char == anyascii(char) and current != anyascii(current)):
362
+ by_translit[key] = char
363
+
364
+ mapping: dict[str, str] = {}
365
+ for char in vocab:
366
+ if char in allowed:
367
+ continue
368
+ form = anyascii(char)
369
+ target = by_translit.get(form) or by_translit.get(form.lower()) or by_translit.get(form[:1])
370
+ if target is not None:
371
+ mapping[char] = target
372
+ return mapping
373
+
374
+
375
+ def _weights_nearest_map(vocab: str, allowed: set[str], projection: nn.Linear) -> dict[str, str]:
376
+ """Map each forbidden character to the allowed one whose projection weights are most similar.
377
+
378
+ This uses the model's own learned representation: the nearest allowed character is the one
379
+ the model most confuses the forbidden character with (cosine similarity of the projection
380
+ weight rows).
381
+ """
382
+ vocab_size = len(vocab)
383
+ rows = nn.functional.normalize(projection.weight.detach()[:vocab_size], dim=1)
384
+ allowed_idx = [i for i, char in enumerate(vocab) if char in allowed]
385
+ forbidden_idx = [i for i, char in enumerate(vocab) if char not in allowed]
386
+ if not allowed_idx or not forbidden_idx:
387
+ return {}
388
+ similarity = rows[forbidden_idx] @ rows[allowed_idx].t()
389
+ nearest = similarity.argmax(dim=1)
390
+ return {vocab[forbidden_idx[k]]: vocab[allowed_idx[int(nearest[k])]] for k in range(len(forbidden_idx))}
391
+
392
+
393
+ def _keep_and_reassign(
394
+ vocab: str, allowed: set[str], out_features: int, char_map: dict[str, str]
395
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
396
+ """Build the keep mask and the (forbidden -> allowed) index tensors for one projection."""
397
+ vocab_size = len(vocab)
398
+ keep = torch.zeros(out_features, dtype=torch.bool)
399
+ for idx, char in enumerate(vocab):
400
+ keep[idx] = char in allowed
401
+ keep[vocab_size] = True # sequence terminator (CTC blank / attention <eos>)
402
+
403
+ position = {char: idx for idx, char in enumerate(vocab)}
404
+ src, dst = [], []
405
+ for forbidden_char, allowed_char in char_map.items():
406
+ src_idx, dst_idx = position.get(forbidden_char), position.get(allowed_char)
407
+ # only reassign genuinely-forbidden characters onto genuinely-allowed ones
408
+ if src_idx is not None and dst_idx is not None and not keep[src_idx] and allowed_char in allowed:
409
+ src.append(src_idx)
410
+ dst.append(dst_idx)
411
+ return keep, torch.tensor(src, dtype=torch.long), torch.tensor(dst, dtype=torch.long)
412
+
413
+
414
+ def add_whitelist(
415
+ model: nn.Module,
416
+ vocabs: str | Iterable[str],
417
+ *,
418
+ strategy: str = "mask",
419
+ mapping: str | dict[str, str] | None = None,
420
+ verbose: bool = False,
421
+ ) -> WhitelistHandle:
422
+ """Restrict a recognition model so it can only predict a subset of its vocabulary.
423
+
424
+ The whitelist is enforced at the model's final projection layer, before the decoding
425
+ `argmax`. Because the projection is the single point every logit flows through, the
426
+ constraint also applies inside the autoregressive decoding loop of SAR, MASTER and PARSeq,
427
+ so a forbidden character can never be produced -- not even fed back mid-word. The sequence
428
+ terminator (CTC `blank` / attention `<eos>`) is always kept so decoding still
429
+ terminates. It works with every recognition architecture and with any predictor wrapping
430
+ one (`ocr_predictor`, `kie_predictor`, `recognition_predictor`).
431
+
432
+ Two strategies are available:
433
+
434
+ * `"mask"` (default): the logits of forbidden characters are set to `-inf`, so decoding
435
+ falls back to the highest-scoring allowed character.
436
+ * `"nearest"`: the score of each forbidden character is first reassigned to the closest
437
+ allowed character (so e.g. `ä` folds onto `a`), then forbidden logits are masked.
438
+ Forbidden characters without a mapping fall back to masking.
439
+
440
+ A whitelist can only restrict a model to characters it already knows: characters that are
441
+ not part of the model's own vocabulary are silently ignored.
442
+
443
+ >>> from doctr.datasets import VOCABS
444
+ >>> from doctr.models import ocr_predictor
445
+ >>> from doctr.models.utils import add_whitelist
446
+ >>> predictor = ocr_predictor(pretrained=True)
447
+ >>> handle = add_whitelist(predictor, [VOCABS["polish"], VOCABS["german"]])
448
+ >>> # ... run the predictor; only Polish/German characters can be predicted ...
449
+ >>> handle.remove() # restore the original, unconstrained decoding
450
+
451
+ Args:
452
+ model: an `ocr_predictor`, `kie_predictor`, `recognition_predictor`, or a recognition model.
453
+ vocabs: a vocabulary string (e.g. `VOCABS["german"]`) or an iterable of vocabulary
454
+ strings (e.g. `[VOCABS["polish"], VOCABS["german"]]`) whose characters are allowed.
455
+ strategy: `"mask"` (default) to drop forbidden characters, or `"nearest"` to fold
456
+ them onto the closest allowed character.
457
+ mapping: only used when `"strategy="nearest"`". `None` or `"anyascii"` builds the
458
+ forbidden-to-allowed map by transliteration (the default); `"weights"` derives it
459
+ from the projection weights (the model's own confusions); a `dict` of
460
+ `{forbidden_char: allowed_char}` overrides specific characters on top of the
461
+ transliteration map.
462
+ verbose: if True, log how many characters were kept, forbidden and reassigned per model.
463
+
464
+ Returns:
465
+ a :class:`WhitelistHandle`; call its :meth:`~WhitelistHandle.remove` method to restore
466
+ the original, unconstrained decoding.
467
+ """
468
+ if strategy not in {"mask", "nearest"}:
469
+ raise ValueError(f"Unknown strategy {strategy!r}; expected 'mask' or 'nearest'.")
470
+ if strategy == "mask" and mapping is not None:
471
+ raise ValueError("The 'mapping' argument is only used with strategy='nearest'.")
472
+ if isinstance(mapping, str) and mapping not in {"anyascii", "weights"}:
473
+ raise ValueError(f"Unknown mapping {mapping!r}; expected 'anyascii', 'weights', a dict or None.")
474
+ if mapping is not None and not isinstance(mapping, (str, dict)):
475
+ raise ValueError("The 'mapping' argument must be None, 'anyascii', 'weights' or a dict.")
476
+
477
+ allowed = set(vocabs) if isinstance(vocabs, str) else {char for vocab in vocabs for char in vocab}
478
+
479
+ handles: list[torch.utils.hooks.RemovableHandle] = []
480
+ reco_model = _recognition_model(model)
481
+ vocab: str = reco_model.vocab # type: ignore[assignment]
482
+ vocab_size = len(vocab)
483
+ if not any(char in allowed for char in vocab):
484
+ raise ValueError(
485
+ "The whitelist shares no character with the model's vocabulary; the model would "
486
+ "be unable to predict anything."
487
+ )
488
+
489
+ # A vocab-level character map (shared by every projection); the weight-based map is
490
+ # derived per projection further down.
491
+ base_map: dict[str, str] = {}
492
+ if strategy == "nearest" and mapping != "weights":
493
+ base_map = _anyascii_nearest_map(vocab, allowed)
494
+ if isinstance(mapping, dict):
495
+ base_map = {**base_map, **mapping}
496
+
497
+ reassigned = 0
498
+ for projection in _vocab_projections(reco_model, vocab_size):
499
+ char_map = (
500
+ _weights_nearest_map(vocab, allowed, projection)
501
+ if strategy == "nearest" and mapping == "weights"
502
+ else base_map
503
+ )
504
+ keep, src, dst = _keep_and_reassign(vocab, allowed, projection.out_features, char_map)
505
+ reassigned = max(reassigned, src.numel())
506
+
507
+ def _constrain_logits(
508
+ _module: nn.Module,
509
+ _inputs: Any,
510
+ output: torch.Tensor,
511
+ keep: torch.Tensor = keep,
512
+ src: torch.Tensor = src,
513
+ dst: torch.Tensor = dst,
514
+ ):
515
+ output = output.clone()
516
+ if src.numel():
517
+ # move each forbidden character's score onto its nearest allowed character
518
+ values = output[..., src.to(output.device)]
519
+ index = dst.to(output.device).view(*([1] * (output.dim() - 1)), -1).expand(*output.shape[:-1], -1)
520
+ output.scatter_reduce_(-1, index, values, reduce="amax", include_self=True)
521
+ output[..., ~keep.to(output.device)] = float("-inf")
522
+ return output
523
+
524
+ handles.append(projection.register_forward_hook(_constrain_logits))
525
+
526
+ if verbose: # pragma: no cover
527
+ kept = sum(char in allowed for char in vocab)
528
+ logger.info(
529
+ f"add_whitelist: {type(reco_model).__name__} - kept {kept}/{vocab_size} vocabulary "
530
+ f"characters, forbade {vocab_size - kept}"
531
+ + (f", reassigned {reassigned} to a nearest allowed character." if strategy == "nearest" else ".")
532
+ )
533
+
534
+ return WhitelistHandle(handles)