Skip to Content
Recodocs

04 · Ingest documents with layout

Recover the reading, action and page citation from the F-250 fault matrix. Compare what the helpdesk can extract when the same page arrives as a searchable PDF or a scan.

10 min read
Part 2
Build the evidence layer
Model
Qwen2-VL-2B-Instruct
Data
Matched synthetic equipment manuals and scans
Hardware
Tesla T4 and CPU, in Google Colab
Open in Colab

The fault is on one row

You’re back on the facilities helpdesk. The operator has identified fan F-250 and asks for the reading and action printed beside FILTER BLOCKAGE. You have the manual open. You need both fields from that row and a citation to the page. The next row gives an action for a different fault. An extractor that joins them can send the wrong instruction even when it cites the right page.

The manual is synthetic. Its readings and actions are labels for practising extraction.

Synthetic F-250 equipment manual, with a ruled fault matrix and the filter-blockage row outlined
Incoming ticket · F-250

What reading and required action does F-250 list for FILTER BLOCKAGE?

manual-F-250-r3:1

FaultReadingRequired action
FILTER BLOCKAGE101Inspect filter
Reveal the two ingestion choices

Select a layout reader when the PDF contains selectable text. For the image-only copy, choose a reader that can see pixels and check the result against the page.

On the recorded searchable copy, the plain reader attached SEAL WEAR and SENSOR DRIFT to the highlighted row. Compare those with the reading and action on the page.

Actual synthetic page from the notebook. The outline marks the target row using the source manifest’s coordinates.

Change one fact. Keep the question, page revision and visible table fixed. The original PDF lets you select the text. The other copy contains the same page as an image. Which reader would you choose in each case? Use the reveal above to check your prediction.

Same ticket and visible pageWhat changesFirst choice
F-250 asks for the filter-blockage rowSearchable text PDFRead the cells using their coordinates.
F-250 asks for the filter-blockage rowImage-only scan of that PDFRead the pixels and verify the recovered row.

Geometry recovered every answer on text PDFs. Vision recovered them from pixels.

Strict answers out of 12 pages per reader and input, with a paired 95% interval versus layout on the text PDF

1
Reader and inputStrict answersDifference, pp [95% CI]
Plain texttext PDF
0/12
−100[−100, −100]
PDF layouttext PDF
12/12
0[0, 0]
Plain textimage-only scan
0/12
−100[−100, −100]
PDF layoutimage-only scan
0/12
−100[−100, −100]
Visionpage pixels
12/12
0[0, 0]
Source: verified Lesson 04 Colab notebook. PDF readers ran on the host CPU and Vision ran on a Tesla T4. Intervals use resamples of paired families. Across formats, the input and reader can both change.

Read the page in the order it was meant to be read

A content stream is a list of drawing instructions. In the searchable F-250 PDF, those instructions emit the fault names, then all readings, then all actions. The printed rules still put each field in the correct cell. A parser that groups every three emitted strings as one row treats the three fault names as if they were a fault, a reading and an action.

The same page then goes through rasterisation. The scan wraps the resulting image in a PDF container. Plain text can read the original drawing stream and PDF layout can recover its geometry. The two PDF methods see no text cells in the raster copy. Vision receives the exact pixels used in that copy once per family.

# The drawing loop emits one column at a time.
for column in range(len(HEADER)):
    for row, values in enumerate(fixture["rows"][1:], start=1):
        page.drawString(
            TABLE_X[column] + 9,
            PAGE_HEIGHT - TABLE_Y[row] - 22,
            values[column],
        )
# Read the ruled matrix using page geometry.
with pymupdf.open(stream=pdf_bytes, filetype="pdf") as document:
    page = document[0]
    tables = page.find_tables()
    rows = tables.tables[0].extract() if tables.tables else []
    text = page.get_text(sort=True)

Spatial information matters even outside tables. Pupuk Indonesia and its implementation partners describe using coordinates to organise content in documents with images and watermarks. Their case study reports extraction time falling from 5–10 minutes to 40–70 seconds for their system. Pupuk Indonesia and Google Cloud case study

