Document, Diagram, and Interface Understanding
Learn how document, chart, and interface readers separate detection, recognition, and structure to ground answers in verifiable evidence.
Language AI HandbookAll chapters Document, Diagram, and Interface Understanding
An invoice can contain 227.60 and 273.12 in the same column. To answer which is due you must read the digits, associate each number with its row label, and know whether the amount includes tax. A flowchart asks a similar question in a different form: recognizing its labels does little to tell you where a "no" arrow leads. In a settings screenshot, the instruction "enable dark theme" requires both locating a toggle and checking its state. These are separate operations you can evaluate independently.
This chapter follows a synthetic invoice, a small bar chart, a flowchart, and a settings panel. The examples expose their data and geometry, so you can tell where a readout succeeds and where it fails. They use generated objects and deterministic local code, without a paid inference call or a corpus of real company documents.
Why Documents Are Different From Photographs
A photograph can include a sign or a paragraph, but a document usually uses text placement to express relationships. A calculation at the bottom of an invoice has a different role from a line item even if both are amounts and both use the same typeface. A form can place a field value far from the field name, especially when several columns repeat the same labels. A manual can interleave body text, captions, figures, footnotes and running headers. The evidence for how to read one region may be its relation to another region. A pipeline that returns all the right characters can still produce a page which is hard to use because it discarded those relations.
Think of the page as evidence at several scales. At the letter scale, recognition uses shapes and local context to propose characters. At the line scale, positions identify spans and group words into lines. At the region scale, headings, tables and columns impose reading constraints. At the document scale, a caption may define units for a figure and a later clause may change the interpretation of a number. A downstream question chooses which granularity is needed. Locating a signature box and verifying what was signed, for example, are different requests. Choose an intermediate representation that retains the information the final task consumes.
Digital documents often contain text as well as a visual page. Extracted text can be useful evidence when its positions, ordering and encoding are reliable. A scan can have no text layer, or a text layer whose content contradicts the raster because a previous recognizer made a mistake. A page exported from design software can store drawing commands in an order different from its intended reading order. Before diagnosing a multimodal reader, check which input it received and whether the output concerns that representation or the displayed page. Locating a number inside a page layout requires the coordinates for the representation the evaluator is scoring.
Several coordinate frames can coexist during the same evaluation. A raster may use pixel coordinates from the upper left. Some page formats use another origin or a different length unit. A model can receive a resized, padded or cropped version of the rendered page, then report coordinates normalized to that version. Each step changes how evidence boxes need to be interpreted. Store the page index, dimensions, crop origin and rescaling for each image or region passed downstream. Otherwise two boxes with identical four numbers can refer to different places. The examples in this chapter keep coordinates in the declared local fixtures and show explicitly when converting units or reading a different geometric quantity.
The pipeline is auditable at its interfaces. A surprising amount can be learned from a row that stores the crop, proposed text, location, assigned cell and final value together. The OCR text can disagree with what a human sees while the crop is perfect. The transcription can be perfect while the row is wrong. A final question answer can be correct by coincidence when a bad cell happens to contain the same number as the target. Evaluating those cases separately helps identify where a change would matter. It also keeps the benchmark focused on what was observed rather than rewarding an answer merely because it looked plausible.
A document can have several valid local reading sequences
Rows of a simple invoice often read left to right and top to bottom. The body of a two-column article often reads down the first column before the second. In a form, a header can apply to several rows and should be read before its related fields even when their boxes are offset. A document can combine all three conventions on one page. Deciding on a total order before identifying regions makes the choice of ordering axis do more work than it can reliably support. Use the benchmark's actual rule for each document family or preserve a partial order when the task only needs some relations.
A useful evaluation may score required relations instead of matching every adjacent pair. If column members have a unique order but the two column summaries can be presented in either sequence, both complete serializations could satisfy the relevant requirements. Requiring exactly one serialized order would count harmless differences as errors. On the other hand, treating the document as a bag of text would miss wrong header-value associations within each column. State which relations are required and score locality, order or association accordingly. The toy example later has a declared intended total order so we can verify it precisely.
Page headers and footers can need their own handling. Repeated top-of-page words may be useful as section identifiers, yet reading them as though they were part of every paragraph creates duplicates. Page numbers are evidence for navigation but rarely belong in an extracted line item. This distinction matters when building a retrieval index over pages. A text index might want to include a heading as metadata for every passage under that heading, while a user-visible transcript should generally reproduce it at its actual place in the document. Preserve the original evidence and document the intended derived representation.
The Classical Pipeline: Detection, Recognition, Ordering
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 , 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]Expand
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]Expand
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]Expand
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]Expand
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]Expand

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]Expand
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]Expand
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]Expand
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]Expand
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]Expand

