Document, Diagram, and Interface Understanding › The Classical Pipeline: Detection, Recognition, Ordering

Michael BrenndoerferDecember 1, 202614 min read
Language AI HandbookAll chapters
Part 52 of 67Omni-Modal and Embodied Language Systems
Chapter 401Document, Diagram, and Interface Understanding › The Classical Pipeline: Detection, Recognition, Ordering
Reading section 3 of 11 · The Classical Pipeline: Detection, Recognition, Ordering · 14 minSection 3 of 11 · 14 min

Section 3 of 11 · 14 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Detection returns regions such as boxes or quadrilaterals. Recognition returns a text sequence for a region. Ordering assigns a permutation or a partial order to multiple regions. A small detection error can clip a letter, but a correctly recognized word can also land in the wrong output column. Train and test at the level you use at deployment: a line recognizer, word bounding boxes, and paragraph regions support different checks.

DBNet illustrates a detector with a learned differentiable binarization step. Applying CTC to a recognizer is a separate choice. CTC sums the probabilities of frame-level alignments that collapse to the target string. Its collapse operation first merges consecutive identical symbols and then removes blanks. For example, l, blank, l yields two letters; l, l yields one. This ordering matters for repeated characters in strings such as bill. The loss does not require a separate per-frame character label, though it does require correctly transcribed training sequences.

The fixture draws text first and retains each bounding box from the drawing library. The box is an annotation for a text span, not the result of a detector. Simulated recognition returns the same geometry and corrupts one string deliberately. A confidence score from a real recognizer would require calibration; our fixture attaches no learned confidence.

The interface between detection and recognition

Detection asks where text is located. Recognition asks which character sequence belongs to a selected region. The two stages can be trained or evaluated jointly, but their outputs remain separately inspectable. An axis-aligned bounding box can be convenient when lines are horizontal and separated. A rotated or curved line can need a polygon, a centerline or a rectified crop. Feeding a narrow crop of a skewed line into a recognizer can remove the parts of letters that distinguish similar characters. An oversized crop can add text from a neighboring line. The same recognizer can appear better or worse depending on the localization and crop preparation it consumes.

Detecting each word as a separate region makes it easy to attach evidence to a short field value. Detecting a whole line instead can provide useful recognition context. A line region may include a row name and its value together, which also changes what the stage needs to learn about separators and reading order. Evaluation should specify whether one large box covering several words counts as a single correct line, several missed word detections or an acceptable alternative. Without the annotation convention, an overlap number cannot tell you what type of detection the system improved.

For an axis-aligned rectangle with coordinates (x0,y0,x1,y1)(x_0,y_0,x_1,y_1), computing its overlap with another region requires identifying the shared extent on each axis. The shared width is the positive part of the lesser right edge minus the greater left edge. The analogous height uses bottom and top edges. Their product is the intersection area. The union is the sum of the two areas minus their intersection. This subtracts the shared area once after the individual areas counted it twice. A shifted equal-size box can retain some intersection while its transcribed text stays the same, and the inverse is possible as the invoice shows. This makes overlap and recognition checks useful for different parts of a fixture.

An evaluation has another choice even after choosing IoU. If two proposed boxes overlap the same reference, the rule for assigning candidate-to-reference pairs affects which boxes count as matched. One-to-one matching avoids tallying repeated proposals as repeated true detections of one field. A detection-confidence threshold can also change the number of proposals before this assignment. The synthetic invoice uses known identities and compares matching records directly. Its mean IoU is neither a detector average precision curve nor the result of uncertain region matching. This scoped evaluation isolates a recognition error while keeping geography fixed.

Recognition converts a crop into text, with an alphabet or tokenizer that defines which labels are legal. A sequence with a repeated character needs a representation capable of distinguishing adjacent occurrences. When a CTC aligner uses blank symbols and collapse, successive duplicates in the raw alignment are merged before removing blanks. A blank between two identical character labels can therefore preserve both. The training label is still the intended text sequence. The available frame positions and reading direction define possible alignments, and a region where a required sequence cannot be aligned poses a different problem from a region with a plausible but incorrect letter.

A greedy path chooses the highest-scored raw label at each frame and collapses the resulting path. A search over output label sequences may instead aggregate probability mass across several paths which collapse to the same text. Those operations optimize different objects. In a real OCR audit, preserve which decoder produced each hypothesis, the score's interpretation, and any confidence threshold used to reject the result. The short Python examples use declared labels and records. They do not estimate the character probabilities or calibrate a recognition system.

Measuring recognition at the unit the user needs

A character-level discrepancy can be small and still invalidate a field. For a monetary amount, confusing a digit with a letter often prevents numeric parsing. In a line of ordinary prose, one character substitution may still leave the meaning recoverable. A benchmark using exact field matches will treat the difference in the amount as an error even when a character agreement fraction is high. That metric suits an application requiring exact values, while a character error metric helps diagnose the type and frequency of transcription mistakes.