Docling combines native PDF cells with a table model. Its TableFormer implementation predicts the crop’s structure and maps it back to the original PDF cells. It illustrates a path between the two PDF readers and the full-page model in the lab. Docling technical report

Grade the row and its citation together

A number can be correct in isolation and still answer the wrong question if it belongs to the next row. Measure the extracted value, its record scope and the source location together.

The desk asks for an exact reading and action, both in the matching fault row. A correct page identifier is necessary. It cannot make an incorrect pair valid. The evaluator counts body cells separately to show what survived extraction. It looks up each expected fault label, requires a unique matching row and compares each cell in its original column. The desk attaches the known page identifier after extraction. Vision emits rows and headings, and never receives the source manifest or the correct answer.

# Match the expected label and reject ambiguous duplicates.
matches = values_by_fault[label]
observed = matches[0] if len(matches) == 1 else None

# Grade the assembled answer, including its page citation.
strict_correct = score_answer(gold["expected"], answer)

For a source family and method, the strict score is the product of three exact-match indicators. The fields are the decision, the combined reading and action, and the sorted list of cited pages. The stars denote the expected fields.

Sf,m=1[df,m=df∗]⋅1[vf,m=vf∗]⋅1[Ef,m=Ef∗].\begin{aligned} S_{f,m} ={} &\mathbf{1}[d_{f,m}=d_f^*] \\ &\cdot \mathbf{1}[v_{f,m}=v_f^*] \\ &\cdot \mathbf{1}[E_{f,m}=E_f^*]. \end{aligned}

F-250 · “What reading and required action does F-250 list for FILTER BLOCKAGE?”

Expected
answer · 101 | Inspect filter · manual-F-250-r3:1
Plain text
answer · SEAL WEAR | SENSOR DRIFT · manual-F-250-r3:1
PDF layout
answer · 101 | Inspect filter · manual-F-250-r3:1
Vision
answer · 101 | Inspect filter · manual-F-250-r3:1

Plain text saw the reading and the action elsewhere in the stream. It still put the other two fault labels in the reading and action cells.

The plain reader kept fault labels and lost their readings

Exact expected body cells and readings associated with the correct fault

2
Reader and inputExact cellsExact readings
Plain texttext PDF12/1080/36
PDF layouttext PDF108/10836/36
Plain textimage-only scan0/1080/36
PDF layoutimage-only scan0/1080/36
Visionpage pixels108/10836/36
Source: verified Lesson 04 Colab notebook. PDF readers ran on the host CPU and Vision ran on a Tesla T4. A page has three expected rows, giving 108 body cells and 36 readings per arm across the sample.

PubTables-1M separates exact table content from partial agreement. In its canonical test data the authors report exact table content accuracy of 0.9349 on simple tables and 0.2712 on complex tables for DETR-NC. The source domain is scientific papers. The metric distinction carries across to an equipment manual, where spotting some of the right text can leave the record unusable. PubTables-1M preprint, Table 4

Check what a passing row can omit

The F-250 Vision output contains the entire fault matrix. It omits SERVICE NOTES. The notebook reports missing and inverted headings independently because the helpdesk’s fault-row score does not require those headings. A synopsis of the whole page would need a separate contract. The two PDF methods returned an empty row list on the scan and asked for clarification.

F-250 · Same fault matrix as an image-only scan or its source raster

Scan, both PDF readers
rows: [] · clarify · no citation
Vision row
["FILTER BLOCKAGE", "101", "Inspect filter"]
Vision headings
["OVERVIEW", "FAULT MATRIX"]

The full source includes SERVICE NOTES. This missing heading leaves the target-row score unchanged.

Vision kept the fault rows even when it missed headings

Heading errors, unexpected labels and failed output checks

3
Reader and inputOrder errors / invertedMissing headingsExtra / duplicate pagesInvalid / capped
Plain texttext PDF24 / 24012 / 0—
PDF layouttext PDF0 / 000 / 0—
Plain textimage-only scan36 / 0360 / 0—
PDF layoutimage-only scan36 / 0360 / 0—
Visionpage pixels10 / 050 / 00 / 0
Source: verified Lesson 04 Colab notebook. PDF readers ran on the host CPU and Vision ran on a Tesla T4. Order errors count pairs with a missing or inverted heading. Extra and duplicate labels count pages, not cells.