Layout Understanding: From Boxes to Structure
Using region labels and page geometry together
A layout annotation describes roles at a chosen granularity. A heading, a paragraph, a table, a caption and a footer can all be represented as regions on one page. A rectangular region of type table gives a useful index into the page even if the system has yet to identify columns, spanning headers or cells. An assessment should inspect both the definition of each class in its annotation guide and any relations the benchmark records. A heading may overlap a larger body region in one hierarchy while being a disjoint box in another. A detected caption can be locally correct while assigned to the wrong figure.
Layout-aware models can represent two-dimensional coordinates alongside recognized text and image features. The LayoutLMv3 example below combines text and image evidence during pretraining. That does not force its output to have a correct reading order. A position embedding can give the model evidence that a region sits near the bottom-right corner, and the recognized word “Total” may help distinguish the value beside it from other amounts. A model can also overuse this association if the evaluation rarely moves the total to a different location. Hold the meaning and numerical content fixed while changing its location when testing generalization to another template.
The region-wise and sequence-wise errors are distinct. Consider four exact blocks labeled A, B, C and D. Suppose boxes and categories are all correct, but their expected order is A, C, B, D while the parser emits A, B, C, D. Every region can receive full box and category credit. The pair B and C is still inverted, so scores that require their order should detect a difference. The inverse can happen too: the parser can preserve the relative order of all matched regions while missing some required boxes. Report the fraction of ordered entities matched alongside any accuracy computed only over matched entities.
Whitespace can separate columns, but a centered title or a wide figure can span the gutter. A projection-based split may fail if one object overlaps both candidate sides. Some systems isolate the spanning region and then split the body region. Others find pairs of blocks that are likely to follow one another based on learned relations. In this fixture the intervening gutter is clean and the layout has neither a spanning heading nor a floating figure. A classroom exercise can add an artificial spanning box, keep the intended relation of the four original boxes fixed, and see which cases the XY-cut assumptions now exclude.
For table extraction, the reference may group several physical lines into one logical cell. The same description can wrap at a different width without changing which row and column it occupies. Conversely, two items with short descriptions may share a row visually if the source is dense enough. Detecting the ruling grid, assigning text to cells, recognizing strings and interpreting headers are separate questions. A line between two blocks can represent a divider without defining every semantic role. A benchmark that checks structure should state whether merged cells, repeated headings and group rows enter the reference.
Tables, Charts, and Diagrams
Tables convey more than a rectangle of cells
In a ruled table, summing ink over each axis can highlight horizontal and vertical lines. A full-length line produces a strong projection signal, while a short segment from a merged cell may produce a weaker or partial signal. Projection profiles can be dominated by text strokes, heavy shading or border decorations. The common hypothesis that strong lines correspond to grid boundaries needs an explicit validation step. With a borderless table, aligned text can supply evidence for columns. A wrapped label can shift its second line far enough to be near another column boundary, and several centered numeric values can have different widths. A typed reference grid helps distinguish failures in discovering the grid from failures in assigning content to it.
When the purpose is question answering, evaluate which header governs the returned cell. A table can use a multi-row header to express both “forecast” and “Q2.” A cell under “Actual” at the same coordinates in another template may have the same number but answer a different question. This is an example where correct text and the immediate row and column indices may be insufficient unless they are tied to structural roles. For a reported value, retain the header path and evidence region when that detail matters to the user.
A table schema also governs absent cells and repeated identifiers. An empty numeric field, a displayed dash and a missing row mean different things to a downstream consumer. Treat format coercion as a separate operation after structure has been evaluated. A parser that fills a missing amount with zero might produce a sum but lose the ability to indicate incomplete evidence. If a legitimate blank is intended, record that interpretation using the evaluation contract rather than silently treating every absent string the same way.
A related check concerns normalization across cells. A task may accept commas as thousands separators, require preserving a currency code or evaluate whether units are converted correctly. A sorted list of values without their units can match a reference numerically and still be meaningless if the values use different measures. The invoice keeps its schema deliberately simple, so the known corrupted character forces rejection rather than recovery by a locale rule. A deployment evaluation can declare acceptable spellings, return the source text alongside the parsed value and verify that normalization does not turn distinct quantities into the same value.
A layout model can assign types such as caption, heading, body text or table. These labels can guide reading order and grouping, but a label alone does not encode which caption belongs with which figure. DocLayNet includes 11 human-annotated layout classes. LayoutLMv3 combines text and visual input and pretrains with unified masking objectives. A system that consumes OCR tokens and locations can retain those tokens as inspectable intermediate outputs. A system such as Donut can generate a labeled document representation directly from the image without using a separate OCR engine. That architecture can still produce evidence regions if it is designed and measured to do so.
The simple table below uses three declared column centers and three row centers. A fixture box is assigned to the nearest row and column. The gate on its vertical center excludes the header and totals. Nearest-center assignment is a transparent baseline with known geometry. It does not discover grids, spanning cells or line breaks. A collision is returned separately rather than treated as another correct cell. In a production comparison, compute row and column structure scores independently of text recognition.
PythonIn [13]Expand
def table_cells(
boxes, column_centers=(98, 363, 520), row_centers=(159, 204, 249)
):
candidates = {}
collisions = []
for box in boxes:
x, y = box.center
if not 125 <= y <= 270:
continue
row = int(np.argmin(np.abs(np.asarray(row_centers) - y)))
col = int(np.argmin(np.abs(np.asarray(column_centers) - x)))
key = (row, col)
if key in candidates:
collisions.append(key)
else:
candidates[key] = box
return candidates, collisions
def parse_money(box):
value = box.value
whole, dot, minor = value.partition(".")
if not (
whole.isascii()
and whole.isdecimal()
and dot
and minor.isascii()
and minor.isdecimal()
and len(minor) == 2
):
return None
return Decimal(value)
truth_cells, _ = table_cells(boxes)
result_cells, collisions = table_cells(proposed)
amounts = [parse_money(result_cells[i, 2]) for i in range(3)]
subtotal_box = next(box for box in proposed if box.key == "subtotal")
total_box = next(box for box in proposed if box.key == "total")ConsoleOut [14]Expand
Structurally assigned cells: 9; collisions: 0
Exact cell strings: 8/9
Parsed line-item amounts: [Decimal('120.00'), None, Decimal('32.10')]
Printed subtotal: 227.60 (470, 300, 542, 315)
Printed amount due: 273.12 (470, 384, 542, 399)
Line-item reconciliation possible: FalseAll nine table cells are present, yet only eight have the correct string. The printed subtotal and total remain separately readable. A system can return a value sourced from the printed total while declining to claim that it verified the line-item calculation. If checkable values reconcile, a separate numerical rule can compare the exact decimal subtotal plus tax with the printed total. It cannot safely assume a malformed cell is a zero or silently substitute a nearby amount. The lesson applies to inputs with units or currency marks as well: decide the schema before coercing values.
Checking calibration assumptions before comparing bars
An image reader measures positions in pixels. The chart author presents values on an axis that may use a different origin, unit and scale. To turn a pixel into a number, attach tick labels to their pixel locations and fit the appropriate calibration. In the synthetic raster the axis is linear; the larger the value, the smaller the pixel row because the image origin is at the top. For an axis with a logarithmic scale, equal pixel spacings have a different interpretation. The assumptions about scale and axis direction belong in the numerical report and should be checked independently of bar localization.
A difference in the recovered height can originate in the location of the top edge, the inferred scale and offset, the mapping of a bar to a category, or the read unit. If a quarter label is attached to the wrong bar, calibration can recover an excellent number for the wrong quarter. A useful extraction record includes candidate label, raw pixel coordinate, associated axis and calibrated number. A benchmark can then compare matching categories first and include unit consistency in the final value check. Ranking bars can be robust to some additive calibration changes when all bars use the same scale, while recovering an exact value is directly sensitive to those changes.
Two reference ticks determine a straight line when their pixel rows differ. Additional ticks permit a residual check, which can expose an incompatible observation but cannot always identify which label or coordinate caused it. A very small residual on an overfitted calibration is no substitute for confirming the assigned labels. When fitting a line, compare the fitted tick values with their declared references and inspect large residuals. A disagreement might indicate a badly read label, a wrong tick pixel or a bad choice of axis model. The companion fixture below changes one assigned label in isolation so that these sources remain distinguishable.
With a thick or antialiased mark there may be several plausible pixel rows for the top. The current raster uses an exact selected color in a simple rectangular region. It contains no overlapping bars, gradient fill, grid lines of the same mark color or thick outlines around the bar. A parser deployed on exported charts needs a declared mark detector for such cases. Testing under image rescaling is also useful because interpolation can change the available color values. In this fixture the exact-color detector runs on the original pixel grid, and the separate display rendering does not change the numbers read from that grid.
The pure localization error discussed above is a conditional bound. Rounding the bar top to the nearest pixel contributes at most one half of the absolute linear slope in data units, if the direction, tick positions and calibration are exact. Disagreement in tick labels can make the scale error much larger than this bound. A reader who applies the half-pixel bound indiscriminately to every part of chart reading may understate uncertainty. The new diagnostic therefore retains the bar pixels and perturbs one label. Expect any resulting difference in the recovered numbers to come from calibration, not from bar detection.
There are charts where several axes or marks encode different units or data series. A multi-axis plot can place separate quantities on the same drawable coordinate system without making their numeric scales equal. Legends, axes and labels are evidence for associations and need to be carried into any parsed representation. Grouped or stacked bars also require a clear rule about whether a top coordinate or the difference between consecutive segment edges encodes a value. A benchmark designed for plain bars only supports plain-bar claims. Verify which kinds of mark and which axis conventions each test actually uses.
From chart pixels to numbers
A chart reader must connect the mark to its label and calibrate the axis. For a linear vertical axis, pixel rows can increase downward while values increase upward, so the fitted slope is negative. If 10 and 20 occur at rows 300 and 200, the row at 250 represents . For a logarithmic axis, the analogous interpolation is in log values and only for valid positive calibration ticks. Labels, scale and mark identification are different error sources.
ChartQA includes questions about visual chart elements as well as arithmetic or logical operations. It is useful to check underlying value extraction before comparing reasoning on retrieved values. The fixture below draws four colored bars and six ticks. It detects dark tick pixels in a known column and identifies bar regions by their exact fill color. Correctly transcribed tick values and the left-to-right label order are supplied as annotations. This is pixel sampling with known color and annotation, rather than a general chart parser.
PythonIn [15]Expand
MARK = (38, 83, 150)
CHART_VALUES = (12, 15, 9, 22)
CHART_LABELS = ("Q1", "Q2", "Q3", "Q4")
TICKS = (0, 5, 10, 15, 20, 25)
CHART_X = (104, 182, 260, 338)
def render_chart():
image = Image.new("RGB", (410, 255), "white")
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(font_manager.findfont("DejaVu Sans"), 13)
draw.text((80, 16), "Quarterly Revenue (Millions)", font=font, fill="black")
for tick in TICKS:
y = round(206 - 6.4 * tick)
draw.line((51, y, 58, y), fill="black")
draw.text((24, y - 8), str(tick), font=font, fill="black")
draw.line((60, 46, 60, 206), fill="black")
draw.line((60, 206, 378, 206), fill="black")
for label, x, value in zip(
CHART_LABELS, CHART_X, CHART_VALUES, strict=True
):
y = round(206 - 6.4 * value)
draw.rectangle((x - 18, y, x + 18, 205), fill=MARK)
draw.text((x - 9, 214), label, font=font, fill="black")
return image
def chart_readout(image):
pixels = np.asarray(image)
ordered_ticks = np.flatnonzero((pixels[:, 54] == 0).all(axis=1))[::-1]
slope, offset = np.polyfit(ordered_ticks, TICKS, deg=1)
bars = (pixels == MARK).all(axis=2)
painted_columns = np.flatnonzero(bars.any(axis=0))
regions = np.split(
painted_columns, np.flatnonzero(np.diff(painted_columns) > 1) + 1
)
tops = [
int(np.flatnonzero(bars[:, cols].any(axis=1))[0]) for cols in regions
]
return ordered_ticks, tops, slope, offset, slope * np.asarray(tops) + offset
chart_image = render_chart()
rows, tops, slope, intercept, values = chart_readout(chart_image)
errors = np.abs(values - np.asarray(CHART_VALUES))VisualizationOut [16]Expand