When transcriptions have insertions and deletions, comparing characters at the same offsets can overcount mismatches after the first gap. An edit-distance comparison can align shifts when reporting error rates, given a clear convention for normalization and symbols. For equal-length money strings with a single known substitution, aligned comparison is enough to show which position differed. Restrict that shortcut to equal-length strings and state the fixture condition. A whole-page character error rate would require aggregating according to the benchmark's reference text and denominator. Whitespace normalization, case folding and punctuation handling are part of that definition rather than harmless cleanup.

Numeric parsing adds its own decision boundary. A text recognizer can return a plausible string while the application rejects it because currency, decimal separators or formatting disagree with the schema. Some numeric strings are genuinely ambiguous under different locale conventions. Define which conventions are supported before accepting formatted values. When the output is invalid under the declared schema, preserve the original text for diagnosis and treat the parsed numeric value as unavailable. Reconciliation over correct decimal quantities is a separate operation on verified values, not an excuse to reinterpret malformed strings.

If a reader reports “the total shown on the page,” the evidence should point to the printed total. If the reader instead computes a total from rows, the evaluation should describe whether printed fees and taxes enter the calculation and whether the rows were completely extracted. A printed value and a computed value can differ. Keeping their provenance separate preserves the ability to investigate rounding and missing fields. In the invoice the amount due is available as printed even though one line item cannot be parsed under the fixture's schema. That is partial success under an explicit question, with a separate unavailable validation step.

Separating alignment collapse from a transcription comparison

The following alignments are declared strings, with a period standing for a blank. Collapse adjacent repeated labels in the raw path, then discard blanks. With no intervening blank the two l labels compress to one. With an intervening blank they survive as a repeated letter.

PythonIn [2]
CollapseExpand
from itertools import groupby


def collapse_labels(path, blank="."):
    return "".join(label for label, _ in groupby(path) if label != blank)


alignment_paths = ("bbaalll", "bbaall.ll", "..bbaall.ll..")
collapsed = {path: collapse_labels(path) for path in alignment_paths}
assert tuple(collapsed.values()) == ("bal", "ball", "ball")
ConsoleOut [3]
CollapseExpand
bbaalll → bal
bbaall.ll → ball
..bbaall.ll.. → ball

This operation maps an alignment to an output. During training, the sequence label participates in the likelihood of all compatible alignments. In this example each raw path is fixed by hand. Collapsing one path teaches the representation and the significance of the blank, without producing recognition confidences.

PythonIn [5]
CollapseExpand
from dataclasses import dataclass, replace
from decimal import Decimal

import numpy as np
from matplotlib import font_manager
from PIL import Image, ImageDraw, ImageFont


@dataclass(frozen=True)
class Box:
    key: str
    value: str
    xyxy: tuple[int, int, int, int]

    @property
    def center(self):
        x0, y0, x1, y1 = self.xyxy
        return ((x0 + x1) / 2, (y0 + y1) / 2)


def render_invoice():
    img = Image.new("RGB", (670, 480), "white")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype(font_manager.findfont("DejaVu Sans"), 21)
    invoice = (
        ("title", "NORTH DUNE SUPPLY", 40, 25),
        ("id", "Invoice ND-42", 40, 61),
        ("desc-header", "Item", 40, 104),
        ("qty-header", "Qty", 345, 104),
        ("amount-header", "Amount", 470, 104),
        ("r1-item", "Widget", 40, 145),
        ("r1-qty", "10", 345, 145),
        ("r1-amount", "120.00", 470, 145),
        ("r2-item", "Bolt", 40, 190),
        ("r2-qty", "50", 345, 190),
        ("r2-amount", "75.50", 470, 190),
        ("r3-item", "Gasket", 40, 235),
        ("r3-qty", "5", 345, 235),
        ("r3-amount", "32.10", 470, 235),
        ("subtotal-key", "Subtotal", 345, 295),
        ("subtotal", "227.60", 470, 295),
        ("tax-key", "Tax (20%)", 345, 337),
        ("tax", "45.52", 470, 337),
        ("total-key", "Total", 345, 379),
        ("total", "273.12", 470, 379),
        ("note", "Reference: ND-42", 40, 433),
    )
    boxes = []
    for key, value, x, y in invoice:
        draw.text((x, y), value, fill="black", font=font)
        boxes.append(Box(key, value, draw.textbbox((x, y), value, font=font)))
    return img, boxes


def mock_recognizer(boxes):
    return [
        replace(box, value="75.S0") if box.key == "r2-amount" else box
        for box in boxes
    ]