The pattern held across the six source-family groups

Strict passes out of two pages per family group

4
Family groupPlain / textLayout / textPlain / scanLayout / scanVision / pixels
Manual0/22/20/20/22/2
Numeric0/22/20/20/22/2
Multi-source0/22/20/20/22/2
Ambiguity0/22/20/20/22/2
Boundary0/22/20/20/22/2
Follow-up0/22/20/20/22/2
Source: verified Lesson 04 Colab notebook. PDF readers ran on the host CPU and Vision ran on a Tesla T4. Group names come from the course manifest. Every page here asks the fault-row extraction question.

All six groups of development families use the same template and fault-row question. The group names identify which families were sampled from the course suite. These results describe the extraction task and its template. Faded print, handwriting, unfamiliar tables and manual revisions remain outside the comparison.

Time the reader after preparation

The notebook measures PDF creation and rasterisation separately from extraction. For F-250, rendering the searchable PDF took 2.56 ms. Rasterising and wrapping it took 56.81 ms. Once the page is ready, PDF extraction times cover opening and parsing the bytes. The Vision timer starts before preprocessing and stops after generation, decoding and GPU synchronisation. The reported PyTorch allocation includes the model weights resident during extraction.

# Synchronise so GPU work lands inside the timed region.
sync()
torch.cuda.reset_peak_memory_stats()
started = perf_counter()
extracted = parse_vision(image, processor, vision_model)
sync()
elapsed = (perf_counter() - started) * 1_000

Reading pixels took seconds. Reading text geometry took milliseconds.

Per-page extraction wall time, with the observed maximum for each arm

5
Reader and inputMedianMaximum
Plain texttext PDF5.04 ms21.07 ms
PDF layouttext PDF43.73 ms100.82 ms
Plain textimage-only scan1.62 ms5.60 ms
PDF layoutimage-only scan2.32 ms4.27 ms
Visionpage pixels10.64 s13.04 s
1101001,00010,000Plain / textLayout / textPlain / scanLayout / scanVision / pixelsMilliseconds · log scale
Vision load 78.58 s · warm-up 14.83 s · peak allocated 4.54 GiB
Source: verified Lesson 04 Colab notebook. PDF readers ran on the host CPU and Vision ran on a Tesla T4. Extraction excludes document preparation, model loading and warm-up. The maximum describes the recorded pages.

The twelve Vision extractions each used 1,199 input tokens and generated 87–119 tokens. The lab recorded page wall time rather than service throughput. Parseur uses a distinct OCR stage ahead of extraction and reports an 80% improvement in AI response speed measured in tokens per second. Document preparation and response time have separate denominators. Parseur and Google Cloud case study

Pair the formats by source family

For each family, subtract PDF layout’s score on the searchable page from the candidate score. Resample the resulting pairs by family so the text original and scan always move together. Three cells on one row are part of the same observation for this comparison.

Df,m=Sf,m−Sf,ref,Δ^m=1F∑f=1FDf,m.\begin{aligned} D_{f,m} &= S_{f,m} - S_{f,\mathrm{ref}}, \\ \widehat{\Delta}_m &= \frac{1}{F}\sum_{f=1}^{F} D_{f,m}. \end{aligned}
# Keep the pairing keyed to the source family.
assert [row["family"] for row in group] == reference_families
candidate = [row["strict_correct"] for row in group]
interval = paired_interval(group, candidate, incumbent)

Vision and text-layout passed on the same families

Page-level changes relative to layout on the text PDF of each family

6
Reader and inputWinsTiesLosses
Plain texttext PDF00
12
PDF layouttext PDF012
0
Plain textimage-only scan00
12
PDF layoutimage-only scan00
12
Visionpage pixels012
0
Source: verified Lesson 04 Colab notebook. PDF readers ran on the host CPU and Vision ran on a Tesla T4. Paired wins are reference failures rescued. Paired losses are reference passes lost.