ConsoleOut [17]Expand
Detected tick rows: [206, 174, 142, 110, 78, 46] Detected bar-top rows: [129, 110, 148, 65] Fit: slope -0.15625 million units per pixel; intercept 32.18750 Q1: recovered 12.03125; actual 12 Q2: recovered 15.00000; actual 15 Q3: recovered 9.06250; actual 9 Q4: recovered 22.03125; actual 22 Maximum absolute error: 0.06250 million units
The largest absolute error is about 0.0625 million units on this fixture. With exact tick rows and a renderer that rounds each bar top to the nearest pixel, the bar rounding error is at most half a pixel times the absolute fitted slope. That gives about 0.0781 million units here. Missing tick marks, antialiasing, overlapping marks or a wrongly selected scale can invalidate this bound. A numeric label or a companion data table can provide an exact value when the bar position is only an estimate.
Calibrating with one inconsistent tick
Use the six actual detected tick rows. Make a copy of their declared values and increase the value 10 to 15 at the third tick. Keep every pixel, bar label and other assigned tick value identical. Fit a second line and measure the observed-versus-fitted discrepancies against the values provided to each fit. Then compare what the two calibrations imply for the original bar tops.
PythonIn [18]Expand
reference_ticks = np.asarray(TICKS, dtype=float)
inconsistent_ticks = reference_ticks.copy()
inconsistent_ticks[2] += 5.0
altered_slope, altered_intercept = np.polyfit(rows, inconsistent_ticks, deg=1)
tick_residuals = reference_ticks - (slope * rows + intercept)
altered_residuals = inconsistent_ticks - (
altered_slope * rows + altered_intercept
)
altered_values = altered_slope * np.asarray(tops) + altered_intercept
largest_residual_index = int(np.argmax(np.abs(altered_residuals)))
assert np.allclose(tick_residuals, 0)
assert largest_residual_index == 2ConsoleOut [19]Expand
Largest absolute reference residual: 0.000 Largest absolute altered residual: 4.095 at pixel row 142 Q1: original 12.031; altered 12.878 Q2: original 15.000; altered 15.762 Q3: original 9.062; altered 9.994 Q4: original 22.031; altered 22.592
VisualizationOut [20]Expand

