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
@@ -0,0 +1,346 @@
1
+ # Copyright (C) 2021-2026, Mindee.
2
+
3
+ # This program is licensed under the Apache License 2.0.
4
+ # See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
5
+
6
+ import math
7
+ from copy import deepcopy
8
+ from functools import partial
9
+ from typing import Any
10
+
11
+ import torch
12
+ import torch.nn.functional as F
13
+ from torch import nn
14
+
15
+ from doctr.datasets import VOCABS
16
+
17
+ from ...utils import load_pretrained_params
18
+ from .layers import PatchEmbed, WindowedCAETransformerBlock
19
+
20
+ __all__ = ["VisionDetectionTransformer", "vit_det_s", "vit_det_m"]
21
+
22
+
23
+ default_cfgs: dict[str, dict[str, Any]] = {
24
+ "vit_det_s": {
25
+ "mean": (0.694, 0.695, 0.693),
26
+ "std": (0.299, 0.296, 0.301),
27
+ "input_shape": (3, 32, 32),
28
+ "classes": list(VOCABS["french"]),
29
+ "url": "https://github.com/mindee/doctr/releases/download/v1.0.1/vit_det_s-56a33dee.pt",
30
+ },
31
+ "vit_det_m": {
32
+ "mean": (0.694, 0.695, 0.693),
33
+ "std": (0.299, 0.296, 0.301),
34
+ "input_shape": (3, 32, 32),
35
+ "classes": list(VOCABS["french"]),
36
+ "url": "https://github.com/mindee/doctr/releases/download/v1.0.1/vit_det_m-669daf92.pt",
37
+ },
38
+ }
39
+
40
+
41
+ class ClassifierHead(nn.Module):
42
+ """Classifier head for Vision Detection Transformer
43
+
44
+ Args:
45
+ in_channels: number of input channels
46
+ num_classes: number of output classes
47
+ """
48
+
49
+ def __init__(self, in_channels: int, num_classes: int):
50
+ super().__init__()
51
+ self.norm = nn.LayerNorm(in_channels)
52
+ self.fc = nn.Linear(in_channels, num_classes)
53
+
54
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
55
+ # (B, C, H, W)
56
+ x = x.flatten(2).mean(dim=-1) # global average pooling (B, C)
57
+ x = self.norm(x)
58
+ return self.fc(x)
59
+
60
+
61
+ class TakeLastFeature(nn.Module):
62
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
63
+ return x[-1]
64
+
65
+
66
+ class ViTInput(nn.Module):
67
+ """ViT input module, which includes the patch embedding and positional embedding
68
+
69
+ Args:
70
+ patch_embed: the patch embedding module
71
+ pos_embed: the positional embedding module
72
+ has_cls_token: whether the input includes a cls token
73
+ """
74
+
75
+ def __init__(self, patch_embed: PatchEmbed, pos_embed: torch.Tensor, has_cls_token: bool = True):
76
+ super().__init__()
77
+ self.patch_embed = patch_embed
78
+ self.pos_embed = pos_embed
79
+ self.has_cls_token = has_cls_token
80
+
81
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
82
+ x = self.patch_embed(x)
83
+ H, W = x.shape[1], x.shape[2]
84
+
85
+ pos_embed = self.pos_embed
86
+ if self.has_cls_token:
87
+ pos_embed = pos_embed[:, 1:]
88
+
89
+ xy_num = pos_embed.shape[1]
90
+ size = int(math.sqrt(xy_num))
91
+
92
+ if size != H or size != W: # pragma: no cover
93
+ pos_embed = F.interpolate(
94
+ pos_embed.reshape(1, size, size, -1).permute(0, 3, 1, 2),
95
+ size=(H, W),
96
+ mode="bicubic",
97
+ align_corners=False,
98
+ ).permute(0, 2, 3, 1)
99
+ else:
100
+ pos_embed = pos_embed.reshape(1, H, W, -1)
101
+
102
+ return x + pos_embed
103
+
104
+
105
+ class ViTTokenize(nn.Module):
106
+ """ViT tokenize module, which reshapes the input feature map into a sequence of tokens"""
107
+
108
+ def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, tuple[int, int, int, int, int, int]]:
109
+ B, H, W, C = x.shape
110
+ h, w = H // 4, W // 4
111
+ x = x.reshape(B, 4, h, 4, w, C).permute(0, 1, 3, 2, 4, 5).reshape(B * 16, h * w, C)
112
+ return x, (B, H, W, h, w, C)
113
+
114
+
115
+ class ViTStage(nn.Module):
116
+ """ "ViT stage module, which includes a list of transformer blocks and outputs the features of the specified blocks
117
+
118
+ Args:
119
+ blocks: a list of transformer blocks
120
+ out_features_mask: a list of booleans indicating which blocks' features to output
121
+ """
122
+
123
+ def __init__(self, blocks: list[WindowedCAETransformerBlock], out_features_mask: list[bool]):
124
+ super().__init__()
125
+ self.blocks = nn.ModuleList(blocks)
126
+ self.out_features_mask = out_features_mask
127
+
128
+ def forward(self, inputs: tuple[torch.Tensor, tuple[int, int, int, int, int, int]]) -> list[torch.Tensor]:
129
+ x, meta = inputs
130
+ B, H, W, h, w, C = meta
131
+
132
+ outputs = []
133
+
134
+ for idx, blk in enumerate(self.blocks):
135
+ x = blk(x, mask=None)
136
+
137
+ if self.out_features_mask[idx]:
138
+ feat = x.reshape(B, 4, 4, h, w, C).permute(0, 5, 1, 3, 2, 4).reshape(B, C, H, W)
139
+ outputs.append(feat)
140
+
141
+ return outputs
142
+
143
+
144
+ class VisionDetectionTransformer(nn.Sequential):
145
+ """VisionDetectionTransformer architecture as described in
146
+ `"Exploring Plain Vision Transformer Backbones for Object Detection",
147
+ <https://arxiv.org/abs/2203.16527>`_.
148
+
149
+ Args:
150
+ d_model: dimension of the transformer layers
151
+ num_layers: number of transformer layers
152
+ num_heads: number of attention heads
153
+ ffd_ratio: multiplier for the hidden dimension of the feedforward layer
154
+ patch_size: size of the patches
155
+ input_shape: size of the input image
156
+ dropout: dropout rate
157
+ window_block_indexes: list of block indices that use window attention
158
+ out_feature_indexes: list of block indices whose features are output
159
+ num_classes: number of output classes
160
+ include_top: whether the classifier head should be instantiated
161
+ cfg: additional configuration dictionary
162
+ """
163
+
164
+ def __init__(
165
+ self,
166
+ d_model: int,
167
+ num_layers: int,
168
+ num_heads: int,
169
+ mlp_ratio: float = 4.0,
170
+ patch_size: tuple[int, int] = (4, 4),
171
+ input_shape: tuple[int, int, int] = (3, 32, 32),
172
+ dropout: float = 0.1,
173
+ window_block_indexes: list[int] = [0, 1, 3, 6, 7, 9],
174
+ out_feature_indexes: list[int] = [2, 4, 5, 9],
175
+ num_classes: int = 1000,
176
+ include_top: bool = True,
177
+ cfg: dict[str, Any] | None = None,
178
+ ) -> None:
179
+
180
+ in_chans = input_shape[0]
181
+
182
+ patch_embed = PatchEmbed(
183
+ kernel_size=patch_size,
184
+ stride=patch_size,
185
+ in_chans=in_chans,
186
+ embed_dim=d_model,
187
+ )
188
+
189
+ # Initialize absolute positional embedding with pretrain image size.
190
+ num_patches = (input_shape[1] // patch_size[0]) * (input_shape[2] // patch_size[1])
191
+ pos_embed = nn.Parameter(torch.zeros(1, (num_patches + 1), d_model))
192
+ nn.init.trunc_normal_(pos_embed, std=0.02)
193
+
194
+ # stochastic depth decay rule
195
+ dpr = [x.item() for x in torch.linspace(0, dropout, num_layers)]
196
+
197
+ # blocks
198
+ blocks = [
199
+ WindowedCAETransformerBlock(
200
+ dim=d_model,
201
+ num_heads=num_heads,
202
+ mlp_ratio=mlp_ratio,
203
+ qkv_bias=True,
204
+ drop_prob=dpr[i],
205
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
206
+ window=(i in window_block_indexes),
207
+ use_cae=True,
208
+ )
209
+ for i in range(num_layers)
210
+ ]
211
+
212
+ # normalize feature indices
213
+ out_feature_indexes = [i if i >= 0 else i + num_layers for i in out_feature_indexes]
214
+ out_mask = [i in out_feature_indexes for i in range(num_layers)]
215
+
216
+ _layers = [
217
+ ViTInput(patch_embed, pos_embed, has_cls_token=True),
218
+ ViTTokenize(),
219
+ ViTStage(blocks, out_mask),
220
+ ]
221
+ if include_top:
222
+ _layers.extend([
223
+ TakeLastFeature(),
224
+ ClassifierHead(d_model, num_classes),
225
+ ])
226
+
227
+ super().__init__(*_layers)
228
+ self.cfg = cfg
229
+ self.apply(self._init_weights)
230
+
231
+ def _init_weights(self, m):
232
+ if isinstance(m, (nn.Linear, nn.Conv2d)):
233
+ nn.init.trunc_normal_(m.weight, mean=0.0, std=0.02)
234
+ if m.bias is not None:
235
+ nn.init.zeros_(m.bias)
236
+ elif isinstance(m, nn.LayerNorm):
237
+ nn.init.zeros_(m.bias)
238
+ nn.init.ones_(m.weight)
239
+ elif isinstance(m, ViTInput):
240
+ if isinstance(m.pos_embed, torch.nn.Parameter):
241
+ nn.init.trunc_normal_(m.pos_embed, mean=0.0, std=0.02)
242
+ elif isinstance(m, WindowedCAETransformerBlock):
243
+ if m.use_cae:
244
+ nn.init.constant_(m.gamma_1, 0.1)
245
+ nn.init.constant_(m.gamma_2, 0.1)
246
+
247
+ def from_pretrained(self, path_or_url: str, **kwargs: Any) -> None:
248
+ """Load pretrained parameters onto the model
249
+
250
+ Args:
251
+ path_or_url: the path or URL to the model parameters (checkpoint)
252
+ **kwargs: additional arguments to be passed to `doctr.models.utils.load_pretrained_params`
253
+ """
254
+ load_pretrained_params(self, path_or_url, **kwargs)
255
+
256
+
257
+ def _vit_det(
258
+ arch: str,
259
+ pretrained: bool,
260
+ ignore_keys: list[str] | None = None,
261
+ **kwargs: Any,
262
+ ) -> VisionDetectionTransformer:
263
+ kwargs["num_classes"] = kwargs.get("num_classes", len(default_cfgs[arch]["classes"]))
264
+ kwargs["input_shape"] = kwargs.get("input_shape", default_cfgs[arch]["input_shape"])
265
+ kwargs["classes"] = kwargs.get("classes", default_cfgs[arch]["classes"])
266
+
267
+ _cfg = deepcopy(default_cfgs[arch])
268
+ _cfg["num_classes"] = kwargs["num_classes"]
269
+ _cfg["input_shape"] = kwargs["input_shape"]
270
+ _cfg["classes"] = kwargs["classes"]
271
+ kwargs.pop("classes")
272
+
273
+ # Build the model
274
+ model = VisionDetectionTransformer(cfg=_cfg, **kwargs)
275
+ # Load pretrained parameters
276
+ if pretrained:
277
+ # The number of classes is not the same as the number of classes in the pretrained model =>
278
+ # remove the last layer weights
279
+ _ignore_keys = ignore_keys if kwargs["num_classes"] != len(default_cfgs[arch]["classes"]) else None
280
+ model.from_pretrained(default_cfgs[arch]["url"], ignore_keys=_ignore_keys)
281
+
282
+ return model
283
+
284
+
285
+ def vit_det_s(pretrained: bool = False, **kwargs: Any) -> VisionDetectionTransformer:
286
+ """VisionDetectionTransformer-S architecture
287
+ `"Exploring Plain Vision Transformer Backbones for Object Detection",
288
+ <https://arxiv.org/abs/2203.16527>`_.
289
+
290
+ NOTE: Modified for LW-DETR
291
+
292
+ >>> import torch
293
+ >>> from doctr.models import vit_det_s
294
+ >>> model = vit_det_s(pretrained=False)
295
+ >>> input_tensor = torch.rand((1, 3, 32, 32), dtype=torch.float32)
296
+ >>> out = model(input_tensor)
297
+
298
+ Args:
299
+ pretrained: If True, returns a model pre-trained on our classification dataset
300
+ **kwargs: keyword arguments of the VisionDetectionTransformer architecture
301
+
302
+ Returns:
303
+ A feature extractor model
304
+ """
305
+ return _vit_det(
306
+ "vit_det_s",
307
+ pretrained,
308
+ d_model=192,
309
+ num_layers=10,
310
+ num_heads=12,
311
+ mlp_ratio=4.0,
312
+ ignore_keys=["4.norm.weight", "4.norm.bias", "4.fc.weight", "4.fc.bias"],
313
+ **kwargs,
314
+ )
315
+
316
+
317
+ def vit_det_m(pretrained: bool = False, **kwargs: Any) -> VisionDetectionTransformer:
318
+ """VisionDetectionTransformer-B architecture as described in
319
+ `"Exploring Plain Vision Transformer Backbones for Object Detection",
320
+ <https://arxiv.org/abs/2203.16527>`_.
321
+
322
+ NOTE: Modified for LW-DETR
323
+
324
+ >>> import torch
325
+ >>> from doctr.models import vit_det_m
326
+ >>> model = vit_det_m(pretrained=False)
327
+ >>> input_tensor = torch.rand((1, 3, 32, 32), dtype=torch.float32)
328
+ >>> out = model(input_tensor)
329
+
330
+ Args:
331
+ pretrained: If True, returns a model pre-trained on our classification dataset
332
+ **kwargs: keyword arguments of the VisionTransformer architecture
333
+
334
+ Returns:
335
+ A feature extractor model
336
+ """
337
+ return _vit_det(
338
+ "vit_det_m",
339
+ pretrained,
340
+ d_model=384,
341
+ num_layers=10,
342
+ num_heads=12,
343
+ mlp_ratio=4.0,
344
+ ignore_keys=["4.norm.weight", "4.norm.bias", "4.fc.weight", "4.fc.bias"],
345
+ **kwargs,
346
+ )
@@ -32,6 +32,10 @@ ARCHS: list[str] = [
32
32
  "vit_b",
33
33
  "vip_tiny",
34
34
  "vip_base",
35
+ "vit_det_s",
36
+ "vit_det_m",
37
+ "starnet_s3",
38
+ "hgnetv2_b4",
35
39
  ]
36
40
 
37
41
  ORIENTATION_ARCHS: list[str] = ["mobilenet_v3_small_crop_orientation", "mobilenet_v3_small_page_orientation"]
@@ -42,7 +46,7 @@ def _orientation_predictor(
42
46
  ) -> OrientationPredictor:
43
47
  if disabled:
44
48
  # Case where the orientation predictor is disabled
45
- return OrientationPredictor(None, None)
49
+ return OrientationPredictor(None, None, chunk_size=kwargs.get("chunk_size", 32))
46
50
 
47
51
  if isinstance(arch, str):
48
52
  if arch not in ORIENTATION_ARCHS:
@@ -61,9 +65,13 @@ def _orientation_predictor(
61
65
  kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
62
66
  kwargs["std"] = kwargs.get("std", _model.cfg["std"])
63
67
  kwargs["batch_size"] = kwargs.get("batch_size", 128 if model_type == "crop" else 4)
68
+ # Crops are much smaller than pages: many more of them fit in memory at once
69
+ chunk_size = kwargs.pop("chunk_size", 1024 if model_type == "crop" else 32)
64
70
  input_shape = _model.cfg["input_shape"][1:]
65
71
  predictor = OrientationPredictor(
66
- PreProcessor(input_shape, preserve_aspect_ratio=True, symmetric_pad=True, **kwargs), _model
72
+ PreProcessor(input_shape, preserve_aspect_ratio=True, symmetric_pad=True, **kwargs),
73
+ _model,
74
+ chunk_size=chunk_size,
67
75
  )
68
76
  return predictor
69
77
 
@@ -83,6 +91,8 @@ def crop_orientation_predictor(
83
91
  arch: name of the architecture to use (e.g. 'mobilenet_v3_small_crop_orientation')
84
92
  pretrained: If True, returns a model pre-trained on our recognition crops dataset
85
93
  batch_size: number of samples the model processes in parallel
94
+ chunk_size: maximum number of crops decoded and processed at once (1024 by default): longer inputs and
95
+ lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
86
96
  **kwargs: keyword arguments to be passed to the OrientationPredictor
87
97
 
88
98
  Returns:
@@ -106,6 +116,8 @@ def page_orientation_predictor(
106
116
  arch: name of the architecture to use (e.g. 'mobilenet_v3_small_page_orientation')
107
117
  pretrained: If True, returns a model pre-trained on our recognition crops dataset
108
118
  batch_size: number of samples the model processes in parallel
119
+ chunk_size: maximum number of pages decoded and processed at once (32 by default): longer inputs and
120
+ lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
109
121
  **kwargs: keyword arguments to be passed to the OrientationPredictor
110
122
 
111
123
  Returns:
@@ -20,7 +20,8 @@ def _remove_padding(
20
20
 
21
21
  Args:
22
22
  pages: list of pages
23
- loc_preds: list of localization predictions
23
+ loc_preds: list of localization predictions (N, 5, 2) or (N, 4, 2) for non-straight pages,
24
+ (N, 5) or (N, 4) for straight pages
24
25
  preserve_aspect_ratio: whether the aspect ratio was preserved during padding
25
26
  symmetric_pad: whether the padding was symmetric
26
27
  assume_straight_pages: whether the pages are assumed to be straight
@@ -32,32 +33,47 @@ def _remove_padding(
32
33
  # Rectify loc_preds to remove padding
33
34
  rectified_preds = []
34
35
  for page, dict_loc_preds in zip(pages, loc_preds):
36
+ h, w = page.shape[0], page.shape[1]
37
+ rectified_page_preds = {}
35
38
  for k, loc_pred in dict_loc_preds.items():
36
- h, w = page.shape[0], page.shape[1]
39
+ loc_pred = loc_pred.copy()
37
40
  if h > w:
38
41
  # y unchanged, dilate x coord
39
42
  if symmetric_pad:
40
43
  if assume_straight_pages:
41
44
  loc_pred[:, [0, 2]] = (loc_pred[:, [0, 2]] - 0.5) * h / w + 0.5
42
45
  else:
43
- loc_pred[:, :, 0] = (loc_pred[:, :, 0] - 0.5) * h / w + 0.5
46
+ if loc_pred.shape[1] == 5: # case with box score
47
+ loc_pred[:, :-1, 0] = (loc_pred[:, :-1, 0] - 0.5) * h / w + 0.5
48
+ else:
49
+ loc_pred[:, :, 0] = (loc_pred[:, :, 0] - 0.5) * h / w + 0.5
44
50
  else:
45
51
  if assume_straight_pages:
46
52
  loc_pred[:, [0, 2]] *= h / w
47
53
  else:
48
- loc_pred[:, :, 0] *= h / w
54
+ if loc_pred.shape[1] == 5: # case with box score
55
+ loc_pred[:, :-1, 0] *= h / w
56
+ else:
57
+ loc_pred[:, :, 0] *= h / w
49
58
  elif w > h:
50
59
  # x unchanged, dilate y coord
51
60
  if symmetric_pad:
52
61
  if assume_straight_pages:
53
62
  loc_pred[:, [1, 3]] = (loc_pred[:, [1, 3]] - 0.5) * w / h + 0.5
54
63
  else:
55
- loc_pred[:, :, 1] = (loc_pred[:, :, 1] - 0.5) * w / h + 0.5
64
+ if loc_pred.shape[1] == 5: # case with box score
65
+ loc_pred[:, :-1, 1] = (loc_pred[:, :-1, 1] - 0.5) * w / h + 0.5
66
+ else:
67
+ loc_pred[:, :, 1] = (loc_pred[:, :, 1] - 0.5) * w / h + 0.5
56
68
  else:
57
69
  if assume_straight_pages:
58
70
  loc_pred[:, [1, 3]] *= w / h
59
71
  else:
60
- loc_pred[:, :, 1] *= w / h
61
- rectified_preds.append({k: np.clip(loc_pred, 0, 1)})
72
+ if loc_pred.shape[1] == 5: # case with box score
73
+ loc_pred[:, :-1, 1] *= w / h
74
+ else:
75
+ loc_pred[:, :, 1] *= w / h
76
+ rectified_page_preds[k] = np.clip(loc_pred, 0, 1, out=loc_pred)
77
+ rectified_preds.append(rectified_page_preds)
62
78
  return rectified_preds
63
79
  return loc_preds
@@ -52,10 +52,15 @@ class DetectionPostProcessor(NestedObject):
52
52
  return pred[ymin : ymax + 1, xmin : xmax + 1].mean()
53
53
 
54
54
  else:
55
- mask: np.ndarray = np.zeros((h, w), np.int32)
56
- cv2.fillPoly(mask, [points.astype(np.int32)], 1.0)
57
- product = pred * mask
58
- return np.sum(product) / np.count_nonzero(product)
55
+ pts: np.ndarray = points.reshape((-1, 2)).astype(np.int32)
56
+ xmin = np.clip(pts[:, 0].min(), 0, w - 1)
57
+ xmax = np.clip(pts[:, 0].max(), 0, w - 1)
58
+ ymin = np.clip(pts[:, 1].min(), 0, h - 1)
59
+ ymax = np.clip(pts[:, 1].max(), 0, h - 1)
60
+ mask: np.ndarray = np.zeros((ymax - ymin + 1, xmax - xmin + 1), dtype=np.uint8)
61
+ cv2.fillPoly(mask, [pts - np.array([[xmin, ymin]], dtype=np.int32)], 1)
62
+ vals = pred[ymin : ymax + 1, xmin : xmax + 1][mask.astype(bool)]
63
+ return float(vals.mean()) if vals.size > 0 else 0.0
59
64
 
60
65
  def bitmap_to_boxes(
61
66
  self,
@@ -64,6 +69,28 @@ class DetectionPostProcessor(NestedObject):
64
69
  ) -> np.ndarray:
65
70
  raise NotImplementedError
66
71
 
72
+ def _process_sample(self, proba_map: np.ndarray) -> list[np.ndarray]:
73
+ """Performs postprocessing for a single sample
74
+
75
+ Args:
76
+ proba_map: probability map of shape (H, W, C)
77
+
78
+ Returns:
79
+ list of C class predictions, each of shape (*, 5) or (*, 6)
80
+ """
81
+ return [
82
+ self.bitmap_to_boxes(
83
+ proba_map[..., idx],
84
+ # Erosion + dilation on the binary map
85
+ cv2.morphologyEx(
86
+ (proba_map[..., idx] >= self.bin_thresh).astype(np.uint8),
87
+ cv2.MORPH_OPEN,
88
+ self._opening_kernel,
89
+ ),
90
+ )
91
+ for idx in range(proba_map.shape[-1])
92
+ ]
93
+
67
94
  def __call__(
68
95
  self,
69
96
  proba_map,
@@ -79,17 +106,4 @@ class DetectionPostProcessor(NestedObject):
79
106
  """
80
107
  if proba_map.ndim != 4:
81
108
  raise AssertionError(f"arg `proba_map` is expected to be 4-dimensional, got {proba_map.ndim}.")
82
-
83
- # Erosion + dilation on the binary map
84
- bin_map = [
85
- [
86
- cv2.morphologyEx(bmap[..., idx], cv2.MORPH_OPEN, self._opening_kernel)
87
- for idx in range(proba_map.shape[-1])
88
- ]
89
- for bmap in (proba_map >= self.bin_thresh).astype(np.uint8)
90
- ]
91
-
92
- return [
93
- [self.bitmap_to_boxes(pmaps[..., idx], bmaps[idx]) for idx in range(proba_map.shape[-1])]
94
- for pmaps, bmaps in zip(proba_map, bin_map)
95
- ]
109
+ return [self._process_sample(sample) for sample in proba_map]
@@ -11,6 +11,8 @@ import numpy as np
11
11
  import pyclipper
12
12
  from shapely.geometry import Polygon
13
13
 
14
+ from doctr.utils import order_points
15
+
14
16
  from ..core import DetectionPostProcessor
15
17
 
16
18
  __all__ = ["DBPostProcessor"]
@@ -80,7 +82,7 @@ class DBPostProcessor(DetectionPostProcessor):
80
82
  return (
81
83
  cv2.boundingRect(expanded_points) # type: ignore[return-value]
82
84
  if self.assume_straight_pages
83
- else np.roll(cv2.boxPoints(cv2.minAreaRect(expanded_points)), -1, axis=0)
85
+ else order_points(cv2.boxPoints(cv2.minAreaRect(expanded_points)))
84
86
  )
85
87
 
86
88
  def bitmap_to_boxes(
@@ -93,8 +95,6 @@ class DBPostProcessor(DetectionPostProcessor):
93
95
  Args:
94
96
  pred: Pred map from differentiable binarization output
95
97
  bitmap: Bitmap map computed from pred (binarized)
96
- angle_tol: Comparison tolerance of the angle with the median angle across the page
97
- ratio_tol: Under this limit aspect ratio, we cannot resolve the direction of the crop
98
98
 
99
99
  Returns:
100
100
  np tensor boxes for the bitmap, each box is a 5-element list
@@ -129,7 +129,7 @@ class DBPostProcessor(DetectionPostProcessor):
129
129
  if self.assume_straight_pages:
130
130
  if _box is None or _box[2] < min_size_box or _box[3] < min_size_box:
131
131
  continue
132
- elif np.linalg.norm(_box[2, :] - _box[0, :], axis=-1) < min_size_box:
132
+ elif _box is None or np.linalg.norm(_box[2, :] - _box[0, :], axis=-1) < min_size_box:
133
133
  continue
134
134
 
135
135
  if self.assume_straight_pages:
@@ -139,7 +139,7 @@ class DBPostProcessor(DetectionPostProcessor):
139
139
  boxes.append([xmin, ymin, xmax, ymax, score])
140
140
  else:
141
141
  # compute relative box to get rid of img shape, in that case _box is a 4pt polygon
142
- if not isinstance(_box, np.ndarray) and _box.shape == (4, 2):
142
+ if not (isinstance(_box, np.ndarray) and _box.shape == (4, 2)):
143
143
  raise AssertionError("When assume straight pages is false a box is a (4, 2) array (polygon)")
144
144
  _box[:, 0] /= width
145
145
  _box[:, 1] /= height
@@ -166,6 +166,8 @@ class _DBNet:
166
166
  thresh_max = 0.7
167
167
  min_size_box = 3
168
168
  assume_straight_pages: bool = True
169
+ mask_empty_classes: bool = False
170
+ class_names: list[str] # set by the framework model
169
171
 
170
172
  @staticmethod
171
173
  def compute_distance(
@@ -241,7 +243,7 @@ class _DBNet:
241
243
  ys: np.ndarray = np.broadcast_to(np.linspace(0, height - 1, num=height).reshape(height, 1), (height, width))
242
244
 
243
245
  # Compute distance map to fill the padded polygon
244
- distance_map = np.zeros((polygon.shape[0], height, width), dtype=polygon.dtype)
246
+ distance_map = np.zeros((polygon.shape[0], height, width), dtype=np.float32)
245
247
  for i in range(polygon.shape[0]):
246
248
  j = (i + 1) % polygon.shape[0]
247
249
  absolute_distance = self.compute_distance(xs, ys, polygon[i], polygon[j])
@@ -289,10 +291,22 @@ class _DBNet:
289
291
  thresh_mask: np.ndarray = np.zeros(target_shape, dtype=np.uint8)
290
292
 
291
293
  for idx, tgt in enumerate(target):
292
- for class_idx, _tgt in enumerate(tgt.values()):
294
+ unknown = set(tgt) - set(self.class_names)
295
+ missing = set(self.class_names) - set(tgt)
296
+ if unknown or missing:
297
+ raise ValueError(
298
+ f"target classes {sorted(tgt)} do not match the model classes {list(self.class_names)}"
299
+ + (f" (unknown: {sorted(unknown)})" if unknown else "")
300
+ + (f" (missing: {sorted(missing)})" if missing else "")
301
+ )
302
+ # Channels follow the order of the model's class names, whatever the order of the target dict
303
+ for class_idx, class_name in enumerate(self.class_names):
304
+ _tgt = tgt[class_name]
293
305
  # Draw each polygon on gt
294
- if _tgt.shape[0] == 0:
295
- # Empty image, full masked
306
+ if _tgt.shape[0] == 0 and self.mask_empty_classes:
307
+ # No box for this class: with `mask_empty_classes` the channel is ignored by the loss (partially
308
+ # annotated data); by default it is supervised as background, an image without any box being
309
+ # a true negative
296
310
  seg_mask[idx, class_idx] = False
297
311
 
298
312
  # Absolute bounding boxes
@@ -106,6 +106,8 @@ class DBNet(_DBNet, nn.Module):
106
106
  exportable: onnx exportable returns only logits
107
107
  cfg: the configuration dict of the model
108
108
  class_names: list of class names
109
+ mask_empty_classes: if True, a class without any box in an image is masked out of the loss (use it for
110
+ partially annotated data); by default the absence is supervised as background
109
111
  """
110
112
 
111
113
  def __init__(
@@ -119,9 +121,11 @@ class DBNet(_DBNet, nn.Module):
119
121
  exportable: bool = False,
120
122
  cfg: dict[str, Any] | None = None,
121
123
  class_names: list[str] = [CLASS_NAME],
124
+ mask_empty_classes: bool = False,
122
125
  ) -> None:
123
126
  super().__init__()
124
127
  self.class_names = class_names
128
+ self.mask_empty_classes = mask_empty_classes
125
129
  num_classes: int = len(self.class_names)
126
130
  self.cfg = cfg
127
131
 
@@ -268,9 +272,11 @@ class DBNet(_DBNet, nn.Module):
268
272
  thresh_target, thresh_mask = torch.from_numpy(targets[2]), torch.from_numpy(targets[3])
269
273
  thresh_target, thresh_mask = thresh_target.to(out_map.device), thresh_mask.to(out_map.device)
270
274
 
275
+ # Every term defaults to a zero that keeps the graph, so a fully masked batch does not crash
276
+ focal_loss = dice_loss = l1_loss = out_map.sum() * 0
277
+ focal_scale = 10.0
271
278
  if torch.any(seg_mask):
272
279
  # Focal loss
273
- focal_scale = 10.0
274
280
  bce_loss = F.binary_cross_entropy_with_logits(out_map, seg_target, reduction="none")
275
281
 
276
282
  p_t = prob_map * seg_target + (1 - prob_map) * (1 - seg_target)
@@ -353,7 +359,7 @@ def db_resnet34(pretrained: bool = False, **kwargs: Any) -> DBNet:
353
359
  >>> out = model(input_tensor)
354
360
 
355
361
  Args:
356
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
362
+ pretrained: If True, returns a model pre-trained on our text detection dataset
357
363
  **kwargs: keyword arguments of the DBNet architecture
358
364
 
359
365
  Returns:
@@ -386,7 +392,7 @@ def db_resnet50(pretrained: bool = False, **kwargs: Any) -> DBNet:
386
392
  >>> out = model(input_tensor)
387
393
 
388
394
  Args:
389
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
395
+ pretrained: If True, returns a model pre-trained on our text detection dataset
390
396
  **kwargs: keyword arguments of the DBNet architecture
391
397
 
392
398
  Returns:
@@ -419,7 +425,7 @@ def db_mobilenet_v3_large(pretrained: bool = False, **kwargs: Any) -> DBNet:
419
425
  >>> out = model(input_tensor)
420
426
 
421
427
  Args:
422
- pretrained (bool): If True, returns a model pre-trained on our text detection dataset
428
+ pretrained: If True, returns a model pre-trained on our text detection dataset
423
429
  **kwargs: keyword arguments of the DBNet architecture
424
430
 
425
431
  Returns: