Level 3 In-Depth AI · Vision, Audio and Multimodal
OCR and Document AI
Turning pictures of text into usable text and data. Classic OCR finds text boxes and reads them; document AI goes further, understanding layout, tables and forms well enough to answer questions about a page or fill a database from it. Modern systems increasingly skip OCR entirely and read pages end to end.
- Level
- ●●●●● Intermediate
- Reading
- 12 min
- To learn it well
- 1 hour to read, an hour to practise
- Builds on
- 33 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 33 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Image Classification
- LSTMs and GRUs
- Residual Connections
- Object Detection
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- OCR and Document AI
Read them roughly in this order. See it on the concept map →
Why it matters
An enormous amount of the world's information is locked in images of text: scanned contracts, invoices and receipts, insurance claims, medical records, handwritten forms, historical archives, photographed whiteboards, street signs, product labels and screenshots. Optical character recognition (OCR) turns those pixels into characters a computer can search, copy and process. Document AI goes further: it understands the structure of a page (headings, paragraphs, tables, form fields and reading order) so it can extract "invoice number", "total" and "due date" into a database, or answer questions such as "what is the deductible on this policy?"
This is one of the most widely deployed forms of AI in business. Banks, insurers, governments, logistics firms and accountants process millions of documents a day with it. It also feeds retrieval-augmented generation: before an LLM can answer questions about your PDFs, the text has to be extracted, with tables and reading order intact. Bad extraction is one of the most common reasons document chatbots fail.
The intuition
Think of how you read an unfamiliar form. First you glance over the page and see where the text is: blocks, lines, boxes. Then you read each piece. Finally you use the layout to make sense of it: the number to the right of "Total:" is the total, a column of numbers under "Price" are prices, and the title is the big text at the top.
A classic OCR pipeline does the same three steps:
- Text detection: find the regions of the image that contain text, as boxes around words or lines. This is Object Detection where the only class is "text".
- Text recognition: crop each box and read its characters, turning a small image into a string.
- Layout and extraction: put the pieces in reading order, recognise structures (tables, key–value pairs, sections) and pull out the fields you need.
Key idea OCR = detect where the text is, recognise what it says, then use the layout to turn words into structure. Modern document AI often folds all three into one model, a layout-aware Transformer or a multimodal LLM that reads the page image directly.
How it works
Two kinds of text
- Document text: scans and PDFs of printed pages. The text is dark on light, horizontal and in a few fonts. Clean printed English can be recognised with error rates well under 1% of characters. Difficulty comes from poor scans, unusual layouts, tables, stamps and handwriting.
- Scene text: text in photos, such as shop signs, licence plates and labels on products. It can be curved, rotated, in perspective, partly hidden and in any style. It is much harder, and has its own benchmarks.
Handwriting recognition (HTR) is harder again, because every writer is different.
Step 1: text detection
Modern text detectors are segmentation-style CNNs. Rather than predicting boxes from anchors as in Object Detection, many predict for every pixel "is this text?" (plus, depending on the method, the distance to the box edges or the link between characters), then group pixels into word or line regions. This handles long, thin and rotated text better than ordinary boxes. EAST (2017), CRAFT (2019) and DBNet (2020) are well-known examples. Their output is a set of possibly rotated quadrilaterals.
Step 2: text recognition
Recognition takes one cropped word or line image and outputs a string. The problem is that you don't know where one character ends and the next begins, and the number of characters varies.
The classic solution is CRNN with CTC (2015). A CNN turns the line image into a sequence of feature vectors, one per narrow vertical slice from left to right. A bidirectional LSTM adds context. At each slice, the model outputs probabilities over characters plus a special "blank". The Connectionist Temporal Classification (CTC) loss sums over all the ways of aligning that per-slice output with the true string, so no character-level positions are needed for training. At prediction time you take the best symbol per slice, merge repeats and remove blanks: --CC-oo-f-ff-e-e-- becomes "Coffee". The same CTC idea is central to Speech Recognition, where it is explained in more detail.
The newer approach treats recognition as translation from image to text. TrOCR (2021) uses a pretrained vision Transformer as the encoder and a Transformer text decoder that generates the characters one at a time, as an encoder–decoder does. It is more accurate, especially on handwriting, and slower.
Step 3: layout, reading order and extraction
Recognised words come with positions, but not in order. Reading order recovery groups boxes into lines (boxes whose vertical extents overlap), sorts each line from left to right, and orders lines from top to bottom. That is enough for simple pages. Multi-column articles, sidebars and tables need layout analysis: detect and label page regions (title, paragraph, list, table, figure, caption, header, footer) with an object detector trained on page images. PubLayNet, with about 360,000 labelled pages from scientific articles, is a standard training set. Tables need a further step, table structure recognition, to find rows, columns and merged cells.
Key information extraction pulls specific fields from forms, receipts and invoices. Rules and templates work for one fixed layout but break when a supplier changes theirs. LayoutLM (2019) made extraction learnable across layouts. It is a BERT-style Transformer whose input for each OCR'd word is the sum of its word embedding, a 2-D position embedding of its bounding box , and in later versions (LayoutLMv2, v3) image features. The model is pretrained on millions of scanned pages, then fine-tuned to tag each word with a field label, so that "15.70" gets labelled total. Because it sees positions, it learns that a number on the same line as "Total:" is probably the total.
OCR-free document understanding
The newest systems skip the separate OCR step. Donut (2021) is an encoder–decoder Transformer that takes the page image and directly generates structured output, such as a JSON string of fields. Nougat (2023) converts academic PDFs into Markdown, including equations. Pix2Struct (2022) learned to read screenshots by predicting their HTML. These are OCR-free models: no OCR errors cascade into later steps, and the model can use visual cues such as bold text and lines.
Multimodal LLMs are the furthest extension of this idea. Given a page image and an instruction ("extract the line items as JSON", "what is the policy's deductible?"), they do detection, recognition, layout and reasoning in one pass. Document visual question answering benchmarks such as DocVQA (2020, about 50,000 questions on about 12,000 document images) track this ability. As of late 2026, frontier multimodal models handle clean documents very well, and small open vision-language models built specially for OCR (such as olmOCR, DeepSeek-OCR and PaddleOCR-VL, first released in 2025) turn page images into Markdown cheaply. Long multi-page documents, dense tables, small print, handwriting and exact numbers still call for verification, and dedicated OCR remains cheaper and faster at very high volumes.
Measuring OCR
The standard metric is the character error rate (CER): the minimum number of single-character insertions, deletions and substitutions needed to turn the OCR output into the true text (the edit distance, or Levenshtein distance), divided by the length of the true text:
, and are the numbers of substitutions, deletions and insertions, and is the number of characters in the reference. The word error rate (WER) is the same calculation over words, and Speech Recognition uses it too.
Worked example. The truth is Total: 15.70 (12 characters, counting the space). The OCR read Tota1: 15.7O: the letter "l" became the digit "1", and the digit "0" became the letter "O", two substitutions. CER = 2/12 ≈ 0.167. Those two confusions (l/1/I and 0/O) are the classic OCR errors. They are also exactly the ones that break an amount or an ID number, which is why extracted numbers should be checked, for example by verifying that line items add up to the total.
For extraction tasks, field-level accuracy or F1 ("was the total extracted exactly right?") matters more than CER.
In code
Two pieces of the pipeline that need no model: reconstructing reading order from unordered word boxes, and computing CER with edit distance.
# Word boxes as a text detector + recogniser might return them: (text, x1, y1, x2, y2), unordered
words = [("Total:", 40, 212, 98, 230), ("INVOICE", 40, 20, 160, 48), ("12.50", 300, 150, 350, 168),
("Coffee", 40, 150, 100, 168), ("beans", 106, 151, 160, 169), ("No.", 200, 24, 232, 44),
("2041", 238, 24, 280, 44), ("Milk", 40, 180, 80, 198), ("3.20", 304, 181, 350, 199),
("15.70", 296, 212, 350, 230)]
def reading_order(words, overlap=0.5):
"""Group boxes into lines by vertical overlap, then read each line left to right."""
lines = []
for w in sorted(words, key=lambda w: (w[2] + w[4]) / 2): # by vertical centre
for line in lines:
ref = line[0]
inter = min(w[4], ref[4]) - max(w[2], ref[2])
if inter > overlap * min(w[4] - w[2], ref[4] - ref[2]): # same line
line.append(w)
break
else:
lines.append([w])
return "\n".join(" ".join(w[0] for w in sorted(line, key=lambda w: w[1])) for line in lines)
print(reading_order(words))
# INVOICE No. 2041
# Coffee beans 12.50
# Milk 3.20
# Total: 15.70
def edit_distance(a, b):
"""Minimum insertions, deletions and substitutions to turn a into b (Levenshtein)."""
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
cur = [i]
for j, cb in enumerate(b, 1):
cur.append(min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb)))
prev = cur
return prev[-1]
truth = "Total: 15.70"
ocr = "Tota1: 15.7O" # two classic OCR confusions: l->1, 0->O
cer = edit_distance(ocr, truth) / len(truth)
print(f"CER = {edit_distance(ocr, truth)} / {len(truth)} = {cer:.3f}") # CER = 2 / 12 = 0.167
Classic OCR with Tesseract, through the pytesseract wrapper (install the Tesseract program itself first, and scan.png is any scanned page):
import pytesseract
from PIL import Image
img = Image.open("scan.png")
print(pytesseract.image_to_string(img, lang="eng")) # plain text
data = pytesseract.image_to_data(img, output_type=pytesseract.Output.DICT)
print(list(zip(data["text"], data["left"], data["top"], data["conf"]))[:10]) # words, boxes, confidence
A Transformer recogniser for a single handwritten line, with TrOCR from Hugging Face (line.png is a cropped line of handwriting, and the model downloads on first use):
from PIL import Image
from transformers import TrOCRProcessor, VisionEncoderDecoderModel
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten")
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten")
pixel_values = processor(images=Image.open("line.png").convert("RGB"), return_tensors="pt").pixel_values
ids = model.generate(pixel_values, max_new_tokens=64)
print(processor.batch_decode(ids, skip_special_tokens=True)[0])
For whole-document extraction with a multimodal LLM, send the page image with an instruction such as "Return the invoice number, line items and total as JSON", using the API pattern in Multimodal LLMs and Structured Output and JSON to enforce the format.
Common pitfalls
- OCR-ing a PDF that already has text. Most PDFs created digitally contain the exact text. Extract it directly (with
pypdf,pdfplumberor PyMuPDF), which is faster and error-free. Only scanned pages need OCR. - Low resolution. Text needs enough pixels per character. Around 300 dpi is the usual recommendation for scans, and small print in a downscaled image is unreadable for any model.
- Skew, shadows and perspective. Photographed pages need deskewing, cropping and contrast correction. Phone scanning apps do this automatically.
- Losing table structure. Plain OCR flattens tables into a jumble of numbers. Use table-aware tools or models when tables matter.
- Silent number errors. One wrong digit in an amount, date or account number is a serious error that CER barely registers. Add validation: totals that add up, check digits, date formats, and human review of low-confidence fields.
- Wrong language or script settings. Tesseract and others need the right language packs, and right-to-left scripts and vertical text need explicit support.
- Multimodal LLMs "correcting" text. A language model may silently fix a typo, normalise a date or fill in a smudged digit with a plausible guess. That is good for readability and dangerous for records. Ask for verbatim transcription, and compare against classic OCR where exactness matters.
Watch out Documents are full of personal and confidential data, such as names, addresses, ID numbers, health and financial details. Check where pages are processed (local versus a cloud API), how long they are stored, and what your data-protection obligations are before sending them anywhere. See Privacy, Data and Copyright and Using AI Safely at Work.
Where it leads
- Retrieval-Augmented Generation and Advanced RAG depend on good document parsing: clean text, preserved tables and sensible chunks.
- Multimodal LLMs increasingly replace OCR pipelines for complex but low-volume documents.
- Structured Output and JSON makes extracted fields come back as valid JSON.
- Speech Recognition shares CTC, encoder–decoder recognisers and the error-rate metrics.
- Object Detection and Image Segmentation supply the detection machinery for text and layout regions.
A bit of history
Reading machines are older than computers. Gustav Tauschek patented an optical reading device in Austria in 1929. In the 1950s and 1960s, OCR read specially designed fonts on bank documents and mail, such as the OCR-A typeface, and the US Postal Service began automated address reading. Ray Kurzweil's Reading Machine (1976) read printed books aloud to blind users using omni-font OCR. LeCun's CNNs read handwritten digits on cheques and postcodes from the late 1980s.
Tesseract was developed at Hewlett-Packard from 1985, open-sourced in 2005 and developed with Google's sponsorship afterwards. It switched to an LSTM recogniser in version 4 (2018). Deep learning reshaped every stage in the 2010s: CRNN with CTC (2015), learned text detectors (2017–2020) and layout-aware LayoutLM (2019). From 2021, OCR-free Transformers (Donut, TrOCR, Pix2Struct, Nougat) and then multimodal LLMs began to read documents end to end, so "document AI" now often means asking a model questions about a page.
Try it
- Compute the CER of
Invoice No. 2O41againstInvoice No. 2041. Then compute the word error rate. Which metric better reflects how bad the error is for a database lookup?- In
reading_order, the "Total:" line works because its boxes overlap vertically. Move "15.70" down by 12 pixels (y1=224, y2=242) and run again. What happens? Then loweroverlapto 0.2.- Try it: photograph a receipt and run it through Tesseract and through a multimodal assistant. Compare the totals, dates and item names character by character.
Hint for 1: one substitution in 16 characters gives a CER of about 0.06. But one of the three words is wrong, a WER of 0.33, and the lookup fails completely.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Tesseract OCR documentation
Documentation for Tesseract, the long-standing open-source OCR engine (LSTM-based since version 4), with guides to installation, languages and improving output quality.
PaddleOCR
A widely used open-source OCR toolkit with text detection, recognition for many languages, and document layout and table parsing.
An End-to-End Trainable Neural Network for Image-based Sequence Recognition and Its Application to Scene Text Recognition
CRNN, a CNN feature extractor plus a recurrent network trained with CTC loss to read a whole text line without segmenting characters. A classic OCR recogniser design.
TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models
Reads text-line images with a pretrained vision Transformer encoder and a text Transformer decoder, with no CNN and no CTC.
LayoutLM: Pre-training of Text and Layout for Document Image Understanding
Adds 2-D position embeddings of each word's bounding box to a BERT-style model, so it learns from both the text and the layout of scanned documents.
OCR-free Document Understanding Transformer
Donut maps a document image directly to structured output (such as JSON fields) with an encoder–decoder Transformer, skipping the separate OCR step.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/ocr-and-documents.md