The largest absolute residual points to the deliberately changed tick row in this setup. That conclusion uses the known fault introduced by the fixture. An unexplained residual on a new chart would require investigating tick association, coordinate detection and the choice of linear scale. The fit with the altered label also changes all four recovered values even though the bar-top rows never moved. A check that only inspects those four pixel rows would miss the calibration error.
Why a graph needs both structure and execution semantics
A diagram can preserve the full inventory of visible node names while communicating a different workflow if one edge was directed incorrectly or got the wrong label. An arrow between two components can represent order, a data dependency or a conditional next action. The task specifies which semantics matter and any instruction on whether connectors with no arrows are undirected. Diagram parsing can therefore produce a typed directed graph for a particular family without asserting that every visual connector should be interpreted that way.
A graph witness can answer a query by naming a source, a normalized relation and a successor. When several edges share the same normalized label from one source, the intended behavior might be branching, ambiguity or invalid input depending on the diagram convention. In the exercise, an absent exact label returns no successor. Preserving this outcome distinguishes missing evidence from a confident answer inferred from nearby words. For a multi-step query, keep the path or subgraph needed to justify the terminal node so that a bad intermediate edge remains visible.
Edge precision and recall are useful when scoring extracted structure. If labels are part of edge identity, changing “no” to “yes” for the same ordered endpoints replaces a correct edge with an incorrect edge. Under a protocol that ignores labels, the structure of that edge can still count as correct. Neither measurement is universally preferable. An accessibility description concerned with connectivity can use an unlabeled graph, while a workflow that follows conditional branches needs accurate labels. A model that succeeds on one local branch should still be tested on reachable endpoints and cases with multiple steps if the deployment needs full path accuracy.
When several different diagrams depict the same process, a parser can be tested separately on invariance to rearranging boxes and on sensitivity to changing edge semantics. The first experiment preserves the graph while changing its appearance. The second preserves much of the appearance while changing one condition. Storing the intended graph directly makes both experiments reproducible. In our synthetic drawing the graph is the starting point for the illustration; the notebook deliberately perturbs that graph to teach scoring. A raster-only reconstruction system would need to detect nodes, connect arrows to endpoints, associate labels and handle occlusion before that score could be reported as extraction from pixels.
Branch labels turn a diagram into a directed graph
A flowchart can use shapes and text to identify nodes, then directed, labeled relations to specify transitions. AI2D describes diagrams with explicit structural annotations. Our small graph is supplied as ground truth. To isolate a parsing error, keep the nodes and endpoint pairs correct but relabel one edge. Measure label-aware edge F1 as when the denominator is positive. A query that requires one unique successor abstains when none or more than one matches.
PythonIn [21]Expand
EDGES = {
("receive", "stock", ""),
("stock", "fulfill", "yes"),
("stock", "backorder", "no"),
("fulfill", "notify", ""),
("backorder", "notify", ""),
}
def successor(edges, source, label):
matches = sorted(
end
for start, end, branch in edges
if start == source and branch == label
)
return matches[0] if len(matches) == 1 else None
missed = (EDGES - {("stock", "backorder", "no")}) | {
("stock", "backorder", "yes")
}
edge_pairs = {"Reference": EDGES, "Relabeled": missed}ConsoleOut [22]Expand
Reference node endpoint count: 5 Labeled edge F1: 1.0 Unique no branch from stock: backorder Relabeled node endpoint count: 5 Labeled edge F1: 0.8 Unique no branch from stock: None
All five endpoint nodes are still present. The relabeling yields four true positive labeled edges out of five on both sides, so F1 is 0.8. The query fails even though the diagram still contains its boxes and arrows. Recovering the graph makes branching or reachability an ordinary symbolic computation. That computation inherits any mistakes in the graph, which is why a separate structure metric matters.
VisualizationOut [23]Expand

