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
|
@@ -7,10 +7,12 @@
|
|
|
7
7
|
import math
|
|
8
8
|
|
|
9
9
|
import numpy as np
|
|
10
|
+
from rapidfuzz.distance import Levenshtein
|
|
10
11
|
|
|
11
|
-
from
|
|
12
|
+
from ..._utils import ConfidenceAggregation, aggregate_confidence
|
|
13
|
+
from ..utils import exact_overlaps, merge_multi_strings, merge_strings
|
|
12
14
|
|
|
13
|
-
__all__ = ["split_crops", "remap_preds"]
|
|
15
|
+
__all__ = ["split_crops", "remap_preds", "ambiguous_overlaps", "resolve_overlap"]
|
|
14
16
|
|
|
15
17
|
|
|
16
18
|
def split_crops(
|
|
@@ -43,9 +45,8 @@ def split_crops(
|
|
|
43
45
|
|
|
44
46
|
for crop in crops:
|
|
45
47
|
h, w = crop.shape[:2]
|
|
46
|
-
aspect_ratio = w / h
|
|
47
48
|
|
|
48
|
-
if
|
|
49
|
+
if h > 0 and w / h > max_ratio:
|
|
49
50
|
split_width = max(1, math.ceil(h * target_ratio))
|
|
50
51
|
overlap_width = max(0, math.floor(split_width * split_overlap_ratio))
|
|
51
52
|
|
|
@@ -85,13 +86,7 @@ def _split_horizontally(image: np.ndarray, split_width: int, overlap_width: int)
|
|
|
85
86
|
if image_width <= split_width:
|
|
86
87
|
return [image], 0.0
|
|
87
88
|
|
|
88
|
-
|
|
89
|
-
step = split_width - overlap_width
|
|
90
|
-
starts = list(range(0, image_width - split_width + 1, step))
|
|
91
|
-
|
|
92
|
-
# Ensure the last patch reaches the end of the image
|
|
93
|
-
if starts[-1] + split_width < image_width:
|
|
94
|
-
starts.append(image_width - split_width)
|
|
89
|
+
starts = _split_starts(image_width, split_width, overlap_width)
|
|
95
90
|
|
|
96
91
|
splits = []
|
|
97
92
|
for start_col in starts:
|
|
@@ -107,10 +102,20 @@ def _split_horizontally(image: np.ndarray, split_width: int, overlap_width: int)
|
|
|
107
102
|
return splits, last_overlap_ratio
|
|
108
103
|
|
|
109
104
|
|
|
105
|
+
def _split_starts(image_width: int, split_width: int, overlap_width: int) -> list[int]:
|
|
106
|
+
"""Start columns of the splits of an image wider than ``split_width``, the last one reaching its end"""
|
|
107
|
+
starts = list(range(0, image_width - split_width + 1, split_width - overlap_width))
|
|
108
|
+
if starts[-1] + split_width < image_width:
|
|
109
|
+
starts.append(image_width - split_width)
|
|
110
|
+
return starts
|
|
111
|
+
|
|
112
|
+
|
|
110
113
|
def remap_preds(
|
|
111
114
|
preds: list[tuple[str, float]],
|
|
112
115
|
crop_map: list[int | tuple[int, int, float]],
|
|
113
116
|
overlap_ratio: float,
|
|
117
|
+
confidence_aggregation: ConfidenceAggregation = "min",
|
|
118
|
+
overlaps: dict[tuple[int, int], int] | None = None,
|
|
114
119
|
) -> list[tuple[str, float]]:
|
|
115
120
|
"""
|
|
116
121
|
Reconstruct predictions from possibly split crops.
|
|
@@ -119,18 +124,130 @@ def remap_preds(
|
|
|
119
124
|
preds: List of (text, confidence) tuples from each crop.
|
|
120
125
|
crop_map: Map returned by `split_crops`.
|
|
121
126
|
overlap_ratio: Overlap ratio used during splitting.
|
|
127
|
+
confidence_aggregation: Aggregation method of the confidences of the non-empty parts.
|
|
128
|
+
overlaps: the overlap length of parts ``i`` and ``i + 1`` of crop ``idx``, keyed by ``(idx, i)``, where it was
|
|
129
|
+
resolved (cf. `resolve_overlap`)
|
|
122
130
|
|
|
123
131
|
Returns:
|
|
124
132
|
List of merged (text, confidence) tuples corresponding to original crops.
|
|
125
133
|
"""
|
|
126
134
|
remapped = []
|
|
127
|
-
for item in crop_map:
|
|
135
|
+
for idx, item in enumerate(crop_map):
|
|
128
136
|
if isinstance(item, int):
|
|
129
137
|
remapped.append(preds[item])
|
|
130
138
|
else:
|
|
131
139
|
start_idx, end_idx, last_overlap = item
|
|
132
140
|
text_parts, confidences = zip(*preds[start_idx:end_idx])
|
|
133
|
-
|
|
134
|
-
|
|
141
|
+
crop_overlaps = {i: n for (crop_idx, i), n in (overlaps or {}).items() if crop_idx == idx}
|
|
142
|
+
merged_text = merge_multi_strings(list(text_parts), overlap_ratio, last_overlap, crop_overlaps)
|
|
143
|
+
text_confidences = [conf for text, conf in zip(text_parts, confidences) if text]
|
|
144
|
+
merged_conf = aggregate_confidence(text_confidences or confidences, confidence_aggregation)
|
|
135
145
|
remapped.append((merged_text, merged_conf))
|
|
136
146
|
return remapped
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _overlap_lengths(a: str, b: str, overlap_ratio: float) -> tuple[dict[int, str], int] | None:
|
|
150
|
+
"""The merges of ``a`` and ``b`` at each exact overlap length, and the length `merge_strings` picks, when several
|
|
151
|
+
lengths match exactly and `merge_strings` picks one of them"""
|
|
152
|
+
lengths = exact_overlaps(a, b)
|
|
153
|
+
if len(lengths) < 2:
|
|
154
|
+
return None
|
|
155
|
+
a_crop, b_crop = a[:-1], b[1:]
|
|
156
|
+
merges = {n: a_crop[: len(a_crop) - n] + b_crop for n in lengths}
|
|
157
|
+
merged = merge_strings(a, b, overlap_ratio)
|
|
158
|
+
default = next((n for n, text in merges.items() if text == merged), None)
|
|
159
|
+
return None if default is None else (merges, default)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def ambiguous_overlaps(
|
|
163
|
+
preds: list[tuple[str, float]],
|
|
164
|
+
crop_map: list[int | tuple[int, int, float]],
|
|
165
|
+
crops: list[np.ndarray],
|
|
166
|
+
target_ratio: int,
|
|
167
|
+
split_overlap_ratio: float,
|
|
168
|
+
) -> list[tuple[tuple[int, int], np.ndarray, str, str, float, float]]:
|
|
169
|
+
"""
|
|
170
|
+
Find the neighboring parts of split crops whose readings overlap exactly at several lengths.
|
|
171
|
+
|
|
172
|
+
Across a repeated stretch (a run such as "0000", or a pattern such as "EMEM"), the characters of an overlap do not
|
|
173
|
+
tell its length: `merge_strings` then relies on the length expected from the overlap ratio, which can be a
|
|
174
|
+
character off.
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
preds: List of (text, confidence) tuples from each part, as read.
|
|
178
|
+
crop_map: Map returned by `split_crops`.
|
|
179
|
+
crops: The crops passed to `split_crops`.
|
|
180
|
+
target_ratio: Target aspect ratio used during splitting.
|
|
181
|
+
split_overlap_ratio: Overlap ratio used during splitting.
|
|
182
|
+
|
|
183
|
+
Returns:
|
|
184
|
+
For each such pair of parts ``i`` and ``i + 1`` of crop ``idx``: ``(idx, i)``, the region of the crop that the
|
|
185
|
+
two parts cover, their readings, their overlap ratio, and the offset of part ``i + 1`` from part ``i`` as a
|
|
186
|
+
ratio of the part width.
|
|
187
|
+
"""
|
|
188
|
+
pairs = []
|
|
189
|
+
for idx, (item, crop) in enumerate(zip(crop_map, crops)):
|
|
190
|
+
if isinstance(item, int):
|
|
191
|
+
continue
|
|
192
|
+
start_idx, end_idx, last_overlap = item
|
|
193
|
+
texts = [text for text, _ in preds[start_idx:end_idx]]
|
|
194
|
+
height, width = crop.shape[:2]
|
|
195
|
+
split_width = max(1, math.ceil(height * target_ratio))
|
|
196
|
+
starts = _split_starts(width, split_width, max(0, math.floor(split_width * split_overlap_ratio)))
|
|
197
|
+
if len(starts) != len(texts): # an empty part was dropped
|
|
198
|
+
continue
|
|
199
|
+
for i in range(len(texts) - 1):
|
|
200
|
+
ratio = last_overlap if i == len(texts) - 2 else split_overlap_ratio
|
|
201
|
+
if _overlap_lengths(texts[i], texts[i + 1], ratio) is not None:
|
|
202
|
+
region = crop[:, starts[i] : starts[i + 1] + split_width]
|
|
203
|
+
offset = (starts[i + 1] - starts[i]) / split_width
|
|
204
|
+
pairs.append(((idx, i), region, texts[i], texts[i + 1], ratio, offset))
|
|
205
|
+
return pairs
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def resolve_overlap(
|
|
209
|
+
a: str,
|
|
210
|
+
b: str,
|
|
211
|
+
overlap_ratio: float,
|
|
212
|
+
offset: float,
|
|
213
|
+
region_text: str,
|
|
214
|
+
max_distance: int = 2,
|
|
215
|
+
margin: float = 0.25,
|
|
216
|
+
) -> int | None:
|
|
217
|
+
"""
|
|
218
|
+
Choose the overlap length of two readings that overlap exactly at several lengths.
|
|
219
|
+
|
|
220
|
+
Each length is scored by two independent signals, so that a misreading of one rarely decides alone:
|
|
221
|
+
- the edit distance of its merge to ``region_text``, a reading of the region both parts cover (a less squeezed
|
|
222
|
+
crop than the whole one, so it can count a repeated stretch),
|
|
223
|
+
- how far apart, in chars, the overlapping chars sit in the two parts when the chars of each part are spread
|
|
224
|
+
evenly over it.
|
|
225
|
+
|
|
226
|
+
Args:
|
|
227
|
+
a: reading of the left part.
|
|
228
|
+
b: reading of the right part.
|
|
229
|
+
overlap_ratio: estimated ratio of overlapping characters, relative to ``len(b)``, used by `merge_strings`.
|
|
230
|
+
offset: start of the right part minus start of the left part, as a ratio of the part width.
|
|
231
|
+
region_text: reading of the region both parts cover.
|
|
232
|
+
max_distance: largest edit distance from ``region_text`` at which a length can replace `merge_strings`' one.
|
|
233
|
+
margin: score by which it must beat `merge_strings`' one.
|
|
234
|
+
|
|
235
|
+
Returns:
|
|
236
|
+
The overlap length, or None to keep `merge_strings`' alignment.
|
|
237
|
+
"""
|
|
238
|
+
candidates = _overlap_lengths(a, b, overlap_ratio)
|
|
239
|
+
if candidates is None:
|
|
240
|
+
return None
|
|
241
|
+
merges, default = candidates
|
|
242
|
+
|
|
243
|
+
def score(n: int) -> tuple[float, int]:
|
|
244
|
+
# Char j of `a` is centred at (j + 0.5) / len(a) of the part width, char j of `b` at offset + (j + 0.5) / len(b)
|
|
245
|
+
gaps = [abs((len(a) - 1 - n + t + 0.5) / len(a) - offset - (t + 1.5) / len(b)) for t in range(n)]
|
|
246
|
+
distance = Levenshtein.distance(merges[n], region_text)
|
|
247
|
+
return distance + len(b) * sum(gaps) / n, distance
|
|
248
|
+
|
|
249
|
+
scores = {n: score(n) for n in merges}
|
|
250
|
+
best = min(merges, key=lambda n: (scores[n][0], n != default))
|
|
251
|
+
if best == default or scores[best][1] > max_distance or scores[best][0] + margin > scores[default][0]:
|
|
252
|
+
return None
|
|
253
|
+
return best
|
|
@@ -3,17 +3,19 @@
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
|
-
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Iterable, Sequence
|
|
7
8
|
from typing import Any
|
|
8
9
|
|
|
9
10
|
import numpy as np
|
|
10
11
|
import torch
|
|
11
12
|
from torch import nn
|
|
12
13
|
|
|
14
|
+
from doctr.models._utils import ConfidenceAggregation, _resolve_confidence_aggregation, predict_by_chunks
|
|
13
15
|
from doctr.models.preprocessor import PreProcessor
|
|
14
16
|
from doctr.models.utils import set_device_and_dtype
|
|
15
17
|
|
|
16
|
-
from ._utils import remap_preds, split_crops
|
|
18
|
+
from ._utils import ambiguous_overlaps, remap_preds, resolve_overlap, split_crops
|
|
17
19
|
|
|
18
20
|
__all__ = ["RecognitionPredictor"]
|
|
19
21
|
|
|
@@ -25,6 +27,13 @@ class RecognitionPredictor(nn.Module):
|
|
|
25
27
|
pre_processor: transform inputs for easier batched model inference
|
|
26
28
|
model: core detection architecture
|
|
27
29
|
split_wide_crops: wether to use crop splitting for high aspect ratio crops
|
|
30
|
+
resolve_ambiguous_overlaps: whether to read the region two parts of a split crop cover once more when their
|
|
31
|
+
readings overlap exactly at several lengths (across a repeated stretch such as "0000"), to choose the
|
|
32
|
+
overlap length (cf. `resolve_overlap`)
|
|
33
|
+
chunk_size: the maximum number of crops decoded and processed at once (1024 by default). Longer
|
|
34
|
+
inputs, lazy page sources (cf. `DocumentFile.from_images(..., lazy=True)`) and iterators are processed
|
|
35
|
+
chunk by chunk, with a memory footprint that does not grow with the number of crops. It is rounded
|
|
36
|
+
up to a multiple of the batch size, so that the predictions are the same as in a single pass.
|
|
28
37
|
"""
|
|
29
38
|
|
|
30
39
|
def __init__(
|
|
@@ -32,26 +41,58 @@ class RecognitionPredictor(nn.Module):
|
|
|
32
41
|
pre_processor: PreProcessor,
|
|
33
42
|
model: nn.Module,
|
|
34
43
|
split_wide_crops: bool = True,
|
|
44
|
+
resolve_ambiguous_overlaps: bool = True,
|
|
45
|
+
chunk_size: int = 1024,
|
|
35
46
|
) -> None:
|
|
36
47
|
super().__init__()
|
|
37
48
|
self.pre_processor = pre_processor
|
|
38
49
|
self.model = model.eval()
|
|
50
|
+
if chunk_size < 1:
|
|
51
|
+
raise ValueError("`chunk_size` must be a positive integer")
|
|
52
|
+
self.chunk_size = chunk_size
|
|
39
53
|
self.split_wide_crops = split_wide_crops
|
|
54
|
+
self.resolve_ambiguous_overlaps = resolve_ambiguous_overlaps
|
|
40
55
|
self.critical_ar = 8 # Critical aspect ratio
|
|
41
56
|
self.overlap_ratio = 0.5 # Ratio of overlap between neighboring crops
|
|
42
57
|
self.target_ar = 6 # Target aspect ratio
|
|
58
|
+
self.split_confidence_aggregation: ConfidenceAggregation = "min" # Confidence aggregation for split crops
|
|
43
59
|
|
|
44
60
|
@torch.inference_mode()
|
|
45
61
|
def forward(
|
|
62
|
+
self,
|
|
63
|
+
crops: Sequence[np.ndarray] | Iterable[np.ndarray],
|
|
64
|
+
**kwargs: Any,
|
|
65
|
+
) -> list[tuple[str, float]]:
|
|
66
|
+
"""Read the character sequence of word crops
|
|
67
|
+
|
|
68
|
+
Args:
|
|
69
|
+
crops: a list of word crops (numpy arrays of shape H x W x C), a lazy page source
|
|
70
|
+
(cf. `DocumentFile.from_images(..., lazy=True)`) or any iterable of crops
|
|
71
|
+
**kwargs: keyword arguments forwarded to the model
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
the text and confidence of each crop
|
|
75
|
+
"""
|
|
76
|
+
return predict_by_chunks(
|
|
77
|
+
lambda chunk: self._predict(chunk, **kwargs), crops, self.chunk_size, self.pre_processor.batch_size
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
@torch.inference_mode()
|
|
81
|
+
def _predict(
|
|
46
82
|
self,
|
|
47
83
|
crops: Sequence[np.ndarray],
|
|
48
84
|
**kwargs: Any,
|
|
49
85
|
) -> list[tuple[str, float]]:
|
|
50
86
|
if len(crops) == 0:
|
|
51
87
|
return []
|
|
88
|
+
_resolve_confidence_aggregation(self.split_confidence_aggregation)
|
|
52
89
|
# Dimension check
|
|
53
90
|
if any(crop.ndim != 3 for crop in crops):
|
|
54
91
|
raise ValueError("incorrect input shape: all crops are expected to be multi-channel 2D images.")
|
|
92
|
+
# An empty crop would otherwise fail with a ZeroDivisionError while splitting or resizing
|
|
93
|
+
empty = next((crop for crop in crops if not all(s > 0 for s in crop.shape)), None)
|
|
94
|
+
if empty is not None:
|
|
95
|
+
raise ValueError(f"incorrect input shape: crops are expected to be non-empty, got shape {empty.shape}.")
|
|
55
96
|
|
|
56
97
|
# Split crops that are too wide
|
|
57
98
|
remapped = False
|
|
@@ -62,24 +103,39 @@ class RecognitionPredictor(nn.Module):
|
|
|
62
103
|
self.target_ar,
|
|
63
104
|
self.overlap_ratio,
|
|
64
105
|
)
|
|
65
|
-
if remapped:
|
|
66
|
-
crops = new_crops
|
|
67
106
|
|
|
107
|
+
out = self._read(new_crops if remapped else crops, **kwargs)
|
|
108
|
+
|
|
109
|
+
# Remap crops
|
|
110
|
+
if self.split_wide_crops and remapped:
|
|
111
|
+
overlaps: dict[tuple[int, int], int] = {}
|
|
112
|
+
if self.resolve_ambiguous_overlaps:
|
|
113
|
+
pairs = ambiguous_overlaps(out, crop_map, list(crops), self.target_ar, self.overlap_ratio)
|
|
114
|
+
if pairs:
|
|
115
|
+
region_reads = self._read([region for _, region, *_ in pairs], **kwargs)
|
|
116
|
+
# A reading this long may have been cut short by the model: the models are trained on words of
|
|
117
|
+
# up to `max_length - 2` (PARSeq, MASTER, ViTSTR), `max_length - 1` (SAR) or `max_length` chars
|
|
118
|
+
# (CRNN, VIPTR)
|
|
119
|
+
max_length = getattr(self.model, "max_length", math.inf) - 2
|
|
120
|
+
for (key, _, a, b, ratio, offset), (region_text, _) in zip(pairs, region_reads, strict=True):
|
|
121
|
+
length = resolve_overlap(a, b, ratio, offset, region_text)
|
|
122
|
+
if length is not None and len(region_text) < max_length:
|
|
123
|
+
overlaps[key] = length
|
|
124
|
+
out = remap_preds(out, crop_map, self.overlap_ratio, self.split_confidence_aggregation, overlaps)
|
|
125
|
+
|
|
126
|
+
return out
|
|
127
|
+
|
|
128
|
+
def _read(self, crops: Sequence[np.ndarray], **kwargs: Any) -> list[tuple[str, float]]:
|
|
129
|
+
"""Read the character sequence of each crop, as is"""
|
|
68
130
|
# Resize & batch them
|
|
69
131
|
processed_batches = self.pre_processor(crops) # type: ignore[arg-type]
|
|
70
132
|
|
|
71
133
|
# Forward it
|
|
72
134
|
_params = next(self.model.parameters())
|
|
73
|
-
self.model, processed_batches = set_device_and_dtype(
|
|
135
|
+
self.model, processed_batches = set_device_and_dtype( # type: ignore[assignment]
|
|
74
136
|
self.model, processed_batches, _params.device, _params.dtype
|
|
75
137
|
)
|
|
76
138
|
raw = [self.model(batch, return_preds=True, **kwargs)["preds"] for batch in processed_batches]
|
|
77
139
|
|
|
78
140
|
# Process outputs
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
# Remap crops
|
|
82
|
-
if self.split_wide_crops and remapped:
|
|
83
|
-
out = remap_preds(out, crop_map, self.overlap_ratio)
|
|
84
|
-
|
|
85
|
-
return out
|
|
141
|
+
return [charseq for batch in raw for charseq in batch]
|
|
@@ -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 resnet31
|
|
18
19
|
from ...utils import _bf16_to_float32, load_pretrained_params
|
|
19
20
|
from ..core import RecognitionModel, RecognitionPostProcessor
|
|
@@ -104,7 +105,7 @@ class SARDecoder(nn.Module):
|
|
|
104
105
|
self.max_length = max_length
|
|
105
106
|
|
|
106
107
|
self.embed = nn.Linear(self.vocab_size + 1, embedding_units)
|
|
107
|
-
self.embed_tgt = nn.Embedding(embedding_units, self.vocab_size + 1)
|
|
108
|
+
self.embed_tgt = nn.Embedding(max(embedding_units, self.vocab_size + 1), self.vocab_size + 1)
|
|
108
109
|
self.attention_module = AttentionModule(feat_chans, rnn_units, attention_units)
|
|
109
110
|
self.lstm_cell = nn.LSTMCell(rnn_units, rnn_units)
|
|
110
111
|
self.output_dense = nn.Linear(2 * rnn_units, self.vocab_size + 1)
|
|
@@ -175,6 +176,7 @@ class SAR(nn.Module, RecognitionModel):
|
|
|
175
176
|
dropout_prob: dropout probability of the encoder LSTM
|
|
176
177
|
exportable: onnx exportable returns only logits
|
|
177
178
|
cfg: dictionary containing information about the model
|
|
179
|
+
confidence_aggregation: aggregation method of the character probabilities into the word confidence
|
|
178
180
|
"""
|
|
179
181
|
|
|
180
182
|
def __init__(
|
|
@@ -189,6 +191,7 @@ class SAR(nn.Module, RecognitionModel):
|
|
|
189
191
|
input_shape: tuple[int, int, int] = (3, 32, 128),
|
|
190
192
|
exportable: bool = False,
|
|
191
193
|
cfg: dict[str, Any] | None = None,
|
|
194
|
+
confidence_aggregation: ConfidenceAggregation = "min",
|
|
192
195
|
) -> None:
|
|
193
196
|
super().__init__()
|
|
194
197
|
self.vocab = vocab
|
|
@@ -216,7 +219,7 @@ class SAR(nn.Module, RecognitionModel):
|
|
|
216
219
|
dropout_prob=dropout_prob,
|
|
217
220
|
)
|
|
218
221
|
|
|
219
|
-
self.postprocessor = SARPostProcessor(vocab=vocab)
|
|
222
|
+
self.postprocessor = SARPostProcessor(vocab=vocab, confidence_aggregation=confidence_aggregation)
|
|
220
223
|
|
|
221
224
|
for n, m in self.named_modules():
|
|
222
225
|
# Don't override the initialization of the backbone
|
|
@@ -320,8 +323,16 @@ class SARPostProcessor(RecognitionPostProcessor):
|
|
|
320
323
|
|
|
321
324
|
Args:
|
|
322
325
|
vocab: string containing the ordered sequence of supported characters
|
|
326
|
+
confidence_aggregation: aggregation method of the character probabilities into the word confidence
|
|
323
327
|
"""
|
|
324
328
|
|
|
329
|
+
def __init__(
|
|
330
|
+
self,
|
|
331
|
+
vocab: str,
|
|
332
|
+
confidence_aggregation: ConfidenceAggregation = "min",
|
|
333
|
+
) -> None:
|
|
334
|
+
super().__init__(vocab, confidence_aggregation)
|
|
335
|
+
|
|
325
336
|
def __call__(
|
|
326
337
|
self,
|
|
327
338
|
logits: torch.Tensor,
|
|
@@ -329,17 +340,20 @@ class SARPostProcessor(RecognitionPostProcessor):
|
|
|
329
340
|
# compute pred with argmax for attention models
|
|
330
341
|
out_idxs = logits.argmax(-1)
|
|
331
342
|
# N x L
|
|
332
|
-
|
|
333
|
-
# Take the minimum confidence of the sequence
|
|
334
|
-
probs = probs.min(dim=1).values.detach().cpu()
|
|
343
|
+
preds_prob = torch.softmax(logits, -1).max(dim=-1)[0].detach().cpu().numpy()
|
|
335
344
|
|
|
336
345
|
# Manual decoding
|
|
337
346
|
word_values = [
|
|
338
347
|
"".join(self._embedding[idx] for idx in encoded_seq).split("<eos>")[0]
|
|
339
348
|
for encoded_seq in out_idxs.detach().cpu().numpy()
|
|
340
349
|
]
|
|
350
|
+
# aggregate the character probabilities of each word up to the EOS token
|
|
351
|
+
probs = [
|
|
352
|
+
aggregate_confidence(preds_prob[i, : len(word)], self.confidence_aggregation)
|
|
353
|
+
for i, word in enumerate(word_values)
|
|
354
|
+
]
|
|
341
355
|
|
|
342
|
-
return list(zip(word_values, probs
|
|
356
|
+
return list(zip(word_values, probs))
|
|
343
357
|
|
|
344
358
|
|
|
345
359
|
def _sar(
|
|
@@ -389,7 +403,7 @@ def sar_resnet31(pretrained: bool = False, **kwargs: Any) -> SAR:
|
|
|
389
403
|
>>> out = model(input_tensor)
|
|
390
404
|
|
|
391
405
|
Args:
|
|
392
|
-
pretrained
|
|
406
|
+
pretrained: If True, returns a model pre-trained on our text recognition dataset
|
|
393
407
|
**kwargs: keyword arguments of the SAR architecture
|
|
394
408
|
|
|
395
409
|
Returns:
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
# This program is licensed under the Apache License 2.0.
|
|
4
4
|
# See LICENSE or go to <https://opensource.org/licenses/Apache-2.0> for full license details.
|
|
5
5
|
|
|
6
|
+
import math
|
|
6
7
|
|
|
7
|
-
from rapidfuzz.distance import
|
|
8
|
+
from rapidfuzz.distance import Levenshtein
|
|
8
9
|
|
|
9
|
-
__all__ = ["merge_strings", "merge_multi_strings"]
|
|
10
|
+
__all__ = ["merge_strings", "merge_multi_strings", "exact_overlaps"]
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
def merge_strings(a: str, b: str, overlap_ratio: float) -> str:
|
|
@@ -15,58 +16,71 @@ def merge_strings(a: str, b: str, overlap_ratio: float) -> str:
|
|
|
15
16
|
Args:
|
|
16
17
|
a: first char seq, suffix should be similar to b's prefix.
|
|
17
18
|
b: second char seq, prefix should be similar to a's suffix.
|
|
18
|
-
overlap_ratio: estimated ratio of overlapping characters.
|
|
19
|
+
overlap_ratio: estimated ratio of overlapping characters, relative to ``len(b)``, in [0, 1].
|
|
19
20
|
|
|
20
21
|
Returns:
|
|
21
22
|
A merged character sequence.
|
|
22
23
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
'abcdefgh'
|
|
24
|
+
>>> from doctr.models.recognition.utils import merge_strings
|
|
25
|
+
>>> merge_strings('abcdX', 'Xdefgh', 0.5)
|
|
26
|
+
'abcdefgh'
|
|
27
|
+
>>> merge_strings('abcdi', 'cdefgh', 0.5)
|
|
28
|
+
'abcdefgh'
|
|
29
29
|
"""
|
|
30
|
-
|
|
31
|
-
if
|
|
30
|
+
overlap_ratio = min(max(overlap_ratio, 0.0), 1.0)
|
|
31
|
+
if min(len(a), len(b)) <= 1: # One sequence is empty or will be after cropping in next step, return both
|
|
32
32
|
return a + b
|
|
33
33
|
|
|
34
34
|
a_crop, b_crop = a[:-1], b[1:] # Remove last letter of "a" and first of "b", because they might be cut off
|
|
35
35
|
max_overlap = min(len(a_crop), len(b_crop))
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
36
|
+
# Expected overlap length between the crops (2 chars were removed by cropping)
|
|
37
|
+
expected = len(b) * overlap_ratio - 2
|
|
38
|
+
|
|
39
|
+
# Start with the "no overlap" hypothesis: cost grows with the expected overlap
|
|
40
|
+
best_cost, best_i, best_j, best_dist = max(expected, 0.0) + 1.0, 0, 0, math.inf
|
|
41
|
+
|
|
42
|
+
# Compare the last i chars of a_crop with the first j chars of b_crop (|i - j| <= 2 absorbs inserted or
|
|
43
|
+
# dropped chars). Lengths closest to the expected one are visited first, so the search stops as soon as no
|
|
44
|
+
# remaining candidate can beat the best one.
|
|
45
|
+
for i in sorted(range(1, max_overlap + 1), key=lambda n: (abs(n - expected), -n)):
|
|
46
|
+
length_cost = abs(i - expected)
|
|
47
|
+
if length_cost > best_cost:
|
|
48
|
+
break
|
|
49
|
+
for j in range(max(1, i - 2), min(len(b_crop), i + 2) + 1):
|
|
50
|
+
fixed_cost = length_cost + 0.25 * abs(i - j)
|
|
51
|
+
# Largest acceptable edit distance: at most 0.8 edits per char, and still able to win (or tie)
|
|
52
|
+
cutoff = min(math.floor(0.8 * max(i, j)), math.floor(best_cost - fixed_cost))
|
|
53
|
+
if cutoff < abs(i - j): # the edit distance is at least the length difference
|
|
54
|
+
continue
|
|
55
|
+
dist = Levenshtein.distance(a_crop[-i:], b_crop[:j], score_cutoff=cutoff)
|
|
56
|
+
if dist > cutoff:
|
|
57
|
+
continue
|
|
58
|
+
cost = dist + fixed_cost
|
|
59
|
+
# On a tie, prefer the closer match, then the longer overlap
|
|
60
|
+
if cost < best_cost or (cost == best_cost and (dist, -i) < (best_dist, -best_i)):
|
|
61
|
+
best_cost, best_i, best_j, best_dist = cost, i, j, dist
|
|
62
|
+
|
|
63
|
+
if best_i == 0:
|
|
64
|
+
# No overlap: with less than ~1 char of expected overlap, the border chars are most likely complete
|
|
65
|
+
# characters (each read by one crop only), so they are kept
|
|
66
|
+
return a + b if len(b) * overlap_ratio < 1 else a_crop + b_crop
|
|
67
|
+
|
|
68
|
+
# Join both readings of the overlap in the middle of their alignment: chars close to a crop border are the
|
|
69
|
+
# least reliable, so the left half is taken from a_crop and the right half from b_crop
|
|
70
|
+
tail, head = a_crop[-best_i:], b_crop[:best_j]
|
|
71
|
+
cuts = [(0, 0)]
|
|
72
|
+
for op in Levenshtein.opcodes(tail, head):
|
|
73
|
+
if op.tag == "equal":
|
|
74
|
+
cuts.extend((op.src_start + t, op.dest_start + t) for t in range(1, op.src_end - op.src_start + 1))
|
|
75
|
+
else:
|
|
76
|
+
cuts.append((op.src_end, op.dest_end))
|
|
77
|
+
cut_a, cut_b = min(cuts, key=lambda c: abs(c[0] + c[1] - (best_i + best_j) / 2))
|
|
78
|
+
return a_crop[: len(a_crop) - best_i] + tail[:cut_a] + head[cut_b:] + b_crop[best_j:]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def merge_multi_strings(
|
|
82
|
+
seq_list: list[str], overlap_ratio: float, last_overlap_ratio: float, overlaps: dict[int, int] | None = None
|
|
83
|
+
) -> str:
|
|
70
84
|
"""
|
|
71
85
|
Merges consecutive string sequences with overlapping characters.
|
|
72
86
|
|
|
@@ -74,14 +88,15 @@ def merge_multi_strings(seq_list: list[str], overlap_ratio: float, last_overlap_
|
|
|
74
88
|
seq_list: list of sequences to merge. Sequences need to be ordered from left to right.
|
|
75
89
|
overlap_ratio: Estimated ratio of overlapping letters between neighboring strings.
|
|
76
90
|
last_overlap_ratio: Estimated ratio of overlapping letters for the last element in seq_list.
|
|
91
|
+
overlaps: number of chars shared by sequences ``i`` and ``i + 1`` once they lose their border chars, for the
|
|
92
|
+
pairs ``i`` where it is known (cf. `exact_overlaps`); the other pairs are aligned by `merge_strings`
|
|
77
93
|
|
|
78
94
|
Returns:
|
|
79
95
|
A merged character sequence
|
|
80
96
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
'abcdefghijkl'
|
|
97
|
+
>>> from doctr.models.recognition.utils import merge_multi_strings
|
|
98
|
+
>>> merge_multi_strings(['abcdX', 'XdefX', 'XefghX', 'Xijk'], 0.5, 0.5)
|
|
99
|
+
'abcdefghijk'
|
|
85
100
|
"""
|
|
86
101
|
if not seq_list:
|
|
87
102
|
return ""
|
|
@@ -89,5 +104,20 @@ def merge_multi_strings(seq_list: list[str], overlap_ratio: float, last_overlap_
|
|
|
89
104
|
for i in range(1, len(seq_list)):
|
|
90
105
|
text_b = seq_list[i]
|
|
91
106
|
ratio = last_overlap_ratio if i == len(seq_list) - 1 else overlap_ratio
|
|
92
|
-
|
|
107
|
+
length = (overlaps or {}).get(i - 1)
|
|
108
|
+
if length is not None and length in exact_overlaps(result, text_b):
|
|
109
|
+
result = result[: len(result) - 1 - length] + text_b[1:]
|
|
110
|
+
else:
|
|
111
|
+
result = merge_strings(result, text_b, ratio)
|
|
93
112
|
return result
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def exact_overlaps(a: str, b: str) -> list[int]:
|
|
116
|
+
"""Lengths at which the end of ``a`` matches the start of ``b`` exactly, once both lose their border char
|
|
117
|
+
|
|
118
|
+
>>> from doctr.models.recognition.utils import exact_overlaps
|
|
119
|
+
>>> exact_overlaps('WARMUP-0000', '-0000001')
|
|
120
|
+
[1, 2, 3]
|
|
121
|
+
"""
|
|
122
|
+
a_crop, b_crop = a[:-1], b[1:]
|
|
123
|
+
return [n for n in range(1, min(len(a_crop), len(b_crop)) + 1) if a_crop[-n:] == b_crop[:n]]
|