Every observed pair agrees between searchable PDF layout and Vision on the raster. The derived 95% paired interval is 0 to 0 percentage points because all twelve paired differences are zero. This is a tie on the fixture. On the same searchable input, Plain text missed every paired case. Against the reference, each scan-only PDF arm also lost all twelve, which combines a change of input representation with either a reader change or a fixed reader that now has no text.

What to keep

InputReaderStrict answersMedian extraction
Searchable text PDFPlain text0/125.04 ms
Searchable text PDFPDF layout12/1243.73 ms
Image-only scanPlain text0/121.62 ms
Image-only scanPDF layout0/122.32 ms
Page pixelsVision12/1210.64 s
  • Check what the PDF contains. If the page has selectable text, try layout extraction and inspect the fields attached to each label. Selectable text alone leaves reading order unresolved.
  • Escalate missing or conflicting rows. A pixel reader can recover an image-only matrix. Before using a recovered instruction, check the correct revision, authorised source, row uniqueness and page citation.
  • Track what the workflow needs to review. Stellar’s AWS case study describes sending exceptions to human reviewers after extracting fields and validating against rules. Preserve the source so the reviewer can settle an uncertain row. Stellar Innovations and AWS case study

Next to try, not tested here: lower the raster resolution, add an OCR stage ahead of row reconstruction, or introduce a row that spans two pages. For each change, decide what evidence would make the answer usable before inspecting its result.

How it was built

ItemSetting
DataOne synthetic fault-matrix page from each of 12 development families, two per existing course group.
Development digest51dbc208b6b20a620237dd76ce0a2db4f10aa75f4f8fc404121e301b8d79a0cf
Page and scan540 × 400 PDF points. Rasterised at 2× into 1,080 × 800 pixels before embedding the same image in a scan PDF and passing it to Vision.
Plain text and PDF layoutpypdf 5.6.1 text extraction with consecutive string grouping. PyMuPDF 1.26.1 table geometry and position-sorted text. ReportLab 4.4.2 generated the source.
VisionQwen/Qwen2-VL-2B-Instruct, revision 1860c46f12b7449d0f5b426a7474ab715342bc65. FP16, greedy decoding, cap of 160 new tokens. The parser accepts a surrounding JSON fence and checks the row width and field types.
GradeExact decision, combined reading and action, and page citation. The grader records cell and heading scores separately.
Paired intervalPercentile interval from 1,500 resamples of matched source families, seed 401.
Recorded runtimeColab Tesla T4 and host CPU. Python 3.13.16, PyTorch 2.14.1+cu130, CUDA 13.0, Transformers 4.51.3.
Saved evidenceScorecard, all 60 extractions, page manifest, failure gallery, runtime receipt.

Time and cost. The queue receipt records 252.5 seconds to execute the notebook. The lab timer records 219.65 seconds after bootstrap, including model load and warm-up. The highest recorded Vision allocation was 4.54 GiB in PyTorch, derived from the byte counter. The notebook measures execution and allocation. It has no currency ledger.

Run it yourself

Use Open in Colab and keep the same notebook inputs for the first comparison. The executed T4 notebook includes the measured outputs. The separate F-250 source PDF and scan PDF let you inspect both versions side by side.

Find this in the notebookInspect
Freeze a set of pages and Render a searchable pageThe F-250 page, manifest and paired PDF bytes.
Read the stream, geometry or pixels and Grade the rowThe assembled answer and field_results in records.json.
Measure the same pages and Compare paired familiescomparisons in summary.json and the worked failed rows in the failure gallery.

Before each change, write your prediction.

  1. Swap the two loops in render_pdf, keeping the x and y coordinates fixed. Will Plain text recover the F-250 row? Check extracted.rows and strict_correct for its searchable PDF.
  2. Change pymupdf.Matrix(2, 2) to pymupdf.Matrix(1, 1). Which column is most likely to fail at the lower resolution? Compare field_results and elapsed_ms for the same Vision page.
  3. Move the target row on one fixture without changing the label, reading or action. Can each reader still find the row by label? Inspect observed_row and the cited page.

Lesson 05 · Build and rerank a shortlist asks how to find the right source once ingestion has preserved its contents.

How is this page?

Last updated on