Grounding: Regions, Coordinates, and Actions
Grounding connects a prediction to a region or an element. A referring expression may request one region, a question may need evidence from several regions, and an action instruction refers to an element with a present state. SeeClick studies screenshot-only GUI grounding and introduces ScreenSpot, a benchmark for grounding language instructions to interface elements. That is distinct from measuring whether an interaction brings about the requested state after a click.
If a structured interface supplies labels and stable element identifiers, a harness can score a target match against those labels. Give it the interface revision, visible bounds and current state, because a stale identifier could refer to a different control or point. If you use coordinates instead, state whether they are image pixels, scaled CSS coordinates or normalized coordinates, and check their mapping at the moment of the action. A screenshot alone does not reveal all possible state. In particular, matching the word "Dark theme" does not determine whether enabling it requires a click.
Our fixture supplies typed elements and pixel bounds for a hypothetical 1024-by-640 viewport. The code reads only this structured metadata. A matcher compares normalized labels and abstains on ambiguity. Once it chooses the toggle, a second step checks whether the desired state is already present. The code returns a proposed point, never a live UI operation.
PythonIn [24]Expand
controls = [
{
"id": "dark-theme",
"label": "Dark theme",
"role": "toggle",
"checked": False,
"box": (752, 150, 790, 175),
},
{
"id": "auto-update",
"label": "Auto-update",
"role": "toggle",
"checked": True,
"box": (752, 200, 790, 225),
},
]
def choose_toggle(elements, label, desired):
matches = [
item
for item in elements
if item["role"] == "toggle"
and item["label"].casefold() == label.casefold()
]
if len(matches) != 1:
return {"status": "ambiguous-or-absent"}
item = matches[0]
if item["checked"] == desired:
return {"status": "already-set", "id": item["id"]}
x0, y0, x1, y1 = item["box"]
return {
"status": "proposed",
"id": item["id"],
"point": ((x0 + x1) / 2, (y0 + y1) / 2),
}
proposal = choose_toggle(controls, "dark theme", True)
already_set = choose_toggle(controls, "auto-update", True)
duplicate = controls + [dict(controls[0], id="other-dark-theme")]
ambiguous = choose_toggle(duplicate, "dark theme", True)ConsoleOut [25]Expand
Change needed: {'status': 'proposed', 'id': 'dark-theme', 'point': (771.0, 162.5)}
No action needed: {'status': 'already-set', 'id': 'auto-update'}
Duplicate label: {'status': 'ambiguous-or-absent'}The true element is the same for both a point-in-region test and an identifier test on this record, but the metrics need not agree. A visible icon may occupy part of a button while its full hit area is larger. For a workflow evaluation, also test whether the intended control changed state and whether unrelated controls kept theirs. Re-evaluating the current state after a redraw checks a different failure than locating the control in an old screenshot. A local fixture can support repeatable tests for duplicate labels or clipped bounds without instrumenting a user’s private screen.
Rechecking an old coordinate after a viewport change
Keep the previous target identifier and generate a second hypothetical viewport at half the original scale. This is an affine coordinate exercise from typed data. It uses the same element boxes and the same proposed point already inspected above, and computes where the point would need to be in the new view.
PythonIn [26]Expand
viewport_scale = 0.5
def scale_edges(values, scale):
return tuple(scale * value for value in values)
def point_in_box(point, box):
x, y = point
x0, y0, x1, y1 = box
return x0 <= x <= x1 and y0 <= y <= y1
target_control = next(item for item in controls if item["id"] == proposal["id"])
scaled_controls = [
{**item, "box": scale_edges(item["box"], viewport_scale)}
for item in controls
]
same_target = next(
item for item in scaled_controls if item["id"] == proposal["id"]
)
scaled_point = scale_edges(proposal["point"], viewport_scale)
assert point_in_box(proposal["point"], target_control["box"])
assert not point_in_box(proposal["point"], same_target["box"])
assert point_in_box(scaled_point, same_target["box"])ConsoleOut [27]Expand
Old point (771.0, 162.5); scaled point (385.5, 81.25). Old point matches the scaled target: False Mapped point matches the same target: True
VisualizationOut [28]Expand