def pixel_iou(a, b):
    x0, y0 = max(a[0], b[0]), max(a[1], b[1])
    x1, y1 = min(a[2], b[2]), min(a[3], b[3])
    inter = max(0, x1 - x0) * max(0, y1 - y0)
    union = (
        (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter
    )
    return inter / union if union else 0.0


invoice, boxes = render_invoice()
proposed = mock_recognizer(boxes)
ConsoleOut [6]
CollapseExpand
Exact transcription matches: 20/21
Mean box IoU: 1.000
Row 2 localized text: 75.S0

The localized box has IoU one because recognition never changes any box. The row 2 string still reads 75.S0, which is unusable as money under the fixture's decimal format. A detection metric that measures only box overlap misses that error. IoU is intersection area divided by union area; here coordinates are axis-aligned pixel edges with the top-left origin. A perfect overlap also says nothing about whether the selected region is sufficient to justify a downstream answer.

VisualizationOut [7]
CollapseExpand
An invoice shows line-item, subtotal, tax and total amounts. The second item amount has a dashed box.
Generated invoice and its retained text boxes. A dashed outline marks the amount with a deliberately corrupted transcription. The printed invoice pixels still show the correct characters.

One corruption and one geometric shift

The known corrupted amount lets us compare two distinct measurement changes using the same reference box. Keep the corrupt recognized string at the original box for the first case. For the second case keep the correct string and move its box horizontally by half the original width, preserving its height and size. Use the same reference in both comparisons.

PythonIn [8]
CollapseExpand
target_amount = next(box for box in boxes if box.key == "r2-amount")
read_amount = next(box for box in proposed if box.key == "r2-amount")
left, top, right, bottom = target_amount.xyxy
half_width = (right - left) / 2
shifted_box = (left + half_width, top, right + half_width, bottom)
evidence_checks = [
    ("wrong string", read_amount.value, read_amount.xyxy),
    ("shifted region", target_amount.value, shifted_box),
]
outcomes = [
    (
        name,
        candidate == target_amount.value,
        pixel_iou(target_amount.xyxy, region),
    )
    for name, candidate, region in evidence_checks
]
different_positions = [
    index
    for index, (true, got) in enumerate(
        zip(target_amount.value, read_amount.value, strict=True), start=1
    )
    if true != got
]
assert different_positions == [4]
assert outcomes[0][1:] == (False, 1.0)
assert outcomes[1][1] and np.isclose(outcomes[1][2], 1 / 3)
ConsoleOut [9]
CollapseExpand
wrong string: exact text False; box IoU 1.000
shifted region: exact text True; box IoU 0.333
Substituted text positions (starting at 1): [4]

With only half the width overlapping, the shifted equal-area rectangles have intersection half their area and union one-and-a-half times that area. The ratio is one third. The correct string survives this artificial shift because it is held fixed by design. A real detector moving a crop upstream of recognition could change both the recognized text and the evidence geometry. Pairing outcomes here isolates why neither exact text nor exact region should stand alone in a grounded extraction experiment.

Reading order on a two-column fixture

A row-first order sorts by top coordinate, then horizontal coordinate. This is appropriate for many line-item rows. A two-column report often has a different convention: finish one column before reading the other. The recursive XY-cut baseline searches for an entirely clear gap and splits before recurring. The implementation below first looks for a horizontal gap and then tests a vertical gap. If both directions have wide whitespace, that priority encodes an assumption. The fixture makes the horizontal break 15 pixels wide and the vertical break 50 pixels wide, with a threshold of 20.

PythonIn [10]
CollapseExpand
def row_first(boxes):
    return [
        box.key for box in sorted(boxes, key=lambda b: (b.xyxy[1], b.xyxy[0]))
    ]


def xy_cut(boxes, min_gap=20):
    for d in (1, 0):
        ordered = sorted(boxes, key=lambda b: b.xyxy[d])
        gaps = [
            right.xyxy[d] - max(b.xyxy[d + 2] for b in ordered[: i + 1])
            for i, right in enumerate(ordered[1:])
        ]
        if gaps and max(gaps) >= min_gap:
            boundary = gaps.index(max(gaps)) + 1
            return xy_cut(ordered[:boundary], min_gap) + xy_cut(
                ordered[boundary:], min_gap
            )
    return row_first(boxes)


columns = (
    Box("L1", "L1", (10, 10, 40, 27)),
    Box("L2", "L2", (10, 42, 40, 59)),
    Box("R1", "R1", (90, 10, 120, 27)),
    Box("R2", "R2", (90, 42, 120, 59)),
)
expected = ["L1", "L2", "R1", "R2"]
row_order, cut_order = row_first(columns), xy_cut(columns)
ConsoleOut [11]
CollapseExpand
Intended order: ['L1', 'L2', 'R1', 'R2']
Row-first: ['L1', 'R1', 'L2', 'R2']
XY-cut: ['L1', 'L2', 'R1', 'R2']

In this example row-first interleaves the columns. XY-cut uses the wider vertical gutter first, then orders the text within each region. Figures that cross a gutter, sidebars and footnote callouts can break this assumption even when all boxes are correct. For release evaluation, label the precedence constraints the downstream reader needs. If two independent regions have no required order, metric design can accept either ordering rather than forcing an arbitrary permutation.

VisualizationOut [12]
CollapseExpand
Boxes L1 and L2 form the left column. R1 and R2 form the right column. A vertical dotted line runs through the gutter.
Four boxes in two columns show why sorting on the row first interleaves content. At the chosen threshold the vertical gutter provides the first split.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy