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.
- doctr/cli/__init__.py +0 -0
- doctr/cli/main.py +506 -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 +2 -1
- doctr/datasets/doc_artefacts.py +2 -1
- doctr/datasets/funsd.py +2 -1
- doctr/datasets/generator/base.py +5 -4
- doctr/datasets/generator/pytorch.py +4 -5
- doctr/datasets/ic03.py +3 -2
- 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 +123 -0
- doctr/datasets/mjsynth.py +4 -2
- doctr/datasets/ocr.py +2 -1
- doctr/datasets/orientation.py +2 -1
- doctr/datasets/recognition.py +2 -1
- doctr/datasets/sroie.py +2 -1
- doctr/datasets/svhn.py +2 -1
- doctr/datasets/svt.py +3 -2
- doctr/datasets/synthtext.py +2 -1
- doctr/datasets/table_structure.py +97 -0
- doctr/datasets/utils.py +14 -5
- doctr/datasets/vocabs.py +2 -0
- doctr/datasets/wildreceipt.py +4 -2
- doctr/file_utils.py +3 -1
- doctr/io/__init__.py +1 -0
- doctr/io/elements.py +252 -260
- doctr/io/exporters.py +1275 -0
- doctr/io/image/base.py +3 -2
- doctr/io/image/pytorch.py +5 -3
- doctr/models/__init__.py +2 -0
- doctr/models/_utils.py +56 -8
- doctr/models/builder.py +532 -61
- doctr/models/classification/__init__.py +2 -0
- doctr/models/classification/magc_resnet/pytorch.py +1 -1
- doctr/models/classification/mobilenet/pytorch.py +6 -6
- doctr/models/classification/predictor/pytorch.py +6 -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 +3 -0
- doctr/models/detection/_utils/base.py +23 -7
- doctr/models/detection/core.py +33 -18
- doctr/models/detection/differentiable_binarization/base.py +6 -4
- doctr/models/detection/differentiable_binarization/pytorch.py +3 -3
- doctr/models/detection/fast/base.py +5 -1
- doctr/models/detection/fast/pytorch.py +3 -3
- doctr/models/detection/linknet/base.py +5 -1
- doctr/models/detection/linknet/pytorch.py +3 -3
- doctr/models/detection/predictor/pytorch.py +3 -2
- doctr/models/detection/zoo.py +2 -2
- doctr/models/factory/hub.py +56 -41
- doctr/models/kie_predictor/base.py +16 -1
- doctr/models/kie_predictor/pytorch.py +41 -10
- 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 +838 -0
- doctr/models/layout/predictor/__init__.py +1 -0
- doctr/models/layout/predictor/pytorch.py +82 -0
- doctr/models/layout/zoo.py +90 -0
- doctr/models/modules/layers/pytorch.py +139 -3
- doctr/models/predictor/base.py +137 -15
- doctr/models/predictor/pytorch.py +150 -8
- doctr/models/preprocessor/pytorch.py +77 -22
- doctr/models/reading_order/__init__.py +1 -0
- doctr/models/reading_order/base.py +667 -0
- doctr/models/recognition/crnn/pytorch.py +5 -7
- doctr/models/recognition/master/pytorch.py +6 -7
- doctr/models/recognition/parseq/pytorch.py +4 -4
- doctr/models/recognition/predictor/pytorch.py +1 -1
- doctr/models/recognition/sar/pytorch.py +1 -1
- doctr/models/recognition/utils.py +8 -10
- doctr/models/recognition/viptr/pytorch.py +3 -5
- doctr/models/recognition/vitstr/pytorch.py +5 -5
- doctr/models/recognition/zoo.py +5 -6
- doctr/models/table_structure/__init__.py +2 -0
- doctr/models/table_structure/predictor/__init__.py +1 -0
- doctr/models/table_structure/predictor/pytorch.py +80 -0
- doctr/models/table_structure/tablecenternet/__init__.py +2 -0
- doctr/models/table_structure/tablecenternet/base.py +485 -0
- doctr/models/table_structure/tablecenternet/pytorch.py +522 -0
- doctr/models/table_structure/zoo.py +82 -0
- doctr/models/utils/pytorch.py +314 -15
- doctr/models/zoo.py +90 -2
- doctr/transforms/modules/base.py +247 -82
- doctr/transforms/modules/pytorch.py +212 -73
- doctr/utils/common_types.py +21 -1
- doctr/utils/data.py +4 -2
- doctr/utils/fonts.py +55 -16
- doctr/utils/geometry.py +135 -18
- doctr/utils/metrics.py +350 -18
- doctr/utils/multithreading.py +5 -2
- doctr/utils/reconstitution.py +696 -132
- doctr/utils/visualization.py +62 -3
- doctr/version.py +1 -1
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/METADATA +67 -27
- python_doctr-1.1.0.dist-info/RECORD +179 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/WHEEL +1 -1
- python_doctr-1.1.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.1.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.0.1.dist-info → python_doctr-1.1.0.dist-info}/zip-safe +0 -0
|
@@ -73,10 +73,8 @@ class CTCPostProcessor(RecognitionPostProcessor):
|
|
|
73
73
|
probs = F.softmax(logits, dim=-1).max(dim=-1).values.min(dim=1).values
|
|
74
74
|
|
|
75
75
|
# collapse best path (using itertools.groupby), map to chars, join char list to string
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
for seq in torch.argmax(logits, dim=-1)
|
|
79
|
-
]
|
|
76
|
+
best_paths = torch.argmax(logits, dim=-1).detach().cpu().numpy()
|
|
77
|
+
words = [decode_sequence([k for k, _ in groupby(seq.tolist()) if k != blank], vocab) for seq in best_paths]
|
|
80
78
|
|
|
81
79
|
return list(zip(words, probs.tolist()))
|
|
82
80
|
|
|
@@ -279,7 +277,7 @@ def crnn_vgg16_bn(pretrained: bool = False, **kwargs: Any) -> CRNN:
|
|
|
279
277
|
>>> out = model(input_tensor)
|
|
280
278
|
|
|
281
279
|
Args:
|
|
282
|
-
pretrained
|
|
280
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
283
281
|
**kwargs: keyword arguments of the CRNN architecture
|
|
284
282
|
|
|
285
283
|
Returns:
|
|
@@ -299,7 +297,7 @@ def crnn_mobilenet_v3_small(pretrained: bool = False, **kwargs: Any) -> CRNN:
|
|
|
299
297
|
>>> out = model(input_tensor)
|
|
300
298
|
|
|
301
299
|
Args:
|
|
302
|
-
pretrained
|
|
300
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
303
301
|
**kwargs: keyword arguments of the CRNN architecture
|
|
304
302
|
|
|
305
303
|
Returns:
|
|
@@ -325,7 +323,7 @@ def crnn_mobilenet_v3_large(pretrained: bool = False, **kwargs: Any) -> CRNN:
|
|
|
325
323
|
>>> out = model(input_tensor)
|
|
326
324
|
|
|
327
325
|
Args:
|
|
328
|
-
pretrained
|
|
326
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
329
327
|
**kwargs: keyword arguments of the CRNN architecture
|
|
330
328
|
|
|
331
329
|
Returns:
|
|
@@ -247,14 +247,13 @@ class MASTER(_MASTER, nn.Module):
|
|
|
247
247
|
for i in range(self.max_length - 1):
|
|
248
248
|
source_mask, target_mask = self.make_source_and_target_mask(encoded, ys)
|
|
249
249
|
output = self.decoder(ys, encoded, source_mask, target_mask)
|
|
250
|
-
logits = self.linear(output)
|
|
251
|
-
prob = torch.softmax(logits, dim=-1)
|
|
252
|
-
next_token = torch.max(prob, dim=-1).indices
|
|
253
250
|
# update ys with the next token and ignore the first token (SOS)
|
|
254
|
-
ys[:, i + 1] =
|
|
251
|
+
ys[:, i + 1] = self.linear(output[:, i]).argmax(-1)
|
|
252
|
+
if (ys == self.vocab_size).any(dim=-1).all(): # every sequence has emitted EOS
|
|
253
|
+
break
|
|
255
254
|
|
|
256
255
|
# Shape (N, max_length, vocab_size + 1)
|
|
257
|
-
return
|
|
256
|
+
return self.linear(output)
|
|
258
257
|
|
|
259
258
|
|
|
260
259
|
class MASTERPostProcessor(_MASTERPostProcessor):
|
|
@@ -274,7 +273,7 @@ class MASTERPostProcessor(_MASTERPostProcessor):
|
|
|
274
273
|
# Manual decoding
|
|
275
274
|
word_values = [
|
|
276
275
|
"".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
|
|
277
|
-
for encoded_seq in out_idxs.cpu().numpy()
|
|
276
|
+
for encoded_seq in out_idxs.detach().cpu().numpy()
|
|
278
277
|
]
|
|
279
278
|
|
|
280
279
|
return list(zip(word_values, probs.numpy().clip(0, 1).tolist()))
|
|
@@ -325,7 +324,7 @@ def master(pretrained: bool = False, **kwargs: Any) -> MASTER:
|
|
|
325
324
|
>>> out = model(input_tensor)
|
|
326
325
|
|
|
327
326
|
Args:
|
|
328
|
-
pretrained
|
|
327
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
329
328
|
**kwargs: keywoard arguments passed to the MASTER architecture
|
|
330
329
|
|
|
331
330
|
Returns:
|
|
@@ -417,16 +417,16 @@ class PARSeqPostProcessor(_PARSeqPostProcessor):
|
|
|
417
417
|
) -> list[tuple[str, float]]:
|
|
418
418
|
# compute pred with argmax for attention models
|
|
419
419
|
out_idxs = logits.argmax(-1)
|
|
420
|
-
preds_prob = torch.softmax(logits, -1).max(dim=-1)[0]
|
|
420
|
+
preds_prob = torch.softmax(logits, -1).max(dim=-1)[0].detach().cpu().numpy()
|
|
421
421
|
|
|
422
422
|
# Manual decoding
|
|
423
423
|
word_values = [
|
|
424
424
|
"".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
|
|
425
|
-
for encoded_seq in out_idxs.cpu().numpy()
|
|
425
|
+
for encoded_seq in out_idxs.detach().cpu().numpy()
|
|
426
426
|
]
|
|
427
427
|
# compute probabilties for each word up to the EOS token
|
|
428
428
|
probs = [
|
|
429
|
-
preds_prob[i, : len(word)].clip(0, 1).mean()
|
|
429
|
+
float(preds_prob[i, : len(word)].clip(0, 1).mean()) if word else 0.0 for i, word in enumerate(word_values)
|
|
430
430
|
]
|
|
431
431
|
|
|
432
432
|
return list(zip(word_values, probs))
|
|
@@ -482,7 +482,7 @@ def parseq(pretrained: bool = False, **kwargs: Any) -> PARSeq:
|
|
|
482
482
|
>>> out = model(input_tensor)
|
|
483
483
|
|
|
484
484
|
Args:
|
|
485
|
-
pretrained
|
|
485
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
486
486
|
**kwargs: keyword arguments of the PARSeq architecture
|
|
487
487
|
|
|
488
488
|
Returns:
|
|
@@ -70,7 +70,7 @@ class RecognitionPredictor(nn.Module):
|
|
|
70
70
|
|
|
71
71
|
# Forward it
|
|
72
72
|
_params = next(self.model.parameters())
|
|
73
|
-
self.model, processed_batches = set_device_and_dtype(
|
|
73
|
+
self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
|
|
74
74
|
self.model, processed_batches, _params.device, _params.dtype
|
|
75
75
|
)
|
|
76
76
|
raw = [self.model(batch, return_preds=True, **kwargs)["preds"] for batch in processed_batches]
|
|
@@ -389,7 +389,7 @@ def sar_resnet31(pretrained: bool = False, **kwargs: Any) -> SAR:
|
|
|
389
389
|
>>> out = model(input_tensor)
|
|
390
390
|
|
|
391
391
|
Args:
|
|
392
|
-
pretrained
|
|
392
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
393
393
|
**kwargs: keyword arguments of the SAR architecture
|
|
394
394
|
|
|
395
395
|
Returns:
|
|
@@ -20,12 +20,11 @@ def merge_strings(a: str, b: str, overlap_ratio: float) -> str:
|
|
|
20
20
|
Returns:
|
|
21
21
|
A merged character sequence.
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
'abcdefgh'
|
|
23
|
+
>>> from doctr.models.recognition.utils import merge_strings
|
|
24
|
+
>>> merge_strings('abcd', 'cdefgh', 0.5)
|
|
25
|
+
'abcdefgh'
|
|
26
|
+
>>> merge_strings('abcdi', 'cdefgh', 0.5)
|
|
27
|
+
'abcdefgh'
|
|
29
28
|
"""
|
|
30
29
|
seq_len = min(len(a), len(b))
|
|
31
30
|
if seq_len <= 1: # One sequence is empty or will be after cropping in next step, return both to keep data
|
|
@@ -78,10 +77,9 @@ def merge_multi_strings(seq_list: list[str], overlap_ratio: float, last_overlap_
|
|
|
78
77
|
Returns:
|
|
79
78
|
A merged character sequence
|
|
80
79
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
'abcdefghijkl'
|
|
80
|
+
>>> from doctr.models.recognition.utils import merge_multi_strings
|
|
81
|
+
>>> merge_multi_strings(['abc', 'bcdef', 'difghi', 'aijkl'], 0.5, 0.1)
|
|
82
|
+
'abcdefghijkl'
|
|
85
83
|
"""
|
|
86
84
|
if not seq_list:
|
|
87
85
|
return ""
|
|
@@ -61,10 +61,8 @@ class VIPTRPostProcessor(RecognitionPostProcessor):
|
|
|
61
61
|
probs = F.softmax(logits, dim=-1).max(dim=-1).values.min(dim=1).values
|
|
62
62
|
|
|
63
63
|
# collapse best path (using itertools.groupby), map to chars, join char list to string
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
for seq in torch.argmax(logits, dim=-1)
|
|
67
|
-
]
|
|
64
|
+
best_paths = torch.argmax(logits, dim=-1).detach().cpu().numpy()
|
|
65
|
+
words = [decode_sequence([k for k, _ in groupby(seq.tolist()) if k != blank], vocab) for seq in best_paths]
|
|
68
66
|
|
|
69
67
|
return list(zip(words, probs.tolist()))
|
|
70
68
|
|
|
@@ -261,7 +259,7 @@ def viptr_tiny(pretrained: bool = False, **kwargs: Any) -> VIPTR:
|
|
|
261
259
|
>>> out = model(input_tensor)
|
|
262
260
|
|
|
263
261
|
Args:
|
|
264
|
-
pretrained
|
|
262
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
265
263
|
**kwargs: keyword arguments of the VIPTR architecture
|
|
266
264
|
|
|
267
265
|
Returns:
|
|
@@ -174,16 +174,16 @@ class ViTSTRPostProcessor(_ViTSTRPostProcessor):
|
|
|
174
174
|
) -> list[tuple[str, float]]:
|
|
175
175
|
# compute pred with argmax for attention models
|
|
176
176
|
out_idxs = logits.argmax(-1)
|
|
177
|
-
preds_prob = torch.softmax(logits, -1).max(dim=-1)[0]
|
|
177
|
+
preds_prob = torch.softmax(logits, -1).max(dim=-1)[0].detach().cpu().numpy()
|
|
178
178
|
|
|
179
179
|
# Manual decoding
|
|
180
180
|
word_values = [
|
|
181
181
|
"".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
|
|
182
|
-
for encoded_seq in out_idxs.cpu().numpy()
|
|
182
|
+
for encoded_seq in out_idxs.detach().cpu().numpy()
|
|
183
183
|
]
|
|
184
184
|
# compute probabilties for each word up to the EOS token
|
|
185
185
|
probs = [
|
|
186
|
-
preds_prob[i, : len(word)].clip(0, 1).mean()
|
|
186
|
+
float(preds_prob[i, : len(word)].clip(0, 1).mean()) if word else 0.0 for i, word in enumerate(word_values)
|
|
187
187
|
]
|
|
188
188
|
|
|
189
189
|
return list(zip(word_values, probs))
|
|
@@ -239,7 +239,7 @@ def vitstr_small(pretrained: bool = False, **kwargs: Any) -> ViTSTR:
|
|
|
239
239
|
>>> out = model(input_tensor)
|
|
240
240
|
|
|
241
241
|
Args:
|
|
242
|
-
pretrained
|
|
242
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
243
243
|
kwargs: keyword arguments of the ViTSTR architecture
|
|
244
244
|
|
|
245
245
|
Returns:
|
|
@@ -268,7 +268,7 @@ def vitstr_base(pretrained: bool = False, **kwargs: Any) -> ViTSTR:
|
|
|
268
268
|
>>> out = model(input_tensor)
|
|
269
269
|
|
|
270
270
|
Args:
|
|
271
|
-
pretrained
|
|
271
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
272
272
|
kwargs: keyword arguments of the ViTSTR architecture
|
|
273
273
|
|
|
274
274
|
Returns:
|
doctr/models/recognition/zoo.py
CHANGED
|
@@ -71,12 +71,11 @@ def recognition_predictor(
|
|
|
71
71
|
) -> RecognitionPredictor:
|
|
72
72
|
"""Text recognition architecture.
|
|
73
73
|
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
>>> out = model([input_page])
|
|
74
|
+
>>> import numpy as np
|
|
75
|
+
>>> from doctr.models import recognition_predictor
|
|
76
|
+
>>> model = recognition_predictor(pretrained=True)
|
|
77
|
+
>>> input_page = (255 * np.random.rand(32, 128, 3)).astype(np.uint8)
|
|
78
|
+
>>> out = model([input_page])
|
|
80
79
|
|
|
81
80
|
Args:
|
|
82
81
|
arch: name of the architecture or model itself to use (e.g. 'crnn_vgg16_bn')
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pytorch import *
|
|
@@ -0,0 +1,80 @@
|
|
|
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
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
from torch import nn
|
|
11
|
+
|
|
12
|
+
from doctr.models.detection._utils import _remove_padding
|
|
13
|
+
from doctr.models.preprocessor import PreProcessor
|
|
14
|
+
from doctr.models.utils import set_device_and_dtype
|
|
15
|
+
|
|
16
|
+
__all__ = ["TablePredictor"]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class TablePredictor(nn.Module):
|
|
20
|
+
"""Implements an object able to recognize the cell structure of tables in a document.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
pre_processor: transform inputs for easier batched model inference
|
|
24
|
+
model: core table-structure-recognition architecture
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
pre_processor: PreProcessor,
|
|
30
|
+
model: nn.Module,
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__()
|
|
33
|
+
self.pre_processor = pre_processor
|
|
34
|
+
self.model = model.eval()
|
|
35
|
+
|
|
36
|
+
@torch.inference_mode()
|
|
37
|
+
def forward(self, pages: list[np.ndarray], **kwargs: Any) -> list[dict[str, Any]]:
|
|
38
|
+
# Extract parameters from the preprocessor
|
|
39
|
+
preserve_aspect_ratio = self.pre_processor.resize.preserve_aspect_ratio
|
|
40
|
+
symmetric_pad = self.pre_processor.resize.symmetric_pad
|
|
41
|
+
assume_straight_pages = self.model.assume_straight_pages
|
|
42
|
+
# Dimension check
|
|
43
|
+
if any(page.ndim != 3 for page in pages):
|
|
44
|
+
raise ValueError("incorrect input shape: all pages are expected to be multi-channel 2D images.")
|
|
45
|
+
|
|
46
|
+
processed_batches = self.pre_processor(pages)
|
|
47
|
+
_params = next(self.model.parameters())
|
|
48
|
+
self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
|
|
49
|
+
self.model, processed_batches, _params.device, _params.dtype
|
|
50
|
+
)
|
|
51
|
+
predicted_batches = [self.model(batch, return_preds=True, **kwargs) for batch in processed_batches]
|
|
52
|
+
preds = [pred for batch in predicted_batches for pred in batch["preds"]]
|
|
53
|
+
|
|
54
|
+
rectified = _remove_padding(
|
|
55
|
+
pages,
|
|
56
|
+
[{"polygons": pred["polygons"]} for pred in preds],
|
|
57
|
+
preserve_aspect_ratio=preserve_aspect_ratio,
|
|
58
|
+
symmetric_pad=symmetric_pad,
|
|
59
|
+
assume_straight_pages=assume_straight_pages, # type: ignore[arg-type]
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
results: list[dict[str, Any]] = []
|
|
63
|
+
for pred, rect in zip(preds, rectified):
|
|
64
|
+
polygons = rect["polygons"] # * np.array([w, h], dtype=np.float32) # relative -> absolute pixels
|
|
65
|
+
scores, logical = pred["scores"], pred["logical"]
|
|
66
|
+
cells, max_row, max_col = [], -1, -1
|
|
67
|
+
for poly, score, lc in zip(polygons, scores, logical):
|
|
68
|
+
start_col, end_col, start_row, end_row = (int(v) for v in lc)
|
|
69
|
+
max_row, max_col = max(max_row, end_row), max(max_col, end_col)
|
|
70
|
+
cells.append({
|
|
71
|
+
"geometry": poly.tolist(), # 4 points (TL, TR, BR, BL) in relative coordinates
|
|
72
|
+
"score": float(score),
|
|
73
|
+
"row_start": start_row,
|
|
74
|
+
"row_end": end_row,
|
|
75
|
+
"col_start": start_col,
|
|
76
|
+
"col_end": end_col,
|
|
77
|
+
})
|
|
78
|
+
# logical coordinates are 0-indexed, so the table size is the largest index + 1 (0 if no cells)
|
|
79
|
+
results.append({"cells": cells, "num_rows": max_row + 1, "num_cols": max_col + 1})
|
|
80
|
+
return results
|