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.
Files changed (93) hide show
  1. doctr/cli/main.py +186 -23
  2. doctr/datasets/detection.py +12 -2
  3. doctr/datasets/generator/base.py +118 -35
  4. doctr/datasets/generator/pytorch.py +1 -1
  5. doctr/datasets/ic03.py +6 -5
  6. doctr/datasets/layout.py +7 -1
  7. doctr/datasets/recognition.py +3 -3
  8. doctr/datasets/svt.py +7 -6
  9. doctr/datasets/utils.py +100 -26
  10. doctr/datasets/vocabs.py +320 -150
  11. doctr/io/__init__.py +2 -0
  12. doctr/io/elements.py +138 -20
  13. doctr/io/exporters.py +848 -208
  14. doctr/io/figures.py +313 -0
  15. doctr/io/image/base.py +54 -8
  16. doctr/io/image/pytorch.py +14 -8
  17. doctr/io/pdf.py +6 -5
  18. doctr/io/reader.py +268 -18
  19. doctr/io/sources.py +636 -0
  20. doctr/models/__init__.py +1 -0
  21. doctr/models/_utils.py +150 -5
  22. doctr/models/builder.py +316 -334
  23. doctr/models/classification/__init__.py +1 -0
  24. doctr/models/classification/hgnetv2/__init__.py +1 -0
  25. doctr/models/classification/hgnetv2/pytorch.py +352 -0
  26. doctr/models/classification/predictor/pytorch.py +28 -0
  27. doctr/models/classification/zoo.py +11 -2
  28. doctr/models/detection/core.py +1 -2
  29. doctr/models/detection/differentiable_binarization/base.py +17 -5
  30. doctr/models/detection/differentiable_binarization/pytorch.py +7 -1
  31. doctr/models/detection/fast/base.py +17 -5
  32. doctr/models/detection/fast/pytorch.py +21 -8
  33. doctr/models/detection/linknet/base.py +17 -5
  34. doctr/models/detection/linknet/pytorch.py +7 -0
  35. doctr/models/detection/predictor/pytorch.py +40 -0
  36. doctr/models/detection/zoo.py +4 -0
  37. doctr/models/factory/hub.py +5 -2
  38. doctr/models/formula/__init__.py +2 -0
  39. doctr/models/formula/formulanet/__init__.py +2 -0
  40. doctr/models/formula/formulanet/base.py +70 -0
  41. doctr/models/formula/formulanet/pytorch.py +587 -0
  42. doctr/models/formula/predictor/__init__.py +1 -0
  43. doctr/models/formula/predictor/pytorch.py +132 -0
  44. doctr/models/formula/zoo.py +102 -0
  45. doctr/models/kie_predictor/base.py +7 -0
  46. doctr/models/kie_predictor/pytorch.py +47 -6
  47. doctr/models/layout/lw_detr/pytorch.py +150 -93
  48. doctr/models/layout/predictor/pytorch.py +32 -0
  49. doctr/models/layout/zoo.py +4 -0
  50. doctr/models/modules/transformer/pytorch.py +151 -31
  51. doctr/models/predictor/base.py +283 -7
  52. doctr/models/predictor/pytorch.py +53 -98
  53. doctr/models/preprocessor/pytorch.py +13 -11
  54. doctr/models/reading_order/base.py +720 -260
  55. doctr/models/recognition/core.py +14 -1
  56. doctr/models/recognition/crnn/pytorch.py +37 -11
  57. doctr/models/recognition/master/base.py +4 -1
  58. doctr/models/recognition/master/pytorch.py +83 -20
  59. doctr/models/recognition/parseq/base.py +4 -1
  60. doctr/models/recognition/parseq/pytorch.py +123 -22
  61. doctr/models/recognition/predictor/_utils.py +131 -14
  62. doctr/models/recognition/predictor/pytorch.py +67 -11
  63. doctr/models/recognition/sar/pytorch.py +20 -6
  64. doctr/models/recognition/utils.py +75 -43
  65. doctr/models/recognition/viptr/pytorch.py +37 -11
  66. doctr/models/recognition/vitstr/base.py +4 -1
  67. doctr/models/recognition/vitstr/pytorch.py +7 -3
  68. doctr/models/recognition/zoo.py +31 -3
  69. doctr/models/table_structure/grid.py +430 -0
  70. doctr/models/table_structure/predictor/pytorch.py +152 -1
  71. doctr/models/table_structure/tablecenternet/base.py +206 -16
  72. doctr/models/table_structure/tablecenternet/pytorch.py +8 -5
  73. doctr/models/table_structure/zoo.py +5 -0
  74. doctr/models/utils/pytorch.py +73 -16
  75. doctr/models/zoo.py +53 -4
  76. doctr/transforms/functional/base.py +6 -0
  77. doctr/transforms/functional/pytorch.py +134 -6
  78. doctr/transforms/modules/base.py +17 -3
  79. doctr/transforms/modules/pytorch.py +185 -4
  80. doctr/utils/data.py +20 -9
  81. doctr/utils/fonts.py +17 -9
  82. doctr/utils/geometry.py +36 -14
  83. doctr/utils/metrics.py +143 -13
  84. doctr/utils/multithreading.py +122 -2
  85. doctr/utils/visualization.py +11 -7
  86. doctr/version.py +1 -1
  87. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/METADATA +54 -224
  88. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/RECORD +93 -81
  89. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/WHEEL +1 -1
  90. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/entry_points.txt +0 -0
  91. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/licenses/LICENSE +0 -0
  92. {python_doctr-1.1.0.dist-info → python_doctr-1.2.0.dist-info}/top_level.txt +0 -0
  93. {python_doctr-1.1.0.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 ..utils import merge_multi_strings
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 aspect_ratio > max_ratio:
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
- # Compute start columns for each split
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
- merged_text = merge_multi_strings(list(text_parts), overlap_ratio, last_overlap)
134
- merged_conf = sum(confidences) / len(confidences) # average confidence
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
- from collections.abc import Sequence
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,9 +103,30 @@ 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
 
@@ -76,10 +138,4 @@ class RecognitionPredictor(nn.Module):
76
138
  raw = [self.model(batch, return_preds=True, **kwargs)["preds"] for batch in processed_batches]
77
139
 
78
140
  # Process outputs
79
- out = [charseq for batch in raw for charseq in batch]
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
- probs = torch.gather(torch.softmax(logits, -1), -1, out_idxs.unsqueeze(-1)).squeeze(-1)
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.numpy().clip(0, 1).tolist()))
356
+ return list(zip(word_values, probs))
343
357
 
