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