Skip to content

[models] Resolve ambiguous overlaps of split word crops by reading the region of each pair - #2231

Merged
felixdittrich92 merged 4 commits into
mindee:mainfrom
pbstriker38:fix/split-crop-merge-ambiguity
Nov 23, 2026
Merged

felixdittrich92 merged 4 commits into
mindee:mainfrom
pbstriker38:fix/split-crop-merge-ambiguity

Conversation

@pbstriker38

@pbstriker38 pbstriker38 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2229 (cross-linked as felixdittrich92/OnnxTR#129). Follow-up to #2153.

Rebuilt on the per-pair approach proposed in review: the branch is rebased on main, starts from your prototype commit
(same code, with a message describing the change), and adds tests, docs and a comment on top. Thanks for the prototype
and the benchmark!

The bug

RecognitionPredictor splits word crops wider than critical_ar (8:1) into overlapping parts, reads each part, and
joins the readings with merge_strings. Across a repeated stretch, a run of one character (0000001) or a repeating
pattern (EME in ENDORSEMENT, ICI in PARTICIPANTS), the overlap matches exactly at several lengths, and
merge_strings keeps the one closest to len(b) * overlap_ratio - 2. That estimate is sometimes a character off, so
the stretch gains or loses part of itself, even when every part is read right:

from doctr.models.recognition.utils import merge_strings, merge_multi_strings

merge_strings("WARMUP-0000", "-0000001", 0.5)  # 'WARMUP-00000001'; the text is 'WARMUP-0000001'
merge_multi_strings(["WARMUP", "MUP-0000", "-0000001"], 0.5, 0.519)  # 'WARMUP-00000001'
merge_strings("ENDORSEMEN", "SEMENT", 0.5)  # 'ENDORSEMEMENT'
merge_strings("PARTICIP", "TICIPANTS", 0.3)  # 'PARTICICIPANTS'

The fix

  1. ambiguous_overlaps finds the pairs of neighbouring parts whose readings overlap exactly at several lengths
    (exact_overlaps), where merge_strings picked one of them, and cuts the region the two parts cover (about 9:1).
  2. RecognitionPredictor reads all those regions in one extra batch.
  3. resolve_overlap scores each exact length by the edit distance of its merge to the region reading, plus how far
    apart the overlapping characters sit in the two parts when each part's characters are spread evenly over its width.
    The best length replaces merge_strings' one only if its merge is at most 2 edits from the region reading and its
    score is better by more than 0.25.
  4. merge_multi_strings / remap_preds take the resolved lengths through a new overlaps argument; every other pair
    is aligned by merge_strings as before.

A region reading at least model.max_length - 2 characters long may have been cut short by the decoder and doesn't
decide. The models are trained on words of up to max_length - 2 (PARSeq, MASTER, ViTSTR), max_length - 1 (SAR) or
max_length characters (CRNN, VIPTR, whose CTC targets have no <eos>), so that is exact or more cautious for each.

This replaces the first version of this PR, which re-read the whole crop and chose among merges of the whole crop.
Squeezed to the model input, a crop that wide read too unreliably (see the review); the region of a pair is far less
squeezed, and the character positions catch what its reading gets wrong.

API

  • RecognitionPredictor(..., resolve_ambiguous_overlaps=True), also an attribute; False gives main's behaviour
    exactly.
  • New: exact_overlaps (recognition/utils.py), ambiguous_overlaps and resolve_overlap
    (recognition/predictor/_utils.py); an optional overlaps argument on merge_multi_strings and remap_preds.
  • The forward pass of RecognitionPredictor._predict moved into _read, so the regions go through the same path.
  • A "Very wide crops" section in the OCR predictor user guide.

Evidence

Rendered IDs and words, all 7 pretrained recognizers

Synthetic IDs (letters, digits, - and /) and long words rendered with Pillow in 5 fonts (DejaVu Sans/Serif,
Liberation Sans/Mono, Noto Sans Mono), crops 30–56 px high, a third of them blurred, all wider than 8:1. Exact-match
counts on main → this PR, with the first version of this PR for comparison:

arch IDs with a run (300) first version IDs too long to read whole (150) first version
parseq 243 → 277 (+34 / −0) +46 / −4 122 → 133 (+12 / −1) +0 / −0
vitstr_small 238 → 275 (+37 / −0) +42 / −1 96 → 102 (+6 / −0) +0 / −0
master 34 → 37 (+3 / −0) +23 / −3 15 → 16 (+1 / −0) +0 / −0
sar_resnet31 205 → 227 (+26 / −4) +16 / −2 69 → 71 (+5 / −3) +0 / −0
crnn_vgg16_bn 253 → 289 (+36 / −0) +8 / −0 136 → 146 (+10 / −0) +0 / −0
crnn_mobilenet_v3_large 245 → 277 (+33 / −1) +2 / −0 125 → 137 (+12 / −0) +0 / −0
viptr_tiny 247 → 281 (+34 / −0) +6 / −0 134 → 142 (+9 / −1) +0 / −0
  • In total +258 / −10 against +143 / −10 for the first version, consistent with your benchmark.
  • No reading changes on IDs without runs (174), on long words with double letters (146: accommodation,
    MISSISSIPPI, www.committee.net, …) or on words with a periodic stretch (44: PARTICIPANTS, ENDORSEMENTS, …), for
    any arch. 4–11 of the 174 IDs and about a fifth of the double-letter words get a region read.
  • The first version did better on parseq, ViTSTR and MASTER for IDs with a run, but at the cost of breaks.

Private documents

On 578 pages of private scanned and born-digital business forms (665 crops wider than 8:1), crnn_vgg16_bn and
parseq read 47–48 regions, in 45–46 crops, and change no word. These documents hold few runs, so this only shows the change is safe
there.

Stand-in recognizer (every part and region read exactly)

Ten strings, seven with a run or repeating pattern, at every size the predictor splits for heights 10–47 px and
characters 0.4–0.8 of the height wide: 213 of 2,130 crops misjoin on main, 61 with this PR, and none is broken. The
61 are the trade-off you described. For example, the 2 parts of a 210 × 24 crop of U-0000000008911 each cut a zero in
half: the exact region reading points at an overlap of 5, the evenly spread positions at 4, merge_strings picked 4,
and the tie keeps it. A character cut in half at a part's edge shifts the evenly spread positions by about half a
character; refining the position term for that might be a follow-up.

Tests

  • tests/common/test_models_recognition_utils.py: exact_overlaps, including a part read entirely inside a run, and
    merge_multi_strings with an imposed overlap, which falls back to merge_strings when it is no longer an exact
    overlap of the merge so far.
  • tests/common/test_models_recognition_predictor.py:
    • remap_preds with overlaps, applied to their own crop only;
    • ambiguous_overlaps on a crop split into 6 parts: the pairs, their regions, ratios (the last pair's included) and
      offsets; nothing for a pair where merge_strings picks no exact length, or for a crop whose parts don't match its
      split;
    • resolve_overlap: the two signals agreeing, and the margin; a reading that matches merge_strings' length; the
      2-edit limit from both sides; the tie above, which keeps merge_strings' length even with no margin; one exact
      length only.
  • tests/pytorch/test_models_recognition_pt.py: one parametrized test of RecognitionPredictor with a scripted
    recognizer. A run split across parts is resolved with one extra batch of 1 region, and the confidence stays the
    parts'. A region reading of max_length - 2 characters keeps merge_strings' length and one of max_length - 3
    decides, and a model without max_length is trusted. Nothing is read again with resolve_ambiguous_overlaps=False,
    without an ambiguous pair, or for a crop that is not split.

They run in 0.02 s and cover the added code fully (82/82 statements, 32/32 branches). Of 26 faults injected one at a
time, 25 are caught: among them never resolving, dropping the position term, the offset, the 2-edit limit or the margin,
moving the edit limit or the cut-short guard by one either way, breaking ties away from merge_strings' length, a wrong
region, offset or last-pair ratio, missing a dropped part, applying one crop's overlaps to every crop, imposing a length
without checking it or off by one, exact_overlaps dropping its longest length, changing the confidence when a
region is read, and ignoring the switch. The one left compares the margin with >=, which differs only when the
score gap equals the margin exactly.

make style and make quality (ruff + mypy) are clean; the recognition test files pass.

🤖 Generated with Claude Code

@felixdittrich92 felixdittrich92 self-assigned this Nov 19, 2026
@felixdittrich92 felixdittrich92 added this to the 1.2.0 milestone Nov 19, 2026
@felixdittrich92 felixdittrich92 added type: enhancement Improvement module: models Related to doctr.models ext: tests Related to tests folder topic: text recognition Related to the task of text recognition labels Nov 19, 2026

@felixdittrich92 felixdittrich92 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot for this: the analysis is thorough, the stand-in "spelling" recognizer is a great test tool, and the core idea (only an extra reading can count a repeated stretch) is right. I benchmarked it at scale, and I'd like to propose a change of approach that came out clearly better. I pushed a prototype you can test directly (details at the end).

Benchmark

All 7 pretrained recognizers, 24,326 crops wider than 8:1:

  • real: every such crop of SROIE (13,623 lines), FUNSD (194), CORD (9);
  • synthetic (30 fonts, 16–64 px, noise / JPEG / blur / spacing): 3,000 IDs with runs or patterns, 1,500 without, 800 separator rows, 1,500 amounts / dates / phone numbers / IBANs, 2,500 long words, 1,200 URLs.

Findings on this PR:

  • The whole reading is often too squeezed to trust. The predictor keeps the aspect ratio, so a 20:1 crop reaches the model as a 128×6 px strip. On a real receipt, parseq turned a row of 24 * (right on main) into 20–21, from a whole reading 'insssesemmunussommuna' (conf 0.68). It shares no char with any candidate, so the edit distance just picks the shortest allowed one. Clean readings can also be confidently wrong: GSTID:000220499968 is read whole as GSTID:0000220499968 (conf 1.00).
  • Real data: across 7 archs, +12/−11 on SROIE (parseq +2/−7).
  • Synthetic: many breaks for the transformer decoders (parseq −64, vitstr −44, master −85).

Proposed approach: per-pair region reading + geometry

  1. Find the pairs of neighbouring parts whose readings overlap exactly at several lengths (and where merge_strings picked one of them).
  2. Read the region those two parts cover (≈ 9:1, far less squeezed than the whole crop), all pairs in one extra batch.
  3. Score each exact overlap length n by two independent signals: the edit distance of its merge to the region reading, plus the mean distance (in chars) between the overlapping chars' positions in the two parts when each part's chars are spread evenly over its width. The part offsets are known exactly from the split.
  4. Use the best length only if its merge is ≤ 2 edits from the region reading and its score beats merge_strings' length by > 0.25. Otherwise keep merge_strings.

Fixed / broken vs main, measured with the actual predictor:

arch this PR proposed
parseq +188 / −64 +211 / −27
crnn_vgg16_bn +49 / −0 +208 / −11
crnn_mobilenet_v3_large +22 / −0 +178 / −10
vitstr_small +111 / −44 +162 / −25
sar_resnet31 +45 / −4 +136 / −29
master +91 / −85 +94 / −38
viptr_tiny +43 / −1 +211 / −14
total +549 / −198 +1,200 / −154
real (SROIE) +12 / −11 +20 / −1 (≥ 0 for every arch)
  • Validated: tuned on half of the synthetic crops, same result on the other half (+596/−73 vs +587/−79).
  • Real documents: on 149 pages, parseq changes no word (the * regression is gone), and crnn changes 1 (an edge-cut * row).
  • Cost: +5–12 % recognition time on split crops; end-to-end within noise.
  • Simpler: no whole-crop reading, so no confidence floor and no ±1-length window. No lengthen_only and no model imports in the predictor (it is arch-agnostic and works for CTC models without special-casing). No candidate search with a cap. The max_length guard reduces to one comparison.

Things I tried that did not beat it, to save you iterations:

  • changing the expected overlap (- 2 → - 1.5 / - 1): −12 to −33 per arch;
  • lengthen-only everywhere: keeps parseq's real-data breaks, which are over-counts;
  • geometry alone (no extra read): +943/−91 in total, a decent fallback;
  • requiring the whole and the region readings to agree: safe, but fewer fixes at double the cost;
  • giving the geometry less weight than the reading: 2–3× more breaks, because real readings are often one char off.

The one trade-off is that with a perfect reader (your stand-in) it fixes 330 of 529 misjoins rather than all of them, since geometry deliberately holds back a reading that disagrees with it. Your stand-in tests would need to reflect that. On real models this is what keeps the breaks down.

Prototype to test

Branch: https://github.com/felixdittrich92/doctr/tree/proto-split-merge-geo
Diff against main: main...felixdittrich92:doctr:proto-split-merge-geo

git fetch https://github.com/felixdittrich92/doctr.git proto-split-merge-geo
git checkout FETCH_HEAD

It is one commit on top of main (~150 lines in 3 files):

  • doctr/models/recognition/utils.py: exact_overlaps, and an optional overlaps argument on merge_multi_strings to impose known overlap lengths;
  • doctr/models/recognition/predictor/_utils.py: ambiguous_overlaps (finds the pairs and cuts their regions), resolve_overlap (the scoring above), and remap_preds passing the overlaps through;
  • doctr/models/recognition/predictor/pytorch.py: the forward pass moved into _read, plus RecognitionPredictor(..., resolve_ambiguous_overlaps=True). Set it to False to get main's behaviour exactly.

It passes ruff and the existing recognition tests, but has no new tests yet. It would be great if you could run it on your ID benchmark and the OnnxTR setup.

Requested changes

  1. Switch to the per-pair region reading + geometry scoring (feel free to take the prototype as a base), or show that it does worse on your data.
  2. Keep the predictor architecture-agnostic: no CTCPostProcessor / SARPostProcessor / VIPTRPostProcessor imports.
  3. Port your tests to it: the merge / remap unit tests, plus the stand-in recognizer tests with expectations adjusted for the geometry term (for example, a reading that is off from the geometry by more than its edit-distance gain keeps merge_strings' length). Also update the description and the "Very wide crops" docs section.

@felixdittrich92

Copy link
Copy Markdown
Collaborator

Please rebase your branch first on main before you apply any further changes :)

@pbstriker38
pbstriker38 force-pushed the fix/split-crop-merge-ambiguity branch from ca4ef89 to 1485688 Compare November 19, 2026 18:27
@pbstriker38 pbstriker38 changed the title [models] Choose ambiguous merges of split word crops by a whole-crop reading [models] Resolve ambiguous overlaps of split word crops by reading the region of each pair Nov 19, 2026
@pbstriker38

Copy link
Copy Markdown
Contributor Author

Thanks a lot for the thorough review and the prototype, the numbers are convincing.

  • Rebased on main.

  • 1. Switched to the per-pair region reading + geometry. The branch now starts from your prototype commit as you pushed it, with tests, docs and a comment on top. On my benchmark (all 7 pretrained recognizers, rendered IDs and words) it gives +258 / −10 against +143 / −10 for the first version. The biggest gains are on CRNN / VIPTR and on IDs too long to read whole, and no reading changes on IDs without runs or on ordinary words with double letters. On 578 pages of private forms, crnn_vgg16_bn and parseq change no word. The table is in the description.

  • 2. Architecture-agnostic: no model imports left. The whole-crop reading, lengthen_only, the confidence floor and the candidate cap are gone with it.

  • 3. Tests ported:

    • unit tests for exact_overlaps, imposed overlaps in merge_multi_strings / remap_preds, ambiguous_overlaps and resolve_overlap, including the margin and a tie;
    • the stand-in recognizer tests, with expectations for the geometry term.

    The description and the "Very wide crops" docs section are updated.

One observation from the stand-in: when a part's edge cuts a character in half, the evenly spread positions are about half a character off. For example, on a 210 × 24 crop of U-0000000008911, an exact region reading and the positions tie, so merge_strings' length is kept. It's in the tests as expected behaviour; refining the position term could be a follow-up if you think it's worth it.

I haven't run it in the OnnxTR setup yet.

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.25%. Comparing base (9553cb6) to head (b7aea90).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #2231   +/-   ##
=======================================
  Coverage   98.24%   98.25%           
=======================================
  Files         181      181           
  Lines       12799    12863   +64     
=======================================
+ Hits        12575    12639   +64     
  Misses        224      224           
Flag Coverage Δ
unittests 98.25% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

felixdittrich92 and others added 3 commits November 19, 2026 13:31
Across a repeated stretch, a run ("0000001") or a pattern ("EME" in
"ENDORSEMENT"), the readings of two neighbouring parts of a split crop
can match exactly at several overlap lengths. merge_strings then keeps
the length nearest to the one the overlap ratio predicts, which is
sometimes a character off, so the stretch gains or loses part of
itself even when both parts are read right.

- exact_overlaps lists the lengths at which two readings match.
- ambiguous_overlaps finds the pairs of parts that match at several
  lengths, one of them the one merge_strings picks, and cuts the region
  of the crop the two parts cover (at most 9:1). _split_starts is
  factored out of _split_horizontally so the regions line up with the
  parts.
- RecognitionPredictor reads all those regions in one extra batch. Its
  forward pass moved into _read so that they take the same path.
- resolve_overlap scores each exact length by the edit distance of its
  merge to the region reading, plus how far apart the overlapping chars
  sit when the chars of each part are spread evenly over its width.
  A length replaces merge_strings' one only if its merge is at most 2
  edits from the region reading and it scores better by more than
  0.25. A region reading of max_length - 2 chars or more may have been
  cut short by the model and does not decide.
- merge_multi_strings and remap_preds take the resolved lengths through
  a new overlaps argument, applied only while they are still exact
  overlaps of the merge so far; every other pair is merged by
  merge_strings as before.
- resolve_ambiguous_overlaps=False, an argument and attribute of
  RecognitionPredictor, keeps the previous behaviour.
- exact_overlaps, and merge_multi_strings imposing known overlap
  lengths: an imposed length that is not an exact overlap of the merge
  so far falls back to merge_strings, and imposing merge_strings' own
  exact lengths merges as it does.
- remap_preds applies the overlaps of each crop to that crop only.
- ambiguous_overlaps finds the pairs whose readings overlap exactly at
  several lengths where merge_strings picks one, and cuts the region
  both parts cover, with the right ratio and offset for the last pair.
- resolve_overlap: the region reading and the char positions agreeing,
  a reading matching merge_strings' length or more than 2 edits off,
  a tie between the two signals, and the margin.
- RecognitionPredictor, with a stand-in recognizer that reads crops
  whose columns spell their chars exactly: a run split across parts is
  resolved with one extra batch; across ten strings at every split
  size, nothing merge_strings merges right is broken, and misjoins
  drop or vanish; a region reading cut short by the model's
  max_length keeps merge_strings' overlap; nothing is resolved with
  the switch off or for crops that are not split.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The user guide says how the parts of a split crop are merged, when a
region is read once more, and how to switch that off. The cut-short
guard's comment says why max_length - 2 suits every recognition model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pbstriker38
pbstriker38 force-pushed the fix/split-crop-merge-ambiguity branch from 1485688 to 9819442 Compare November 19, 2026 21:54

@felixdittrich92 felixdittrich92 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! The implementation looks good to me. The tests (+295 lines) can be cut down a lot without losing anything.

I tried a shorter version: +121 lines, run time 2.8 s → 0.05 s, same coverage of the added code (82/82 statements, 32/32 branches). I injected the faults from your mutation list plus a few more, one at a time: the current tests catch 19 of 21, the shorter ones all 21. The two that get through:

  • exact_overlaps dropping its longest length: no case has a part read entirely inside a run (("000X", "X0000") → [1, 2, 3]).
  • the cut-short guard one char stricter than max_length - 2: only one side of the boundary is tested.

Requested changes:

  1. Replace the spelling stand-in (_spelled, _ColumnsPreProcessor, _SpellingModel, _spelling_predictor, _split_sizes and the 5 tests using them) with a scripted mock and one parametrized test. The unit tests already pin regions, offsets, ratios and scores exactly.
  2. Drop test_merge_multi_strings_imposing_its_own_overlaps and the duplicate cases of test_exact_overlaps / test_merge_multi_strings_overlaps.
  3. Fold test_resolve_overlap_margin into test_resolve_overlap.
  4. Keep comments and docstrings in the tests to the minimum.

tests/pytorch/test_models_recognition_pt.py:

class _ScriptedRecoModel(torch.nn.Module):
    """Reads the crops as the next `readings`: the parts with a confidence of 0.9, the regions of 0.1"""

    def __init__(self, readings: list[str], max_length: int | None) -> None:
        super().__init__()
        self.dummy = torch.nn.Parameter(torch.zeros(1))
        self.readings = iter(readings)
        self.batch_sizes: list[int] = []
        if max_length is not None:
            self.max_length = max_length

    def forward(self, x: torch.Tensor, return_preds: bool = False, **kwargs):
        self.batch_sizes.append(x.shape[0])
        conf = 0.9 if len(self.batch_sizes) == 1 else 0.1
        return {"preds": [(next(self.readings), conf) for _ in range(x.shape[0])]}


# The parts of a 154 x 14 crop of "WARMUP-0000001": merge_strings adds a zero to the run
_PARTS = ["WARMUP-0", "MUP-00000", "-0000001"]


@pytest.mark.parametrize(
    "width, readings, resolve, max_length, text, batch_sizes",
    [
        (154, [*_PARTS, "MUP-0000001"], True, 32, "WARMUP-0000001", [3, 1]),
        (154, [*_PARTS, "MUP-0000001"], True, None, "WARMUP-0000001", [3, 1]),
        # A region reading of `max_length - 2` chars or more may be cut short
        (154, [*_PARTS, "MUP-0000001"], True, 13, "WARMUP-00000001", [3, 1]),
        (154, [*_PARTS, "MUP-0000001"], True, 14, "WARMUP-0000001", [3, 1]),
        (154, [*_PARTS, "MUP-00000001"], True, 32, "WARMUP-00000001", [3, 1]),
        (154, _PARTS, False, 32, "WARMUP-00000001", [3]),
        (154, ["WARMUP-1", "MUP-1234", "-1234567"], True, 32, "WARMUP-1234567", [3]),
        (98, ["WARMUP-0000001"], True, 32, "WARMUP-0000001", [1]),
    ],
)
def test_recognition_predictor_resolve_ambiguous_overlaps(width, readings, resolve, max_length, text, batch_sizes):
    model = _ScriptedRecoModel(readings, max_length)
    predictor = RecognitionPredictor(
        PreProcessor(output_size=(32, 128), batch_size=32, preserve_aspect_ratio=True),
        model,
        resolve_ambiguous_overlaps=resolve,
    )
    assert predictor([np.zeros((14, width, 3), dtype=np.uint8)]) == [(text, 0.9)]
    assert model.batch_sizes == batch_sizes

tests/common/test_models_recognition_utils.py:

@pytest.mark.parametrize(
    "a, b, lengths",
    [
        ("WARMUP-0000", "-0000001", [1, 2, 3]),
        ("PARTICIP", "TICIPANTS", [1, 3]),
        ("000X", "X0000", [1, 2, 3]),
        ("hellowo", "loworld", [2]),
        ("a", "b", []),
    ],
)
def test_exact_overlaps(a, b, lengths):
    assert exact_overlaps(a, b) == lengths


@pytest.mark.parametrize(
    "overlaps, merged",
    [
        (None, "WARMUP-00000001"),
        ({1: 3}, "WARMUP-0000001"),
        # Not an exact overlap of the merge so far: aligned by merge_strings
        ({1: 5}, "WARMUP-00000001"),
    ],
)
def test_merge_multi_strings_overlaps(overlaps, merged):
    assert merge_multi_strings(["WARMUP", "MUP-0000", "-0000001"], 0.5, 0.519, overlaps) == merged

tests/common/test_models_recognition_predictor.py:

def test_remap_preds_overlaps():
    preds = [("WARMUP", 0.9), ("MUP-0000", 0.8), ("-0000001", 0.7)] * 2
    assert remap_preds(preds, [(0, 3, 0.519), (3, 6, 0.519)], 0.5, overlaps={(0, 1): 3}) == [
        ("WARMUP-0000001", 0.7),
        ("WARMUP-00000001", 0.7),
    ]


def test_ambiguous_overlaps():
    crops = [np.zeros((32, 128, 3), dtype=np.uint8), np.arange(10 * 200 * 3, dtype=np.int64).reshape(10, 200, 3)]
    # The second crop is split into 6 parts of 60 columns starting at 0, 30, 60, 90, 120 and 140
    _, crop_map, _ = split_crops(crops, 8, 6, 0.5)
    texts = ["single", "XY-0000", "-000000", "00001AB", "1ABCDEF", "GH00000", "0000000"]

    pairs = ambiguous_overlaps([(text, 0.9) for text in texts], crop_map, crops, 6, 0.5)

    assert [(key, a, b, ratio, offset) for key, _, a, b, ratio, offset in pairs] == [
        ((1, 0), "XY-0000", "-000000", 0.5, 0.5),
        ((1, 1), "-000000", "00001AB", 0.5, 0.5),
        ((1, 4), "GH00000", "0000000", pytest.approx(40 / 60), pytest.approx(20 / 60)),
    ]
    for (_, region, *_), (start, end) in zip(pairs, [(0, 90), (30, 120), (120, 200)]):
        np.testing.assert_array_equal(region, crops[1][:, start:end])
    # merge_strings picks no exact overlap / the parts do not match the split
    assert ambiguous_overlaps([("aaab", 0.9), ("baabbbbb", 0.9)], [(0, 2, 0.2)], [crops[1][:, :90]], 6, 0.5) == []
    assert ambiguous_overlaps([(text, 0.9) for text in texts[:3]], [0, (1, 3, 0.5)], crops, 6, 0.5) == []


@pytest.mark.parametrize(
    "a, b, overlap_ratio, offset, region_text, kwargs, length",
    [
        # The region reading and the char positions agree on 4, merge_strings picks 3 (score gap 1.28)
        ("MUP-00000", "-0000001", 2 / 3, 1 / 3, "MUP-0000001", {}, 4),
        ("MUP-00000", "-0000001", 2 / 3, 1 / 3, "MUP-0000001", {"margin": 1.3}, None),
        ("MUP-00000", "-0000001", 2 / 3, 1 / 3, "MUP-00000001", {}, None),
        ("MUP-00000", "-0000001", 2 / 3, 1 / 3, "XYZ", {}, None),
        # The region reading points at 5, the char positions at merge_strings' 4: a tie keeps it
        ("U-000000000", "00000008911", 78 / 144, 66 / 144, "U-0000000008911", {"margin": 0}, None),
        ("hellowo", "loworld", 0.5, 0.5, "helloworld", {}, None),
        ("aaab", "baabbbbb", 0.2, 0.5, "aaabbbbb", {}, None),
    ],
)
def test_resolve_overlap(a, b, overlap_ratio, offset, region_text, kwargs, length):
    assert resolve_overlap(a, b, overlap_ratio, offset, region_text, **kwargs) == length

The spelling stand-in and its sweep over split sizes give way to a
scripted model and one parametrized predictor test, since the unit
tests pin the regions, offsets, ratios and scores exactly. The
random-input merge test and the duplicate cases are dropped, and the
margin cases join test_resolve_overlap.

The cases now also cover a part read entirely inside a run in
exact_overlaps, the cut-short guard on both sides of max_length - 2,
and the 2-edit limit on both sides.

Co-Authored-By: felix <felixdittrich92@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@pbstriker38

Copy link
Copy Markdown
Contributor Author

Thanks, done in b7aea90 with your shorter suite, credited to you as co-author. One change: in test_resolve_overlap the XYZ row is replaced by two readings, 2 and 3 edits from the merge (MXY-0000001 → 4, MXY-00Z0001 → None), so the 2-edit limit is tested from both sides. With XYZ alone, both >= max_distance and max_distance=3 got through.

I reran my fault list against it, extended with your two and a few boundary faults: 25 of 26 caught, against 20 of 25 for the old tests. The one left compares the margin with >=, which differs only when the score gap equals the margin exactly, so I didn't pin a test on a float. The added code is fully covered (82/82 statements, 32/32 branches), and the new tests run in 0.02 s here. The Tests section of the description is updated.

It's a separate commit on top so you can see the change. Happy to squash it into the test commit if you prefer.

@felixdittrich92 felixdittrich92 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @pbstriker38 👍

@felixdittrich92
felixdittrich92 merged commit fa3cfc0 into mindee:main Nov 23, 2026
60 of 61 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ext: tests Related to tests folder module: models Related to doctr.models topic: text recognition Related to the task of text recognition type: enhancement Improvement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Split-crop merge_strings misjoins readings across repeated characters, including after #2153

2 participants