The boxes and points have the same relative placement in both panels. Pixel numbers differ because the frames have different scales. The old point fails the same-target box test, and the mapped half-scale point passes it. This preserves the distinction between recognizing the correct element and having a suitable coordinate for the current viewport. A stale point from a previous layout would need an actual new localization when a simple scale transform no longer describes the change.
Keep screen points attached to the right revision
An interface grounding result can return a coordinate, an element identifier or both. A coordinate refers to a particular image and its coordinate system. An identifier refers to an element in a particular interface representation. An accessible or structured tree may place an outer hit region around a small visible glyph, so object detection and an effective click region can differ. If the viewport or scale changes, a new point may be needed even if the stable identifier still refers to the same control. If components are regenerated, an identifier can become stale even when the pixels look unchanged.
A point answer should carry enough information to map it back to the view that generated the prediction. One can test this on a static layout using a coordinate transform. If an entire drawing is uniformly scaled to half its original width and height about the origin, matching the new view requires halving the original pixel coordinates and all its box corners. If a content crop then removes a margin, subtract the crop origin in the scaled frame before comparing a point with boxes in crop coordinates. The order of these operations matters when the crop offset is specified in a different frame. Named coordinate frames and a concrete witness make these transforms easier to audit.
Document grounding and interface grounding share a need to attach predictions to evidence, but the latter can also need current state. A request to set a toggle on has a different success condition from a request to invert it. If it is already on, a correct system may return “already set” instead of proposing a click. Receiving a point in the intended control region does not by itself demonstrate the requested state was achieved. A combined evaluator can record target selection, precondition, proposed transition and verified resulting state under a safe, authorized interaction protocol. In this notebook the proposal remains a record in a local fixture. The static mock can test current state and identity without causing a side effect.
A repeated label is useful for evaluating abstention. If the same label appears in several settings sections, choosing the first result can be wrong even if its role is a toggle. Additional structure such as the section name or stable identifier may resolve the ambiguity, but only when it is present and within scope. The simple resolver has no such extra context; it reports ambiguity or absence when the matching criterion selects other than exactly one element. Real evaluation should capture which cue justified a proposed disambiguation before counting it as an interface success.
Evidence for question answering
An answer that includes a bounding box can be audited at the evidence level. If the text is correct but points at a subtotal rather than the taxed total, the stated provenance is wrong. If a region is correct but the recognizer returns a malformed string, localization succeeded while transcription failed. A broad region may contain both the desired and misleading values. A geometric threshold can score whether it sufficiently overlaps the available reference region, but evidence quality for the task can depend on whether the relevant text actually appears and is specific enough to justify the answer.
Consider reporting a page index, field identity, raw value and transformed coordinates as one result, then aggregating over fields. A document with two copies of the same number should not let a region match the item solely by text equality. Similarly, evaluation of a chart extraction can match the category and axis before comparing the numeric value. This use of identity distinguishes correct association from coincidence. A text retrieval pipeline can store short evidence spans alongside each answer for a human check, while a benchmark can score automated associations against a trusted reference.
An audit can include a controlled missing-evidence example. Remove or corrupt one field while retaining the rest of the document and ask for both the now-unavailable field and an unaffected adjacent one. An ideal diagnostic can distinguish the predicted missing field, an unavailable verification step and a correct neighboring answer. This chapter's invoice contains a text-layer corruption at one field while keeping its raster evidence and physical coordinates unchanged. It shows how a pipeline can expose an error instead of filling in a plausible substitute. The model would need additional evidence to recover a correct transcription from the pixels.
Key Parameters
Change a parameter in the stage where it actually has meaning. The XY-cut threshold is a minimum clear gap in fixture pixels. It changes when splitting recurses and when the region falls back to row-first order. Its value needs reconsideration when inputs are resized independently or contain a title that spans a gap. The box IoU threshold is a decision on how much overlap counts as a match under the declared annotation scheme. A recognition threshold affects acceptance of text predictions if a model produces a usable score. Neither a gap threshold nor a confidence threshold belongs in the arithmetic that converts a valid tick location into a chart value.
The axis fit depends on the tick rows and labels, the assumed scale, and the observed mark coordinates. Perturbing a tick label can move every inferred number together. Perturbing a single observed bar top under a fixed fit changes only that mark's calibrated value. Retain these inputs when recording reproduced numbers so another reader can distinguish the sources of error.
The interface fixture is parameterized by role, label and desired state, and defines its coordinates on a known viewport. A matching label on an element of the wrong role does not pass the exact matcher. A changed box with an unchanged identity can still invalidate an old proposed point. For a meaningful threshold or parameter sweep, label which upstream detections, state facts and downstream tasks are held fixed.
The Modern Stack: OCR-Free and OCR-Based
An OCR-based pipeline exposes a separate detector and recognizer before structured layout processing. Those intermediate observations can help a reviewer see where a downstream error entered the data. An OCR-free document model can generate a task output directly from pixels without a separate exposed OCR stage. The absence of an intermediate text stream changes which evidence is readily available for inspection. It does not decide whether grounding can be produced or externally verified. A system that offers evidence regions can be assessed for localization and factual correctness regardless of whether its recognizer is an explicit component.
A hybrid architecture can use recognized text for many fields while consulting pixels to read charts, locate checkboxes or disambiguate a suspected text error. The adaptation policy matters. Specify how the system chooses which inputs to consult and what it does when the two disagree. In this chapter the raster and the emulated text layer are deliberately distinct. Reading only perfect boxes and corrupted text is an evaluation of that exposed interface. Correcting the corrupt value by reading its actual glyph would be a different experiment.
Resolution, crop strategy and context budget
A square image of side length 1,024 pixels contains 4,096 patches if it is covered by nonoverlapping 16-by-16 patches. At 2,048 pixels with the same stride, it contains 16,384. This is a geometric patch count under the stated tiling. Some model architectures pool, resample or otherwise change the number of representations before sending them to a language model. Others use overlapping crops, padding or variable image sizes. State which convention you count before inferring inference cost or context use from the original resolution.
Cropping can preserve a small detail at higher resolution while reducing the rest of the image seen by the model. A region proposal that cuts off a nearby header can increase recognition quality and reduce the ability to interpret the recognized text. A useful evaluation compares a full-page representation, a tested crop policy and explicit cropped-context failures. When a task relies on associations across the page, recording both page-level context and targeted local evidence can be more revealing than reporting average image scale alone.
The patch budget in that square-grid example can be reproduced without invoking any model.
PythonIn [29]Expand
patch_edge = 16
for image_edge in (1024, 2048):
side_patches, remainder = divmod(image_edge, patch_edge)
assert remainder == 0
print(f"{image_edge} px square: {side_patches**2} patches")ConsoleOut [29]Expand
1024 px square: 4096 patches 2048 px square: 16384 patches
Doubling both spatial dimensions quadruples the count under this tiling rule. Compare that change with the evidence missing from the smaller image before deciding whether to raise resolution or target a crop.
Limitations and Impact
The exact boxes, tick values, chart colors, label order and graph vocabulary in the examples are fixture annotations. A learned system would have to recover some or all of them. Keep splits by source or document template where layout reuse could otherwise leak answers. Include representative pages with different reading orders and table structures, charts with different scales, and interfaces with localized labels or missing controls. For each test retain source provenance and annotation rules, and separate the errors in reading from those in meaning and execution.
A token budget has a similar need for definitions. Without resizing or token merging, a 1,024-by-1,024 image divided into nonoverlapping 16-by-16 patches yields 4,096 patch positions. Doubling both image dimensions produces 16,384. Special tokens, tiling overlap, pooling and projection can change the actual model-facing count. Compare the resolved visual detail and the token count at the measured interface before choosing how to pass full pages to a particular model.
Summary
An invoice can have good text detection but bad recognition or cell reconstruction. A chart answer can be arithmetically correct for an incorrectly calibrated value. A flowchart answer can fail when all nodes are recovered but one relation has the wrong label. A screen action can locate the right control while ignoring its state. Keep these checks separate and retain the evidence regions or elements that let you verify the final result.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about document, diagram, and interface understanding.
Document, Diagram, and Interface Understanding
Join the discussionAsk a question or share what you learned.
Keep exploring
Reference
Citation details
Cite or share this article.


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!