python-doctr 1.1.0__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/main.py +186 -23
- doctr/datasets/detection.py +12 -2
- doctr/datasets/generator/base.py +118 -35
- doctr/datasets/generator/pytorch.py +1 -1
- doctr/datasets/ic03.py +6 -5
- doctr/datasets/layout.py +7 -1
- doctr/datasets/recognition.py +3 -3
- doctr/datasets/svt.py +7 -6
- doctr/datasets/utils.py +100 -26
- doctr/datasets/vocabs.py +320 -150
- doctr/io/__init__.py +2 -0
- doctr/io/elements.py +138 -20
- doctr/io/exporters.py +848 -208
- doctr/io/figures.py +313 -0
- doctr/io/image/base.py +54 -8
- doctr/io/image/pytorch.py +14 -8
- doctr/io/pdf.py +6 -5
- doctr/io/reader.py +268 -18
- doctr/io/sources.py +636 -0
- doctr/models/__init__.py +1 -0
- doctr/models/_utils.py +150 -5
- doctr/models/builder.py +316 -334
- doctr/models/classification/__init__.py +1 -0
- doctr/models/classification/hgnetv2/__init__.py +1 -0
- doctr/models/classification/hgnetv2/pytorch.py +352 -0
- doctr/models/classification/predictor/pytorch.py +28 -0
- doctr/models/classification/zoo.py +11 -2
- doctr/models/detection/core.py +1 -2
- doctr/models/detection/differentiable_binarization/base.py +17 -5
- doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
- doctr/models/detection/fast/base.py +17 -5
- doctr/models/detection/fast/pytorch.py +21 -8
- doctr/models/detection/linknet/base.py +17 -5
- doctr/models/detection/linknet/pytorch.py +7 -0
- doctr/models/detection/predictor/pytorch.py +40 -0
- doctr/models/detection/zoo.py +4 -0
- doctr/models/factory/hub.py +5 -2
- 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 +7 -0
- doctr/models/kie_predictor/pytorch.py +47 -6
- doctr/models/layout/lw_detr/pytorch.py +150 -93
- doctr/models/layout/predictor/pytorch.py +32 -0
- doctr/models/layout/zoo.py +4 -0
- doctr/models/modules/transformer/pytorch.py +151 -31
- doctr/models/predictor/base.py +283 -7
- doctr/models/predictor/pytorch.py +53 -98
- doctr/models/preprocessor/pytorch.py +13 -11
- doctr/models/reading_order/base.py +720 -260
- doctr/models/recognition/core.py +14 -1
- doctr/models/recognition/crnn/pytorch.py +37 -11
- doctr/models/recognition/master/base.py +4 -1
- doctr/models/recognition/master/pytorch.py +83 -20
- doctr/models/recognition/parseq/base.py +4 -1
- doctr/models/recognition/parseq/pytorch.py +123 -22
- doctr/models/recognition/predictor/_utils.py +131 -14
- doctr/models/recognition/predictor/pytorch.py +67 -11
- doctr/models/recognition/sar/pytorch.py +20 -6
- doctr/models/recognition/utils.py +75 -43
- doctr/models/recognition/viptr/pytorch.py +37 -11
- doctr/models/recognition/vitstr/base.py +4 -1
- doctr/models/recognition/vitstr/pytorch.py +7 -3
- doctr/models/recognition/zoo.py +31 -3
- doctr/models/table_structure/grid.py +430 -0
- doctr/models/table_structure/predictor/pytorch.py +152 -1
- doctr/models/table_structure/tablecenternet/base.py +206 -16
- doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
- doctr/models/table_structure/zoo.py +5 -0
- doctr/models/utils/pytorch.py +73 -16
- doctr/models/zoo.py +53 -4
- doctr/transforms/functional/base.py +6 -0
- doctr/transforms/functional/pytorch.py +134 -6
- doctr/transforms/modules/base.py +17 -3
- doctr/transforms/modules/pytorch.py +185 -4
- doctr/utils/data.py +20 -9
- doctr/utils/fonts.py +17 -9
- doctr/utils/geometry.py +36 -14
- doctr/utils/metrics.py +143 -13
- doctr/utils/multithreading.py +122 -2
- doctr/utils/visualization.py +11 -7
- doctr/version.py +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
- {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/zip-safe +0 -0
|
@@ -5,9 +5,9 @@
|
|
|
5
5
|
|
|
6
6
|
from collections.abc import Callable
|
|
7
7
|
from copy import deepcopy
|
|
8
|
-
from itertools import groupby
|
|
9
8
|
from typing import Any
|
|
10
9
|
|
|
10
|
+
import numpy as np
|
|
11
11
|
import torch
|
|
12
12
|
import torch.nn as nn
|
|
13
13
|
import torch.nn.functional as F
|
|
@@ -15,6 +15,7 @@ from torchvision.models._utils import IntermediateLayerGetter
|
|
|
15
15
|
|
|
16
16
|
from doctr.datasets import VOCABS, decode_sequence
|
|
17
17
|
|
|
18
|
+
from ..._utils import ConfidenceAggregation, aggregate_confidence
|
|
18
19
|
from ...classification import vip_tiny
|
|
19
20
|
from ...utils import _bf16_to_float32, load_pretrained_params
|
|
20
21
|
from ..core import RecognitionModel, RecognitionPostProcessor
|
|
@@ -38,13 +39,22 @@ class VIPTRPostProcessor(RecognitionPostProcessor):
|
|
|
38
39
|
|
|
39
40
|
Args:
|
|
40
41
|
vocab: string containing the ordered sequence of supported characters
|
|
42
|
+
confidence_aggregation: aggregation method of the character probabilities into the word confidence
|
|
41
43
|
"""
|
|
42
44
|
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
vocab: str,
|
|
48
|
+
confidence_aggregation: ConfidenceAggregation = "min",
|
|
49
|
+
) -> None:
|
|
50
|
+
super().__init__(vocab, confidence_aggregation)
|
|
51
|
+
|
|
43
52
|
@staticmethod
|
|
44
53
|
def ctc_best_path(
|
|
45
54
|
logits: torch.Tensor,
|
|
46
55
|
vocab: str = VOCABS["french"],
|
|
47
56
|
blank: int = 0,
|
|
57
|
+
confidence_aggregation: ConfidenceAggregation = "min",
|
|
48
58
|
) -> list[tuple[str, float]]:
|
|
49
59
|
"""Implements best path decoding as shown by Graves (Dissertation, p63), highly inspired from
|
|
50
60
|
<https://github.com/githubharald/CTCDecoder>`_.
|
|
@@ -53,18 +63,27 @@ class VIPTRPostProcessor(RecognitionPostProcessor):
|
|
|
53
63
|
logits: model output, shape: N x T x C
|
|
54
64
|
vocab: vocabulary to use
|
|
55
65
|
blank: index of blank label
|
|
66
|
+
confidence_aggregation: aggregation method of the character probabilities into the word confidence
|
|
56
67
|
|
|
57
68
|
Returns:
|
|
58
69
|
A list of tuples: (word, confidence)
|
|
59
70
|
"""
|
|
60
|
-
|
|
61
|
-
probs = F.softmax(logits, dim=-1).max(dim=-1).values.
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
71
|
+
best_paths = logits.argmax(dim=-1).detach().cpu().numpy()
|
|
72
|
+
probs = F.softmax(logits.float(), dim=-1).max(dim=-1).values.detach().cpu().numpy()
|
|
73
|
+
|
|
74
|
+
results = []
|
|
75
|
+
for path, path_probs in zip(best_paths, probs):
|
|
76
|
+
# Collapse the repeated labels: the probability of a character is the highest one within its run
|
|
77
|
+
run_starts = np.flatnonzero(np.r_[True, path[1:] != path[:-1]])
|
|
78
|
+
labels, label_probs = path[run_starts], np.maximum.reduceat(path_probs, run_starts)
|
|
79
|
+
# Remove the blanks
|
|
80
|
+
is_char = labels != blank
|
|
81
|
+
results.append((
|
|
82
|
+
decode_sequence(labels[is_char].tolist(), vocab),
|
|
83
|
+
aggregate_confidence(label_probs[is_char], confidence_aggregation),
|
|
84
|
+
))
|
|
85
|
+
|
|
86
|
+
return results
|
|
68
87
|
|
|
69
88
|
def __call__(self, logits: torch.Tensor) -> list[tuple[str, float]]:
|
|
70
89
|
"""Performs decoding of raw output with CTC and decoding of CTC predictions
|
|
@@ -78,7 +97,12 @@ class VIPTRPostProcessor(RecognitionPostProcessor):
|
|
|
78
97
|
|
|
79
98
|
"""
|
|
80
99
|
# Decode CTC
|
|
81
|
-
return self.ctc_best_path(
|
|
100
|
+
return self.ctc_best_path(
|
|
101
|
+
logits=logits,
|
|
102
|
+
vocab=self.vocab,
|
|
103
|
+
blank=len(self.vocab),
|
|
104
|
+
confidence_aggregation=self.confidence_aggregation,
|
|
105
|
+
)
|
|
82
106
|
|
|
83
107
|
|
|
84
108
|
class VIPTR(RecognitionModel, nn.Module):
|
|
@@ -91,6 +115,7 @@ class VIPTR(RecognitionModel, nn.Module):
|
|
|
91
115
|
input_shape: input shape of the image
|
|
92
116
|
exportable: onnx exportable returns only logits
|
|
93
117
|
cfg: configuration dictionary
|
|
118
|
+
confidence_aggregation: aggregation method of the character probabilities into the word confidence
|
|
94
119
|
"""
|
|
95
120
|
|
|
96
121
|
def __init__(
|
|
@@ -100,6 +125,7 @@ class VIPTR(RecognitionModel, nn.Module):
|
|
|
100
125
|
input_shape: tuple[int, int, int] = (3, 32, 128),
|
|
101
126
|
exportable: bool = False,
|
|
102
127
|
cfg: dict[str, Any] | None = None,
|
|
128
|
+
confidence_aggregation: ConfidenceAggregation = "min",
|
|
103
129
|
):
|
|
104
130
|
super().__init__()
|
|
105
131
|
self.vocab = vocab
|
|
@@ -112,7 +138,7 @@ class VIPTR(RecognitionModel, nn.Module):
|
|
|
112
138
|
with torch.inference_mode():
|
|
113
139
|
embedding_units = self.feat_extractor(torch.zeros((1, *input_shape)))["features"].shape[-1]
|
|
114
140
|
|
|
115
|
-
self.postprocessor = VIPTRPostProcessor(vocab=self.vocab)
|
|
141
|
+
self.postprocessor = VIPTRPostProcessor(vocab=self.vocab, confidence_aggregation=confidence_aggregation)
|
|
116
142
|
self.head = nn.Linear(embedding_units, len(self.vocab) + 1) # +1 for PAD
|
|
117
143
|
|
|
118
144
|
for n, m in self.named_modules():
|
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import numpy as np
|
|
8
8
|
|
|
9
9
|
from ....datasets import encode_sequences
|
|
10
|
+
from ..._utils import ConfidenceAggregation
|
|
10
11
|
from ..core import RecognitionPostProcessor
|
|
11
12
|
|
|
12
13
|
|
|
@@ -43,11 +44,13 @@ class _ViTSTRPostProcessor(RecognitionPostProcessor):
|
|
|
43
44
|
|
|
44
45
|
Args:
|
|
45
46
|
vocab: string containing the ordered sequence of supported characters
|
|
47
|
+
confidence_aggregation: aggregation method of the character probabilities into the word confidence
|
|
46
48
|
"""
|
|
47
49
|
|
|
48
50
|
def __init__(
|
|
49
51
|
self,
|
|
50
52
|
vocab: str,
|
|
53
|
+
confidence_aggregation: ConfidenceAggregation = "mean",
|
|
51
54
|
) -> None:
|
|
52
|
-
super().__init__(vocab)
|
|
55
|
+
super().__init__(vocab, confidence_aggregation)
|
|
53
56
|
self._embedding = list(vocab) + ["<eos>", "<sos>"]
|
|
@@ -14,6 +14,7 @@ from torchvision.models._utils import IntermediateLayerGetter
|
|
|
14
14
|
|
|
15
15
|
from doctr.datasets import VOCABS
|
|
16
16
|
|
|
17
|
+
from ..._utils import ConfidenceAggregation, aggregate_confidence
|
|
17
18
|
from ...classification import vit_b, vit_s
|
|
18
19
|
from ...utils import _bf16_to_float32, load_pretrained_params
|
|
19
20
|
from .base import _ViTSTR, _ViTSTRPostProcessor
|
|
@@ -51,6 +52,7 @@ class ViTSTR(_ViTSTR, nn.Module):
|
|
|
51
52
|
input_shape: input shape of the image
|
|
52
53
|
exportable: onnx exportable returns only logits
|
|
53
54
|
cfg: dictionary containing information about the model
|
|
55
|
+
confidence_aggregation: aggregation method of the character probabilities into the word confidence
|
|
54
56
|
"""
|
|
55
57
|
|
|
56
58
|
def __init__(
|
|
@@ -62,6 +64,7 @@ class ViTSTR(_ViTSTR, nn.Module):
|
|
|
62
64
|
input_shape: tuple[int, int, int] = (3, 32, 128), # different from paper
|
|
63
65
|
exportable: bool = False,
|
|
64
66
|
cfg: dict[str, Any] | None = None,
|
|
67
|
+
confidence_aggregation: ConfidenceAggregation = "mean",
|
|
65
68
|
) -> None:
|
|
66
69
|
super().__init__()
|
|
67
70
|
self.vocab = vocab
|
|
@@ -72,7 +75,7 @@ class ViTSTR(_ViTSTR, nn.Module):
|
|
|
72
75
|
self.feat_extractor = feature_extractor
|
|
73
76
|
self.head = nn.Linear(embedding_units, len(self.vocab) + 1) # +1 for EOS
|
|
74
77
|
|
|
75
|
-
self.postprocessor = ViTSTRPostProcessor(vocab=self.vocab)
|
|
78
|
+
self.postprocessor = ViTSTRPostProcessor(vocab=self.vocab, confidence_aggregation=confidence_aggregation)
|
|
76
79
|
|
|
77
80
|
def from_pretrained(self, path_or_url: str, **kwargs: Any) -> None:
|
|
78
81
|
"""Load pretrained parameters onto the model
|
|
@@ -181,9 +184,10 @@ class ViTSTRPostProcessor(_ViTSTRPostProcessor):
|
|
|
181
184
|
"".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
|
|
182
185
|
for encoded_seq in out_idxs.detach().cpu().numpy()
|
|
183
186
|
]
|
|
184
|
-
#
|
|
187
|
+
# aggregate the character probabilities of each word up to the EOS token
|
|
185
188
|
probs = [
|
|
186
|
-
|
|
189
|
+
aggregate_confidence(preds_prob[i, : len(word)], self.confidence_aggregation)
|
|
190
|
+
for i, word in enumerate(word_values)
|
|
187
191
|
]
|
|
188
192
|
|
|
189
193
|
return list(zip(word_values, probs))
|
doctr/models/recognition/zoo.py
CHANGED
|
@@ -9,6 +9,7 @@ from doctr.models.preprocessor import PreProcessor
|
|
|
9
9
|
from doctr.models.utils import _CompiledModule
|
|
10
10
|
|
|
11
11
|
from .. import recognition
|
|
12
|
+
from .._utils import ConfidenceAggregation, _resolve_confidence_aggregation
|
|
12
13
|
from .predictor import RecognitionPredictor
|
|
13
14
|
|
|
14
15
|
__all__ = ["recognition_predictor"]
|
|
@@ -27,7 +28,15 @@ ARCHS: list[str] = [
|
|
|
27
28
|
]
|
|
28
29
|
|
|
29
30
|
|
|
30
|
-
def _predictor(
|
|
31
|
+
def _predictor(
|
|
32
|
+
arch: Any,
|
|
33
|
+
pretrained: bool,
|
|
34
|
+
confidence_aggregation: ConfidenceAggregation | None = None,
|
|
35
|
+
**kwargs: Any,
|
|
36
|
+
) -> RecognitionPredictor:
|
|
37
|
+
if confidence_aggregation is not None:
|
|
38
|
+
_resolve_confidence_aggregation(confidence_aggregation)
|
|
39
|
+
|
|
31
40
|
if isinstance(arch, str):
|
|
32
41
|
if arch not in ARCHS:
|
|
33
42
|
raise ValueError(f"unknown architecture '{arch}'")
|
|
@@ -51,13 +60,19 @@ def _predictor(arch: Any, pretrained: bool, **kwargs: Any) -> RecognitionPredict
|
|
|
51
60
|
raise ValueError(f"unknown architecture: {type(arch)}")
|
|
52
61
|
_model = arch
|
|
53
62
|
|
|
63
|
+
if confidence_aggregation is not None:
|
|
64
|
+
_model.postprocessor.confidence_aggregation = confidence_aggregation
|
|
65
|
+
|
|
54
66
|
kwargs.pop("pretrained_backbone", None)
|
|
55
67
|
|
|
56
68
|
kwargs["mean"] = kwargs.get("mean", _model.cfg["mean"])
|
|
57
69
|
kwargs["std"] = kwargs.get("std", _model.cfg["std"])
|
|
58
70
|
kwargs["batch_size"] = kwargs.get("batch_size", 128)
|
|
59
71
|
input_shape = _model.cfg["input_shape"][-2:]
|
|
60
|
-
|
|
72
|
+
chunk_size = kwargs.pop("chunk_size", 1024)
|
|
73
|
+
predictor = RecognitionPredictor(
|
|
74
|
+
PreProcessor(input_shape, preserve_aspect_ratio=True, **kwargs), _model, chunk_size=chunk_size
|
|
75
|
+
)
|
|
61
76
|
|
|
62
77
|
return predictor
|
|
63
78
|
|
|
@@ -67,6 +82,7 @@ def recognition_predictor(
|
|
|
67
82
|
pretrained: bool = False,
|
|
68
83
|
symmetric_pad: bool = False,
|
|
69
84
|
batch_size: int = 128,
|
|
85
|
+
confidence_aggregation: ConfidenceAggregation | None = None,
|
|
70
86
|
**kwargs: Any,
|
|
71
87
|
) -> RecognitionPredictor:
|
|
72
88
|
"""Text recognition architecture.
|
|
@@ -82,9 +98,21 @@ def recognition_predictor(
|
|
|
82
98
|
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
83
99
|
symmetric_pad: if True, pad the image symmetrically instead of padding at the bottom-right
|
|
84
100
|
batch_size: number of samples the model processes in parallel
|
|
101
|
+
chunk_size: maximum number of crops decoded and processed at once (1024 by default): longer inputs and
|
|
102
|
+
lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) are processed chunk by chunk
|
|
103
|
+
confidence_aggregation: aggregation method of the character probabilities into the word confidence:
|
|
104
|
+
"mean", "min", "max", "median", "geometric_mean", "harmonic_mean" or a callable. If None, the one of
|
|
105
|
+
the model is kept ("min" for CRNN, VIPTR, SAR and MASTER, "mean" for ViTSTR and PARSeq by default)
|
|
85
106
|
**kwargs: optional parameters to be passed to the architecture
|
|
86
107
|
|
|
87
108
|
Returns:
|
|
88
109
|
Recognition predictor
|
|
89
110
|
"""
|
|
90
|
-
return _predictor(
|
|
111
|
+
return _predictor(
|
|
112
|
+
arch=arch,
|
|
113
|
+
pretrained=pretrained,
|
|
114
|
+
symmetric_pad=symmetric_pad,
|
|
115
|
+
batch_size=batch_size,
|
|
116
|
+
confidence_aggregation=confidence_aggregation,
|
|
117
|
+
**kwargs,
|
|
118
|
+
)
|