python-doctr 1.0.1__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 (121) hide show
  1. doctr/cli/__init__.py +0 -0
  2. doctr/cli/main.py +506 -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 +2 -1
  9. doctr/datasets/doc_artefacts.py +2 -1
  10. doctr/datasets/funsd.py +2 -1
  11. doctr/datasets/generator/base.py +5 -4
  12. doctr/datasets/generator/pytorch.py +4 -5
  13. doctr/datasets/ic03.py +3 -2
  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 +123 -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 +2 -1
  23. doctr/datasets/sroie.py +2 -1
  24. doctr/datasets/svhn.py +2 -1
  25. doctr/datasets/svt.py +3 -2
  26. doctr/datasets/synthtext.py +2 -1
  27. doctr/datasets/table_structure.py +97 -0
  28. doctr/datasets/utils.py +14 -5
  29. doctr/datasets/vocabs.py +2 -0
  30. doctr/datasets/wildreceipt.py +4 -2
  31. doctr/file_utils.py +3 -1
  32. doctr/io/__init__.py +1 -0
  33. doctr/io/elements.py +252 -260
  34. doctr/io/exporters.py +1275 -0
  35. doctr/io/image/base.py +3 -2
  36. doctr/io/image/pytorch.py +5 -3
  37. doctr/models/__init__.py +2 -0
  38. doctr/models/_utils.py +56 -8
  39. doctr/models/builder.py +532 -61
  40. doctr/models/classification/__init__.py +2 -0
  41. doctr/models/classification/magc_resnet/pytorch.py +1 -1
  42. doctr/models/classification/mobilenet/pytorch.py +6 -6
  43. doctr/models/classification/predictor/pytorch.py +6 -2
  44. doctr/models/classification/resnet/pytorch.py +5 -5
  45. doctr/models/classification/starnet/__init__.py +1 -0
  46. doctr/models/classification/starnet/pytorch.py +202 -0
  47. doctr/models/classification/textnet/pytorch.py +6 -5
  48. doctr/models/classification/vgg/pytorch.py +3 -2
  49. doctr/models/classification/vip/layers/pytorch.py +4 -4
  50. doctr/models/classification/vip/pytorch.py +4 -4
  51. doctr/models/classification/vit/pytorch.py +3 -3
  52. doctr/models/classification/vit_det/__init__.py +1 -0
  53. doctr/models/classification/vit_det/layers/__init__.py +1 -0
  54. doctr/models/classification/vit_det/layers/pytorch.py +215 -0
  55. doctr/models/classification/vit_det/pytorch.py +346 -0
  56. doctr/models/classification/zoo.py +3 -0
  57. doctr/models/detection/_utils/base.py +23 -7
  58. doctr/models/detection/core.py +33 -18
  59. doctr/models/detection/differentiable_binarization/base.py +6 -4
  60. doctr/models/detection/differentiable_binarization/pytorch.py +3 -3
  61. doctr/models/detection/fast/base.py +5 -1
  62. doctr/models/detection/fast/pytorch.py +3 -3
  63. doctr/models/detection/linknet/base.py +5 -1
  64. doctr/models/detection/linknet/pytorch.py +3 -3
  65. doctr/models/detection/predictor/pytorch.py +3 -2
  66. doctr/models/detection/zoo.py +2 -2
  67. doctr/models/factory/hub.py +56 -41
  68. doctr/models/kie_predictor/base.py +16 -1
  69. doctr/models/kie_predictor/pytorch.py +41 -10
  70. doctr/models/layout/__init__.py +2 -0
  71. doctr/models/layout/lw_detr/__init__.py +1 -0
  72. doctr/models/layout/lw_detr/base.py +309 -0
  73. doctr/models/layout/lw_detr/layers/__init__.py +1 -0
  74. doctr/models/layout/lw_detr/layers/pytorch.py +785 -0
  75. doctr/models/layout/lw_detr/pytorch.py +838 -0
  76. doctr/models/layout/predictor/__init__.py +1 -0
  77. doctr/models/layout/predictor/pytorch.py +82 -0
  78. doctr/models/layout/zoo.py +90 -0
  79. doctr/models/modules/layers/pytorch.py +139 -3
  80. doctr/models/predictor/base.py +137 -15
  81. doctr/models/predictor/pytorch.py +150 -8
  82. doctr/models/preprocessor/pytorch.py +77 -22
  83. doctr/models/reading_order/__init__.py +1 -0
  84. doctr/models/reading_order/base.py +667 -0
  85. doctr/models/recognition/crnn/pytorch.py +5 -7
  86. doctr/models/recognition/master/pytorch.py +6 -7
  87. doctr/models/recognition/parseq/pytorch.py +4 -4
  88. doctr/models/recognition/predictor/pytorch.py +1 -1
  89. doctr/models/recognition/sar/pytorch.py +1 -1
  90. doctr/models/recognition/utils.py +8 -10
  91. doctr/models/recognition/viptr/pytorch.py +3 -5
  92. doctr/models/recognition/vitstr/pytorch.py +5 -5
  93. doctr/models/recognition/zoo.py +5 -6
  94. doctr/models/table_structure/__init__.py +2 -0
  95. doctr/models/table_structure/predictor/__init__.py +1 -0
  96. doctr/models/table_structure/predictor/pytorch.py +80 -0
  97. doctr/models/table_structure/tablecenternet/__init__.py +2 -0
  98. doctr/models/table_structure/tablecenternet/base.py +485 -0
  99. doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
  100. doctr/models/table_structure/zoo.py +82 -0
  101. doctr/models/utils/pytorch.py +314 -15
  102. doctr/models/zoo.py +90 -2
  103. doctr/transforms/modules/base.py +247 -82
  104. doctr/transforms/modules/pytorch.py +212 -73
  105. doctr/utils/common_types.py +21 -1
  106. doctr/utils/data.py +4 -2
  107. doctr/utils/fonts.py +55 -16
  108. doctr/utils/geometry.py +135 -18
  109. doctr/utils/metrics.py +350 -18
  110. doctr/utils/multithreading.py +5 -2
  111. doctr/utils/reconstitution.py +696 -132
  112. doctr/utils/visualization.py +62 -3
  113. doctr/version.py +1 -1
  114. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/METADATA +67 -27
  115. python_doctr-1.1.0.dist-info/RECORD +179 -0
  116. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
  117. python_doctr-1.1.0.dist-info/entry_points.txt +2 -0
  118. python_doctr-1.0.1.dist-info/RECORD +0 -149
  119. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/licenses/LICENSE +0 -0
  120. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
  121. {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
@@ -0,0 +1,522 @@
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
+ # Credits: architecture and loss ported from https://github.com/dreamy-xay/TableCenterNet
7
+
8
+ from collections.abc import Callable
9
+ from typing import Any
10
+
11
+ import numpy as np
12
+ import torch
13
+ from torch import nn
14
+ from torch.nn import functional as F
15
+ from torchvision.models._utils import IntermediateLayerGetter
16
+
17
+ from ....models.classification import starnet_s3
18
+ from ...modules.layers.pytorch import DCNv2
19
+ from ...utils import _bf16_to_float32, load_pretrained_params
20
+ from .base import TableCenterNetPostProcessor, _TableCenterNet
21
+
22
+ __all__ = ["TableCenterNet", "tablecenternet"]
23
+
24
+ default_cfgs: dict[str, dict[str, Any]] = {
25
+ "tablecenternet": {
26
+ "input_shape": (3, 1024, 1024),
27
+ "mean": (0.798, 0.785, 0.772),
28
+ "std": (0.264, 0.2749, 0.287),
29
+ "url": "https://github.com/mindee/doctr/releases/download/v1.0.1/tablecenternet-ea5b30a3.pt",
30
+ },
31
+ }
32
+
33
+ # Helper functions
34
+
35
+
36
+ def _gather_feat(feat: torch.Tensor, ind: torch.Tensor) -> torch.Tensor:
37
+ """Gather features at specific indices."""
38
+ dim = feat.size(2)
39
+ ind = ind.unsqueeze(2).expand(ind.size(0), ind.size(1), dim)
40
+ return feat.gather(1, ind)
41
+
42
+
43
+ def _transpose_and_gather_feat(feat: torch.Tensor, ind: torch.Tensor) -> torch.Tensor:
44
+ """Transpose and gather features at specific indices."""
45
+ feat = feat.permute(0, 2, 3, 1).contiguous()
46
+ feat = feat.view(feat.size(0), -1, feat.size(3))
47
+ return _gather_feat(feat, ind)
48
+
49
+
50
+ # Layers
51
+
52
+
53
+ class DeformConv(nn.Module):
54
+ """A deformable convolution layer, as described in `<https://arxiv.org/abs/1703.06211>`_.
55
+
56
+ Args:
57
+ chi: number of input channels
58
+ cho: number of output channels
59
+ """
60
+
61
+ def __init__(self, chi: int, cho: int):
62
+ super().__init__()
63
+ self.actf = nn.Sequential(nn.BatchNorm2d(cho, momentum=0.1), nn.ReLU(inplace=True))
64
+ self.conv = DCNv2(chi, cho, kernel_size=3, stride=1, padding=1)
65
+
66
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
67
+ return self.actf(self.conv(x))
68
+
69
+
70
+ class IDAUp(nn.Module):
71
+ """Iterative Deep Aggregation for Upsampling, as described in `<https://arxiv.org/abs/1707.06484>`_.
72
+
73
+ Args:
74
+ o: number of output channels
75
+ channels: list of number of channels for each input feature map
76
+ up_f: list of upsampling factors for each input feature map
77
+ """
78
+
79
+ def __init__(self, o: int, channels: list[int], up_f: list[int]):
80
+ super().__init__()
81
+ for i in range(1, len(channels)):
82
+ c, f = channels[i], int(up_f[i])
83
+ setattr(self, "proj_" + str(i), DeformConv(c, o))
84
+ setattr(self, "node_" + str(i), DeformConv(o, o))
85
+ up = nn.ConvTranspose2d(o, o, f * 2, stride=f, padding=f // 2, output_padding=0, groups=o, bias=False)
86
+ setattr(self, "up_" + str(i), up)
87
+
88
+ def forward(self, layers: list[torch.Tensor], startp: int, endp: int) -> None:
89
+ for i in range(startp + 1, endp):
90
+ upsample = getattr(self, "up_" + str(i - startp))
91
+ project = getattr(self, "proj_" + str(i - startp))
92
+ layers[i] = upsample(project(layers[i]))
93
+ node = getattr(self, "node_" + str(i - startp))
94
+ layers[i] = node(layers[i - 1] + layers[i])
95
+
96
+
97
+ class DLAUp(nn.Module):
98
+ """Deep Layer Aggregation for Upsampling, as described in `<https://arxiv.org/abs/1707.06484>`_.
99
+
100
+ Args:
101
+ startp: index of the first backbone map fed to the decoder
102
+ channels: list of number of channels for each input feature map
103
+ scales: list of upsampling factors for each input feature map
104
+ in_channels: list of number of input channels for each input feature map (optional)
105
+ """
106
+
107
+ def __init__(self, startp: int, channels: list[int], scales: list[int], in_channels: list[int] | None = None):
108
+ super().__init__()
109
+ self.startp = startp
110
+ if in_channels is None:
111
+ in_channels = channels
112
+ self.channels = channels
113
+ channels = list(channels)
114
+ np_scales = np.array(scales, dtype=int)
115
+ for i in range(len(channels) - 1):
116
+ j = -i - 2
117
+ setattr(self, f"ida_{i}", IDAUp(channels[j], in_channels[j:], (np_scales[j:] // np_scales[j]).tolist()))
118
+ np_scales[j + 1 :] = np_scales[j]
119
+ in_channels[j + 1 :] = [channels[j] for _ in channels[j + 1 :]]
120
+
121
+ def forward(self, layers: list[torch.Tensor]) -> list[torch.Tensor]:
122
+ out = [layers[-1]]
123
+ for i in range(len(layers) - self.startp - 1):
124
+ ida = getattr(self, f"ida_{i}")
125
+ ida(layers, len(layers) - i - 2, len(layers))
126
+ out.insert(0, layers[-1])
127
+ return out
128
+
129
+
130
+ # Model
131
+
132
+
133
+ class TableCenterNet(nn.Module, _TableCenterNet):
134
+ """TableCenterNet for table-structure recognition, as described in the official implementation
135
+ `<https://github.com/dreamy-xay/TableCenterNet>`_.
136
+
137
+ A StarNet backbone feeds a deformable-convolution DLA decoder, followed by six dense heads
138
+ (`hm`, `reg`, `ct2cn`, `cn2ct`, `lc`, `sp`) describing cell centers, corners and their
139
+ logical coordinates.
140
+
141
+ Args:
142
+ feat_extractor: the StarNet backbone serving as feature extractor (returns the stem + 4 stage maps)
143
+ heads: mapping from head name to its number of output channels
144
+ head_conv: number of channels in the hidden layer of each head
145
+ first_level: index of the first backbone map fed to the decoder
146
+ last_level: index (exclusive) of the last backbone map fed to the decoder
147
+ center_thresh: minimum score for a cell center to be kept
148
+ corner_thresh: minimum score for a corner to be used during relocation
149
+ center_k: maximum number of cell centers
150
+ corner_k: maximum number of corners
151
+ not_relocate: if True, skip the corner-relocation step
152
+ assume_straight_pages: if True, the predictor will fit straight boxes to the cells
153
+ exportable: onnx exportable returns only the raw head maps
154
+ cfg: the configuration dict of the model
155
+ """
156
+
157
+ def __init__(
158
+ self,
159
+ feat_extractor: IntermediateLayerGetter,
160
+ heads: dict[str, int] = {"hm": 2, "reg": 2, "ct2cn": 8, "cn2ct": 8, "lc": 2, "sp": 2},
161
+ head_conv: int = 256,
162
+ first_level: int = 1,
163
+ last_level: int = 4,
164
+ center_thresh: float = 0.3,
165
+ corner_thresh: float = 0.3,
166
+ center_k: int = 3000,
167
+ corner_k: int = 5000,
168
+ not_relocate: bool = False,
169
+ max_objects: int = 300,
170
+ max_corners: int = 1200,
171
+ assume_straight_pages: bool = True,
172
+ exportable: bool = False,
173
+ cfg: dict[str, Any] | None = None,
174
+ ) -> None:
175
+ super().__init__()
176
+ self.heads = heads
177
+ self.exportable = exportable
178
+ self.assume_straight_pages = assume_straight_pages
179
+ self.cfg = cfg
180
+ self.first_level, self.last_level = first_level, last_level
181
+ self.center_k, self.corner_k = center_k, corner_k
182
+ self.max_objects, self.max_corners = max_objects, max_corners
183
+
184
+ self.feat_extractor = feat_extractor
185
+ # Identify the number of channels for the decoder initialization
186
+ _is_training = self.feat_extractor.training
187
+ self.feat_extractor = self.feat_extractor.eval()
188
+ with torch.no_grad():
189
+ out = self.feat_extractor(torch.zeros((1, 3, 256, 256)))
190
+ channels = [v.shape[1] for v in out.values()]
191
+ if _is_training:
192
+ self.feat_extractor = self.feat_extractor.train()
193
+
194
+ scales = [2**i for i in range(len(channels[first_level:]))]
195
+ self.dla_up = DLAUp(first_level, channels[first_level:], scales)
196
+ out_channel = channels[first_level]
197
+ self.ida_up = IDAUp(
198
+ out_channel, channels[first_level:last_level], [2**i for i in range(last_level - first_level)]
199
+ )
200
+ for head, out_ch in self.heads.items():
201
+ fc = nn.Sequential(
202
+ nn.Conv2d(channels[first_level], head_conv, 3, padding=1, bias=True),
203
+ nn.ReLU(inplace=True),
204
+ nn.Conv2d(head_conv, out_ch, 1, stride=1, padding=0, bias=True),
205
+ )
206
+ # Reference head initialisation: detection-style bias for heatmaps, zeroed bias otherwise
207
+ final = fc[2]
208
+ if isinstance(final, nn.Conv2d) and final.bias is not None:
209
+ nn.init.constant_(final.bias, -2.19 if "hm" in head else 0.0)
210
+ self.__setattr__(head, fc)
211
+
212
+ self.postprocessor = TableCenterNetPostProcessor(
213
+ center_thresh=center_thresh,
214
+ corner_thresh=corner_thresh,
215
+ not_relocate=not_relocate,
216
+ assume_straight_pages=self.assume_straight_pages,
217
+ )
218
+
219
+ def from_pretrained(self, path_or_url: str, **kwargs: Any) -> None:
220
+ """Load pretrained parameters onto the model
221
+
222
+ Args:
223
+ path_or_url: the path or URL to the model parameters (checkpoint)
224
+ **kwargs: additional arguments to be passed to `doctr.models.utils.load_pretrained_params`
225
+ """
226
+ load_pretrained_params(self, path_or_url, **kwargs)
227
+
228
+ def _polygons_decode(self, heatmap: torch.Tensor, vec: torch.Tensor, reg: torch.Tensor, k: int):
229
+ """Decode key-points (cell centers or corners) into the four points of a quadrilateral."""
230
+ batch = heatmap.size(0)
231
+ # NMS on heatmaps
232
+ pad = (3 - 1) // 2
233
+ hmax = F.max_pool2d(heatmap, (3, 3), stride=1, padding=pad)
234
+ heatmap = heatmap * (hmax == heatmap).float()
235
+ # Top-K key-points
236
+ batch, cat, height, width = heatmap.size()
237
+ k = min(k, height * width) # never request more points than there are locations
238
+ topk_scores, topk_inds = torch.topk(heatmap.view(batch, cat, -1), k)
239
+ topk_inds = topk_inds % (height * width)
240
+ topk_ys = (topk_inds // width).int().float()
241
+ topk_xs = (topk_inds % width).int().float()
242
+ scores, topk_ind = torch.topk(topk_scores.view(batch, -1), k)
243
+ indexes = _gather_feat(topk_inds.view(batch, -1, 1), topk_ind).view(batch, k)
244
+ ys = _gather_feat(topk_ys.view(batch, -1, 1), topk_ind).view(batch, k)
245
+ xs = _gather_feat(topk_xs.view(batch, -1, 1), topk_ind).view(batch, k)
246
+
247
+ scores = scores.view(batch, k, 1)
248
+ offset = _transpose_and_gather_feat(reg, indexes)
249
+ xs = xs.view(batch, k, 1) + offset[:, :, 0:1]
250
+ ys = ys.view(batch, k, 1) + offset[:, :, 1:2]
251
+ v = _transpose_and_gather_feat(vec, indexes)
252
+ polygons = torch.cat(
253
+ [
254
+ xs - v[..., 0:1],
255
+ ys - v[..., 1:2],
256
+ xs - v[..., 2:3],
257
+ ys - v[..., 3:4],
258
+ xs - v[..., 4:5],
259
+ ys - v[..., 5:6],
260
+ xs - v[..., 6:7],
261
+ ys - v[..., 7:8],
262
+ ],
263
+ dim=2,
264
+ )
265
+ return scores, indexes, xs, ys, polygons
266
+
267
+ def _forward_heads(self, x: torch.Tensor) -> dict[str, torch.Tensor]:
268
+ """Run the model and return the raw head maps."""
269
+ feats = self.feat_extractor(x)
270
+ feats = [feats[str(idx)] for idx in range(len(feats))]
271
+ layers = self.dla_up(feats)
272
+ y = [layers[i].clone() for i in range(self.last_level - self.first_level)]
273
+ self.ida_up(y, 0, len(y))
274
+ return {head: self.__getattr__(head)(y[-1]) for head in self.heads} # type: ignore[operator]
275
+
276
+ @torch.compiler.disable
277
+ def _decode(self, heads: dict[str, torch.Tensor]) -> dict[str, Any]:
278
+ """Decode the raw head maps into cell polygons, scores, logical coordinates and corner points."""
279
+ hm = heads["hm"].sigmoid()
280
+ reg = heads["reg"]
281
+ c_scores, c_ind, _, _, c_poly = self._polygons_decode(hm[:, 0:1], heads["ct2cn"], reg, self.center_k)
282
+ k_scores, k_ind, k_xs, k_ys, k_poly = self._polygons_decode(hm[:, 1:2], heads["cn2ct"], reg, self.corner_k)
283
+ spans = _transpose_and_gather_feat(heads["sp"], c_ind)
284
+ corner_logics = _transpose_and_gather_feat(heads["lc"], k_ind)
285
+ feat_h, feat_w = hm.shape[2], hm.shape[3]
286
+
287
+ def _np(t: torch.Tensor) -> np.ndarray:
288
+ # Cast to float32 first: relevant under autocast/AMP
289
+ return t.detach().float().cpu().numpy()
290
+
291
+ return {
292
+ "center_polygons": _np(c_poly),
293
+ "center_scores": _np(c_scores.squeeze(-1)),
294
+ "center_spans": _np(spans),
295
+ "corner_polygons": _np(k_poly),
296
+ "corner_scores": _np(k_scores.squeeze(-1)),
297
+ "corner_points": _np(torch.cat([k_xs, k_ys], dim=2)),
298
+ "corner_logics": _np(corner_logics),
299
+ "lc": _np(heads["lc"]),
300
+ "feat_size": (feat_h, feat_w),
301
+ }
302
+
303
+ def forward(
304
+ self,
305
+ x: torch.Tensor,
306
+ target: list[dict[str, np.ndarray]] | None = None,
307
+ return_model_output: bool = False,
308
+ return_preds: bool = False,
309
+ ) -> dict[str, Any]:
310
+ heads_out = self._forward_heads(x)
311
+
312
+ heads_out = {head: _bf16_to_float32(heads_out[head]) for head in self.heads} # cast to float32 (AMP safe-guard)
313
+
314
+ out: dict[str, Any] = {}
315
+
316
+ if self.exportable:
317
+ return heads_out
318
+
319
+ if return_model_output:
320
+ # Cast to float32 (the heads can be bfloat16/float16 under autocast)
321
+ out["out_map"] = heads_out
322
+
323
+ if target is None or return_preds:
324
+ # Disable for torch.compile compatibility
325
+ @torch.compiler.disable
326
+ def _postprocess(heads_out):
327
+ return self.postprocessor(self._decode(heads_out))
328
+
329
+ out["preds"] = _postprocess(heads_out)
330
+
331
+ if target is not None:
332
+ # Disable for torch.compile compatibility (the target rendering relies on numpy/scipy)
333
+ @torch.compiler.disable
334
+ def _compute_loss(heads_out, target):
335
+ return self.compute_loss(heads_out, target)
336
+
337
+ out["loss"] = _compute_loss(heads_out, target)
338
+
339
+ return out
340
+
341
+ def compute_loss(
342
+ self,
343
+ output: dict[str, torch.Tensor],
344
+ target: list[dict[str, np.ndarray]],
345
+ ) -> torch.Tensor:
346
+ """Compute the multi-task TableCenterNet loss.
347
+
348
+ Args:
349
+ output: the raw head maps returned by the model
350
+ target: one `{"cells": (N, 4, 2) relative polygons, "logic": (N, 4)}` dict per image
351
+
352
+ Returns:
353
+ the scalar training loss
354
+ """
355
+ out_h, out_w = int(output["hm"].shape[-2]), int(output["hm"].shape[-1])
356
+ # Render the dense targets (numpy/scipy) from the relative cell annotations
357
+ dense_np = self.build_target(target, (out_h, out_w))
358
+ device = output["hm"].device
359
+ dense = {k: torch.from_numpy(v).to(device) for k, v in dense_np.items()}
360
+ # AMP safe-guard: compute the loss in float32
361
+ output = {k: v.float() for k, v in output.items()}
362
+ return self._loss_from_dense(output, dense)
363
+
364
+ def _loss_from_dense(self, output: dict[str, torch.Tensor], target: dict[str, torch.Tensor]) -> torch.Tensor:
365
+ """Compute the multi-task TableCenterNet loss.
366
+
367
+ Args:
368
+ output: the raw head maps returned by the model
369
+ target: dense targets matching the reference schema (
370
+ keys:
371
+ hm, reg, reg_ind, reg_mask, ct_ind, ct_mask,
372
+ ct2cn, cn_ind, cn_mask, cn2ct, ct_cn_ind,
373
+ lc, lc_mask, lc_ind, lc_span
374
+ )
375
+
376
+ Returns:
377
+ the scalar training loss
378
+ """
379
+ eps = 1e-4
380
+ hm = torch.clamp(output["hm"].sigmoid(), min=eps, max=1 - eps)
381
+
382
+ # Focal loss on the center/corner heat-maps
383
+ gt = target["hm"]
384
+ pos_inds, neg_inds = gt.eq(1).float(), gt.lt(1).float()
385
+ neg_weights = torch.pow(1 - gt, 4)
386
+ pos_loss = (torch.log(hm) * torch.pow(1 - hm, 2) * pos_inds).sum()
387
+ neg_loss = (torch.log(1 - hm) * torch.pow(hm, 2) * neg_weights * neg_inds).sum()
388
+ num_pos = pos_inds.sum()
389
+ hm_loss = -neg_loss if num_pos == 0 else -(pos_loss + neg_loss) / num_pos
390
+
391
+ # L1 on the sub-pixel offsets
392
+ reg_pred = _transpose_and_gather_feat(output["reg"], target["reg_ind"])
393
+ reg_mask = target["reg_mask"].unsqueeze(2).expand_as(reg_pred).float()
394
+ reg_loss = F.l1_loss(reg_pred * reg_mask, target["reg"] * reg_mask, reduction="sum") / (reg_mask.sum() + eps)
395
+
396
+ # Vector-pair loss (center<->corner offsets)
397
+ ct2cn_loss, cn2ct_loss, invalid_loss = self._vec_pair_loss(output, target, eps)
398
+
399
+ # Logical-coordinate + span loss
400
+ lc_coord_loss, span_diff_loss, span_loss = self._logic_coord_loss(output, target, eps)
401
+
402
+ return (
403
+ hm_loss + reg_loss + ct2cn_loss + (cn2ct_loss + invalid_loss) + (lc_coord_loss + span_diff_loss + span_loss)
404
+ )
405
+
406
+ @staticmethod
407
+ def _vec_pair_loss(output, target, eps):
408
+ ct2cn_pred = _transpose_and_gather_feat(output["ct2cn"], target["ct_ind"])
409
+ cn2ct_pred = _transpose_and_gather_feat(output["cn2ct"], target["cn_ind"])
410
+ cn2ct_pred_temp, cn2ct_gt_temp = cn2ct_pred, target["cn2ct"]
411
+ b, m, n = ct2cn_pred.size(0), ct2cn_pred.size(1), cn2ct_pred.size(1)
412
+
413
+ ct_cn_ind = target["ct_cn_ind"].unsqueeze(2).expand(b, 4 * m, 2)
414
+ cn2ct_pred = cn2ct_pred.view(b, 4 * n, 2).gather(1, ct_cn_ind).view(b, m, 8)
415
+ cn2ct_gt = target["cn2ct"].view(b, 4 * n, 2).gather(1, ct_cn_ind).view(b, m, 8)
416
+
417
+ ct_mask = target["ct_mask"].unsqueeze(2).expand_as(ct2cn_pred).float()
418
+ num_ct = ct_mask.sum() + eps
419
+ cn_mask = target["cn_mask"].unsqueeze(2).expand_as(cn2ct_pred_temp)
420
+
421
+ delta = (torch.abs(ct2cn_pred - target["ct2cn"]) + torch.abs(cn2ct_pred - cn2ct_gt)) / (
422
+ torch.abs(target["ct2cn"]) + eps
423
+ )
424
+ weight = torch.sin(1.570796 * torch.min(delta, torch.tensor(1.0, device=delta.device)))
425
+ ct2cn_loss = (
426
+ F.l1_loss(ct2cn_pred * ct_mask * weight, target["ct2cn"] * ct_mask * weight, reduction="sum") / num_ct
427
+ )
428
+ cn2ct_loss = F.l1_loss(cn2ct_pred * ct_mask * weight, cn2ct_gt * ct_mask * weight, reduction="sum") / num_ct
429
+
430
+ invalid_vec_mask = cn2ct_gt_temp == 0
431
+ invalid_vec_cn_mask = (invalid_vec_mask == cn_mask).float()
432
+ invalid_loss = F.l1_loss(
433
+ cn2ct_pred_temp * invalid_vec_cn_mask, cn2ct_gt_temp * invalid_vec_cn_mask, reduction="sum"
434
+ ) / (invalid_vec_cn_mask.sum() + eps)
435
+ return ct2cn_loss, 0.5 * cn2ct_loss, 0.2 * invalid_loss
436
+
437
+ @staticmethod
438
+ def _logic_coord_loss(output, target, eps):
439
+ coord, span = output["lc"], output["sp"]
440
+ b, num = target["lc_span"].size(0), target["lc_span"].size(1)
441
+
442
+ coords_pred = _transpose_and_gather_feat(coord, target["lc_ind"].view(b, num * 4)).view(b, num, 4, 2)
443
+ cols_pred, rows_pred = coords_pred[..., 0], coords_pred[..., 1]
444
+ span_pred = _transpose_and_gather_feat(span, target["ct_ind"])
445
+ span_mask = target["ct_mask"].unsqueeze(2).expand(b, num, 2).float()
446
+ num_span_mask = span_mask.sum() + eps
447
+
448
+ coord_gt, coord_mask = target["lc"], target["lc_mask"]
449
+ coord_weight = torch.square(1.0 - torch.abs(coord_gt - torch.round(coord_gt)))
450
+ coord_loss = F.l1_loss(
451
+ coord * coord_mask * coord_weight, coord_gt * coord_mask * coord_weight, reduction="sum"
452
+ ) / (coord_mask.sum() + eps)
453
+
454
+ col_span_diff_pred = cols_pred[..., [1, 2]] - cols_pred[..., [0, 3]]
455
+ row_span_diff_pred = rows_pred[..., [3, 2]] - rows_pred[..., [0, 1]]
456
+ col_span_pred = span_pred[..., 0].unsqueeze(2).expand(b, num, 2)
457
+ row_span_pred = span_pred[..., 1].unsqueeze(2).expand(b, num, 2)
458
+ col_span_gt = target["lc_span"][..., 0].unsqueeze(2).expand(b, num, 2)
459
+ row_span_gt = target["lc_span"][..., 1].unsqueeze(2).expand(b, num, 2)
460
+
461
+ def span_weight(out1, out2, tgt):
462
+ scaled = (torch.abs(out1 - tgt) + torch.abs(out2 - tgt)) * 5.0
463
+ delta = torch.min(scaled, torch.tensor(1.0, device=tgt.device))
464
+ return torch.sin(1.570796 * delta)
465
+
466
+ col_w = span_weight(col_span_pred, col_span_diff_pred, col_span_gt)
467
+ row_w = span_weight(row_span_pred, row_span_diff_pred, row_span_gt)
468
+ sp_weight = torch.stack([(col_w[..., 0] + col_w[..., 1]) / 2.0, (row_w[..., 0] + row_w[..., 1]) / 2.0], dim=-1)
469
+
470
+ col_span_diff_loss = (
471
+ F.l1_loss(col_span_diff_pred * span_mask * col_w, col_span_gt * span_mask * col_w, reduction="sum")
472
+ / num_span_mask
473
+ )
474
+ row_span_diff_loss = (
475
+ F.l1_loss(row_span_diff_pred * span_mask * row_w, row_span_gt * span_mask * row_w, reduction="sum")
476
+ / num_span_mask
477
+ )
478
+ span_diff_loss = col_span_diff_loss + row_span_diff_loss
479
+
480
+ span_loss = (
481
+ F.l1_loss(span_pred * span_mask * sp_weight, target["lc_span"] * span_mask * sp_weight, reduction="sum")
482
+ / num_span_mask
483
+ )
484
+ return coord_loss, span_diff_loss, span_loss
485
+
486
+
487
+ def _tablecenternet(
488
+ arch: str,
489
+ pretrained: bool,
490
+ backbone_fn: Callable[..., nn.Module],
491
+ pretrained_backbone: bool = True,
492
+ **kwargs: Any,
493
+ ) -> TableCenterNet:
494
+ pretrained_backbone = pretrained_backbone and not pretrained
495
+ backbone = backbone_fn(pretrained_backbone)
496
+ # 4 stages - all starnet variants
497
+ feat_extractor = IntermediateLayerGetter(backbone, {str(idx): str(idx) for idx in range(5)})
498
+
499
+ model = TableCenterNet(feat_extractor, cfg=default_cfgs[arch], **kwargs)
500
+ # Load pretrained parameters
501
+ if pretrained:
502
+ model.from_pretrained(default_cfgs[arch]["url"], ignore_keys=None)
503
+
504
+ return model
505
+
506
+
507
+ def tablecenternet(pretrained: bool = False, **kwargs: Any) -> TableCenterNet:
508
+ """TableCenterNet with a StarNet-S3 backbone, matching the official checkpoint.
509
+
510
+ >>> import torch
511
+ >>> from doctr.models import tablecenternet
512
+ >>> model = tablecenternet(pretrained=False)
513
+ >>> out = model(torch.rand((1, 3, 1024, 1024), dtype=torch.float32), return_preds=True)
514
+
515
+ Args:
516
+ pretrained: boolean, True if model is pretrained
517
+ **kwargs: keyword arguments of the TableCenterNet architecture
518
+
519
+ Returns:
520
+ A TableCenterNet model with a StarNet-S3 backbone
521
+ """
522
+ return _tablecenternet("tablecenternet", pretrained, starnet_s3, **kwargs)
@@ -0,0 +1,82 @@
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
+ from typing import Any
7
+
8
+ from doctr.models.utils import _CompiledModule
9
+
10
+ from .. import table_structure
11
+ from ..preprocessor import PreProcessor
12
+ from .predictor import TablePredictor
13
+
14
+ __all__ = ["table_predictor"]
15
+
16
+ ARCHS: list[str] = ["tablecenternet"]
17
+
18
+
19
+ def _predictor(arch: Any, pretrained: bool, assume_straight_pages: bool = False, **kwargs: Any) -> TablePredictor:
20
+ if isinstance(arch, str):
21
+ if arch not in ARCHS:
22
+ raise ValueError(f"unknown architecture '{arch}'")
23
+ _model = table_structure.__dict__[arch](pretrained=pretrained, assume_straight_pages=assume_straight_pages)
24
+ else:
25
+ allowed_archs = [table_structure.TableCenterNet, _CompiledModule]
26
+ if not isinstance(arch, tuple(allowed_archs)):
27
+ raise ValueError(f"unknown architecture: {type(arch)}")
28
+ _model = arch
29
+ _model.assume_straight_pages = assume_straight_pages # type: ignore[attr-defined]
30
+
31
+ kwargs.pop("pretrained_backbone", None)
32
+ kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
33
+ kwargs["std"] = kwargs.get("std", _model.cfg["std"])
34
+ kwargs["batch_size"] = kwargs.get("batch_size", 2)
35
+ kwargs.setdefault("preserve_aspect_ratio", True)
36
+ kwargs.setdefault("symmetric_pad", True)
37
+ predictor = TablePredictor(
38
+ PreProcessor(_model.cfg["input_shape"][1:], **kwargs),
39
+ _model,
40
+ )
41
+ return predictor
42
+
43
+
44
+ def table_predictor(
45
+ arch: Any = "tablecenternet",
46
+ pretrained: bool = False,
47
+ assume_straight_pages: bool = False,
48
+ preserve_aspect_ratio: bool = True,
49
+ symmetric_pad: bool = True,
50
+ batch_size: int = 2,
51
+ **kwargs: Any,
52
+ ) -> TablePredictor:
53
+ """Table structure recognition architecture.
54
+
55
+ >>> import numpy as np
56
+ >>> from doctr.models import table_predictor
57
+ >>> model = table_predictor(arch='tablecenternet', pretrained=True)
58
+ >>> input_page = (255 * np.random.rand(600, 800, 3)).astype(np.uint8)
59
+ >>> out = model([input_page])
60
+
61
+ Args:
62
+ arch: name of the architecture or model itself to use (e.g. 'tablecenternet')
63
+ pretrained: If True, returns a model pre-trained on a table structure recognition dataset
64
+ assume_straight_pages: if True, fit straight boxes to the detected cells
65
+ preserve_aspect_ratio: if True, pad the input document image to preserve the aspect ratio before
66
+ running the model on it
67
+ symmetric_pad: if True, pad the image symmetrically instead of padding at the bottom-right
68
+ batch_size: number of samples the model processes in parallel
69
+ **kwargs: optional keyword arguments passed to the architecture
70
+
71
+ Returns:
72
+ Table structure recognition predictor
73
+ """
74
+ return _predictor(
75
+ arch=arch,
76
+ pretrained=pretrained,
77
+ assume_straight_pages=assume_straight_pages,
78
+ preserve_aspect_ratio=preserve_aspect_ratio,
79
+ symmetric_pad=symmetric_pad,
80
+ batch_size=batch_size,
81
+ **kwargs,
82
+ )