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.
Files changed (138) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +506 -0
  3. doctr/contrib/artefacts.py +1 -1
  4. doctr/contrib/base.py +1 -1
  5. doctr/datasets/__init__.py +2 -0
  6. doctr/datasets/coco_text.py +5 -3
  7. doctr/datasets/cord.py +3 -2
  8. doctr/datasets/datasets/base.py +13 -25
  9. doctr/datasets/datasets/pytorch.py +15 -5
  10. doctr/datasets/detection.py +3 -2
  11. doctr/datasets/doc_artefacts.py +3 -2
  12. doctr/datasets/funsd.py +3 -2
  13. doctr/datasets/generator/base.py +6 -5
  14. doctr/datasets/generator/pytorch.py +5 -6
  15. doctr/datasets/ic03.py +4 -3
  16. doctr/datasets/ic13.py +5 -3
  17. doctr/datasets/iiit5k.py +3 -2
  18. doctr/datasets/iiithws.py +5 -3
  19. doctr/datasets/imgur5k.py +5 -3
  20. doctr/datasets/layout.py +123 -0
  21. doctr/datasets/mjsynth.py +5 -3
  22. doctr/datasets/ocr.py +3 -2
  23. doctr/datasets/orientation.py +3 -2
  24. doctr/datasets/recognition.py +3 -2
  25. doctr/datasets/sroie.py +3 -2
  26. doctr/datasets/svhn.py +3 -2
  27. doctr/datasets/svt.py +4 -3
  28. doctr/datasets/synthtext.py +3 -2
  29. doctr/datasets/table_structure.py +97 -0
  30. doctr/datasets/utils.py +15 -6
  31. doctr/datasets/vocabs.py +3 -1
  32. doctr/datasets/wildreceipt.py +5 -3
  33. doctr/file_utils.py +4 -2
  34. doctr/io/__init__.py +1 -0
  35. doctr/io/elements.py +253 -261
  36. doctr/io/exporters.py +1275 -0
  37. doctr/io/html.py +1 -1
  38. doctr/io/image/base.py +4 -3
  39. doctr/io/image/pytorch.py +6 -4
  40. doctr/io/pdf.py +1 -1
  41. doctr/io/reader.py +1 -1
  42. doctr/models/__init__.py +2 -0
  43. doctr/models/_utils.py +111 -25
  44. doctr/models/builder.py +533 -62
  45. doctr/models/classification/__init__.py +2 -0
  46. doctr/models/classification/magc_resnet/pytorch.py +2 -2
  47. doctr/models/classification/mobilenet/pytorch.py +7 -7
  48. doctr/models/classification/predictor/pytorch.py +7 -3
  49. doctr/models/classification/resnet/pytorch.py +6 -6
  50. doctr/models/classification/starnet/__init__.py +1 -0
  51. doctr/models/classification/starnet/pytorch.py +202 -0
  52. doctr/models/classification/textnet/pytorch.py +7 -6
  53. doctr/models/classification/vgg/pytorch.py +4 -3
  54. doctr/models/classification/vip/layers/pytorch.py +5 -5
  55. doctr/models/classification/vip/pytorch.py +5 -5
  56. doctr/models/classification/vit/pytorch.py +4 -4
  57. doctr/models/classification/vit_det/__init__.py +1 -0
  58. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  59. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  60. doctr/models/classification/vit_det/pytorch.py +346 -0
  61. doctr/models/classification/zoo.py +4 -1
  62. doctr/models/core.py +1 -1
  63. doctr/models/detection/_utils/base.py +24 -8
  64. doctr/models/detection/_utils/pytorch.py +1 -1
  65. doctr/models/detection/core.py +34 -19
  66. doctr/models/detection/differentiable_binarization/base.py +7 -5
  67. doctr/models/detection/differentiable_binarization/pytorch.py +4 -4
  68. doctr/models/detection/fast/base.py +6 -2
  69. doctr/models/detection/fast/pytorch.py +4 -4
  70. doctr/models/detection/linknet/base.py +6 -2
  71. doctr/models/detection/linknet/pytorch.py +4 -4
  72. doctr/models/detection/predictor/pytorch.py +4 -3
  73. doctr/models/detection/zoo.py +3 -3
  74. doctr/models/factory/hub.py +72 -52
  75. doctr/models/kie_predictor/base.py +17 -2
  76. doctr/models/kie_predictor/pytorch.py +42 -11
  77. doctr/models/layout/__init__.py +2 -0
  78. doctr/models/layout/lw_detr/__init__.py +1 -0
  79. doctr/models/layout/lw_detr/base.py +309 -0
  80. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  81. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  82. doctr/models/layout/lw_detr/pytorch.py +838 -0
  83. doctr/models/layout/predictor/__init__.py +1 -0
  84. doctr/models/layout/predictor/pytorch.py +82 -0
  85. doctr/models/layout/zoo.py +90 -0
  86. doctr/models/modules/layers/pytorch.py +140 -4
  87. doctr/models/modules/transformer/pytorch.py +1 -1
  88. doctr/models/modules/vision_transformer/pytorch.py +1 -1
  89. doctr/models/predictor/base.py +138 -16
  90. doctr/models/predictor/pytorch.py +151 -9
  91. doctr/models/preprocessor/pytorch.py +78 -23
  92. doctr/models/reading_order/__init__.py +1 -0
  93. doctr/models/reading_order/base.py +667 -0
  94. doctr/models/recognition/core.py +1 -1
  95. doctr/models/recognition/crnn/pytorch.py +6 -8
  96. doctr/models/recognition/master/base.py +1 -1
  97. doctr/models/recognition/master/pytorch.py +7 -8
  98. doctr/models/recognition/parseq/base.py +1 -1
  99. doctr/models/recognition/parseq/pytorch.py +5 -5
  100. doctr/models/recognition/predictor/_utils.py +1 -1
  101. doctr/models/recognition/predictor/pytorch.py +2 -2
  102. doctr/models/recognition/sar/pytorch.py +2 -2
  103. doctr/models/recognition/utils.py +9 -11
  104. doctr/models/recognition/viptr/pytorch.py +4 -6
  105. doctr/models/recognition/vitstr/base.py +1 -1
  106. doctr/models/recognition/vitstr/pytorch.py +6 -6
  107. doctr/models/recognition/zoo.py +6 -7
  108. doctr/models/table_structure/__init__.py +2 -0
  109. doctr/models/table_structure/predictor/__init__.py +1 -0
  110. doctr/models/table_structure/predictor/pytorch.py +80 -0
  111. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  112. doctr/models/table_structure/tablecenternet/base.py +485 -0
  113. doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
  114. doctr/models/table_structure/zoo.py +82 -0
  115. doctr/models/utils/pytorch.py +316 -16
  116. doctr/models/zoo.py +91 -3
  117. doctr/transforms/functional/base.py +3 -2
  118. doctr/transforms/functional/pytorch.py +1 -1
  119. doctr/transforms/modules/base.py +248 -83
  120. doctr/transforms/modules/pytorch.py +213 -74
  121. doctr/utils/common_types.py +22 -2
  122. doctr/utils/data.py +5 -4
  123. doctr/utils/fonts.py +56 -17
  124. doctr/utils/geometry.py +136 -19
  125. doctr/utils/metrics.py +351 -19
  126. doctr/utils/multithreading.py +6 -3
  127. doctr/utils/reconstitution.py +697 -133
  128. doctr/utils/repr.py +1 -1
  129. doctr/utils/visualization.py +63 -4
  130. doctr/version.py +1 -1
  131. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/METADATA +73 -26
  132. python_doctr-1.1.0.dist-info/RECORD +179 -0
  133. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
  134. python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
  135. python_doctr-1.0.0.dist-info/RECORD +0 -149
  136. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
  137. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
  138. {python_doctr-1.0.0.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
@@ -0,0 +1,215 @@
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 torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+ from doctr.models.modules import DropPath
11
+
12
+ __all__ = ["PatchEmbed", "MLP", "AttentionWithCAE", "WindowedCAETransformerBlock"]
13
+
14
+
15
+ class PatchEmbed(nn.Module):
16
+ """Simple 2D convolutional patch embedding layer for ViT Det
17
+
18
+ Args:
19
+ kernel_size: kernel size of the projection layer.
20
+ stride: stride of the projection layer.
21
+ padding: padding size of the projection layer.
22
+ in_chans: Number of input image channels.
23
+ embed_dim: embed_dim (int): Patch embedding dimension.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ kernel_size: tuple[int, int] = (16, 16),
29
+ stride: tuple[int, int] = (16, 16),
30
+ padding: tuple[int, int] = (0, 0),
31
+ in_chans: int = 3,
32
+ embed_dim: int = 768,
33
+ ):
34
+ super().__init__()
35
+
36
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding)
37
+
38
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
39
+ # B C H W -> B H W C
40
+ return self.proj(x).permute(0, 2, 3, 1)
41
+
42
+
43
+ class MLP(nn.Module):
44
+ """Simple Multilayer Perceptron (MLP)
45
+
46
+ Args:
47
+ in_features: number of input features
48
+ hidden_features: number of hidden features (default: in_features)
49
+ out_features: number of output features (default: in_features)
50
+ act_layer: activation layer (default: nn.GELU)
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ in_features: int,
56
+ hidden_features: int | None = None,
57
+ out_features: int | None = None,
58
+ act_layer=nn.GELU,
59
+ ):
60
+ super().__init__()
61
+
62
+ hidden_features = hidden_features or in_features
63
+ out_features = out_features or in_features
64
+
65
+ self.net = nn.Sequential(
66
+ nn.Linear(in_features, hidden_features),
67
+ act_layer(),
68
+ nn.Linear(hidden_features, out_features),
69
+ )
70
+
71
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
72
+ return self.net(x)
73
+
74
+
75
+ class AttentionWithCAE(nn.Module):
76
+ """Multi-head Attention block with CAE bias construction.
77
+
78
+ Args:
79
+ dim: Number of input channels.
80
+ num_heads: Number of attention heads.
81
+ qkv_bias: If True, add a learnable bias to query, key, value.
82
+ use_cae: If True, use CAE bias construction (separate q and v bias).
83
+ """
84
+
85
+ def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = True, use_cae: bool = False):
86
+ super().__init__()
87
+
88
+ self.num_heads = num_heads
89
+ self.head_dim = dim // num_heads
90
+ self.scale = self.head_dim**-0.5
91
+ self.use_cae = use_cae
92
+
93
+ self.qkv = nn.Linear(dim, dim * 3, bias=(qkv_bias and not use_cae))
94
+
95
+ # CAE bias
96
+ if use_cae:
97
+ self.q_bias = nn.Parameter(torch.zeros(dim))
98
+ self.v_bias = nn.Parameter(torch.zeros(dim))
99
+
100
+ self.proj = nn.Linear(dim, dim)
101
+
102
+ def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
103
+ B, N, C = x.shape
104
+
105
+ # QKV projection
106
+ if self.use_cae:
107
+ zeros = torch.zeros_like(self.v_bias, requires_grad=False)
108
+ qkv_bias = torch.cat([self.q_bias, zeros, self.v_bias])
109
+ qkv = F.linear(x, weight=self.qkv.weight, bias=qkv_bias)
110
+ else: # pragma: no cover
111
+ qkv = self.qkv(x)
112
+
113
+ # Reshape to multi-head
114
+ qkv = qkv.view(B, N, 3, self.num_heads, self.head_dim)
115
+ q, k, v = qkv.permute(2, 0, 3, 1, 4)
116
+
117
+ # Attention
118
+ attn = (q * self.scale) @ k.transpose(-2, -1)
119
+
120
+ if mask is not None:
121
+ attn = attn.masked_fill(mask.view(B, 1, 1, N).expand_as(attn), float("-inf"))
122
+
123
+ attn = attn.softmax(dim=-1)
124
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
125
+ return self.proj(x)
126
+
127
+
128
+ class WindowedCAETransformerBlock(nn.Module):
129
+ """Transformer blocks with support of window attention and residual propagation blocks
130
+
131
+ Args:
132
+ dim (int): Number of input channels.
133
+ num_heads (int): Number of attention heads in each ViT block.
134
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
135
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
136
+ drop_prob (float): Stochastic depth rate.
137
+ norm_layer (nn.Module): Normalization layer.
138
+ act_layer (nn.Module): Activation layer.
139
+ window (bool): If True, use window attention. Otherwise, use global attention.
140
+ use_cae (bool): If True, use CAE bias construction (separate q and v bias).
141
+ """
142
+
143
+ def __init__(
144
+ self,
145
+ dim,
146
+ num_heads,
147
+ mlp_ratio=4.0,
148
+ qkv_bias=True,
149
+ drop_prob=0.0,
150
+ norm_layer=nn.LayerNorm,
151
+ act_layer=nn.GELU,
152
+ window=False,
153
+ use_cae=False,
154
+ ):
155
+ super().__init__()
156
+
157
+ self.norm1 = norm_layer(dim)
158
+ self.norm2 = norm_layer(dim)
159
+
160
+ self.attn = AttentionWithCAE(
161
+ dim,
162
+ num_heads=num_heads,
163
+ qkv_bias=qkv_bias,
164
+ use_cae=use_cae,
165
+ )
166
+ self.mlp = MLP(
167
+ in_features=dim,
168
+ hidden_features=int(dim * mlp_ratio),
169
+ act_layer=act_layer,
170
+ )
171
+ self.drop_path = DropPath(drop_prob) if drop_prob > 0.0 else nn.Identity()
172
+
173
+ self.window = window
174
+ self.use_cae = use_cae
175
+
176
+ if use_cae:
177
+ self.gamma_1 = nn.Parameter(0.1 * torch.ones(dim), requires_grad=True)
178
+ self.gamma_2 = nn.Parameter(0.1 * torch.ones(dim), requires_grad=True)
179
+
180
+ def forward(self, x: torch.Tensor, mask: torch.Tensor | None = None) -> torch.Tensor:
181
+ B, HW, C = x.shape
182
+ shortcut = x
183
+
184
+ x = self.norm1(x)
185
+ mask_r = mask
186
+
187
+ # Window partitioning logic
188
+ if not self.window:
189
+ x = x.reshape(B // 16, 16 * HW, C)
190
+ shortcut_r = shortcut.reshape(B // 16, 16 * HW, C)
191
+
192
+ if mask is not None: # pragma: no cover
193
+ mask_r = mask.reshape(B // 16, 16 * HW)
194
+ else:
195
+ mask_r = None
196
+ else:
197
+ shortcut_r = shortcut
198
+
199
+ # Attention
200
+ attn_out = self.attn(x, mask_r)
201
+
202
+ if self.use_cae:
203
+ attn_out = self.gamma_1 * attn_out
204
+
205
+ x = shortcut_r + self.drop_path(attn_out)
206
+
207
+ # Reshape back if needed
208
+ if not self.window:
209
+ x = x.reshape(B, HW, C)
210
+ if mask is not None: # pragma: no cover
211
+ mask = mask.reshape(B, HW)
212
+
213
+ x = x + self.drop_path((self.gamma_2 * self.mlp(self.norm2(x))) if self.use_cae else self.mlp(self.norm2(x)))
214
+
215
+ return x
@@ -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
+ )
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
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.
@@ -32,6 +32,9 @@ 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",
35
38
  ]
36
39
 
37
40
  ORIENTATION_ARCHS: list[str] = ["mobilenet_v3_small_crop_orientation", "mobilenet_v3_small_page_orientation"]
doctr/models/core.py CHANGED
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
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.
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
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.
@@ -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
@@ -1,4 +1,4 @@
1
- # Copyright (C) 2021-2025, Mindee.
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.