344
358
 
345
359
  def _sar(
@@ -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 Hamming
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,57 +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
  >>> from doctr.models.recognition.utils import merge_strings
24
- >>> merge_strings('abcd', 'cdefgh', 0.5)
25
+ >>> merge_strings('abcdX', 'Xdefgh', 0.5)
25
26
  'abcdefgh'
26
27
  >>> merge_strings('abcdi', 'cdefgh', 0.5)
27
28
  'abcdefgh'
28
29
  """
29
- seq_len = min(len(a), len(b))
30
- if seq_len <= 1: # One sequence is empty or will be after cropping in next step, return both to keep data
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
31
32
  return a + b
32
33
 
33
34
  a_crop, b_crop = a[:-1], b[1:] # Remove last letter of "a" and first of "b", because they might be cut off
34
35
  max_overlap = min(len(a_crop), len(b_crop))
35
-
36
- # Compute Hamming distances for all possible overlaps
37
- scores = [Hamming.distance(a_crop[-i:], b_crop[:i], processor=None) for i in range(1, max_overlap + 1)]
38
-
39
- # Find zero-score matches
40
- zero_matches = [i for i, score in enumerate(scores) if score == 0]
41
-
42
- expected_overlap = round(len(b) * overlap_ratio) - 3 # adjust for cropping and index
43
-
44
- # Case 1: One perfect match - exactly one zero score - just merge there
45
- if len(zero_matches) == 1:
46
- i = zero_matches[0]
47
- return a_crop + b_crop[i + 1 :]
48
-
49
- # Case 2: Multiple perfect matches - likely due to repeated characters.
50
- # Use the estimated overlap length to choose the match closest to the expected alignment.
51
- elif len(zero_matches) > 1:
52
- best_i = min(zero_matches, key=lambda x: abs(x - expected_overlap))
53
- return a_crop + b_crop[best_i + 1 :]
54
-
55
- # Case 3: Absence of zero scores indicates that the same character in the image was recognized differently OR that
56
- # the overlap was too small and we just need to merge the crops fully
57
- if expected_overlap < -1:
58
- return a + b
59
- elif expected_overlap < 0:
60
- return a_crop + b_crop
61
-
62
- # Find best overlap by minimizing Hamming distance + distance from expected overlap size
63
- combined_scores = [score + abs(i - expected_overlap) for i, score in enumerate(scores)]
64
- best_i = combined_scores.index(min(combined_scores))
65
- return a_crop + b_crop[best_i + 1 :]
66
-
67
-
68
- def merge_multi_strings(seq_list: list[str], overlap_ratio: float, last_overlap_ratio: float) -> str:
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:
69
84
  """
70
85
  Merges consecutive string sequences with overlapping characters.
71
86
 
@@ -73,13 +88,15 @@ def merge_multi_strings(seq_list: list[str], overlap_ratio: float, last_overlap_
73
88
  seq_list: list of sequences to merge. Sequences need to be ordered from left to right.
74
89
  overlap_ratio: Estimated ratio of overlapping letters between neighboring strings.
75
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`
76
93
 
77
94
  Returns:
78
95
  A merged character sequence
79
96
 
80
97
  >>> from doctr.models.recognition.utils import merge_multi_strings
81
- >>> merge_multi_strings(['abc', 'bcdef', 'difghi', 'aijkl'], 0.5, 0.1)
82
- 'abcdefghijkl'
98
+ >>> merge_multi_strings(['abcdX', 'XdefX', 'XefghX', 'Xijk'], 0.5, 0.5)
99
+ 'abcdefghijk'
83
100
  """
84
101
  if not seq_list:
85
102
  return ""
@@ -87,5 +104,20 @@ def merge_multi_strings(seq_list: list[str], overlap_ratio: float, last_overlap_
87
104
  for i in range(1, len(seq_list)):
88
105
  text_b = seq_list[i]
89
106
  ratio = last_overlap_ratio if i == len(seq_list) - 1 else overlap_ratio
90
- result = merge_strings(result, text_b, ratio)
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)
91
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]]