Turning a photo of a passport, ID card or form into clean, structured data used to mean chaining together image filters, a traditional OCR engine and a pile of hand-written rules. Today, a lot of that work can be done by transformer-based vision models, exported to a portable format and served through a lightweight Python API. This article is a practical guide for engineers building that kind of system. It explains how a modern document scanning pipeline fits together, where Vision Transformers help (and where they don't), how to export models to ONNX and run them quickly with ONNX Runtime, and how to serve everything with FastAPI without blocking your server. It finishes with what it takes to run a pipeline like this in production, and when it makes more sense to use an existing service.
How a document scanning pipeline works
Whatever models you use, most document scanning systems follow the same sequence. An image arrives, usually from a phone camera or a desk scanner. The system finds the document in the image, crops it and corrects perspective, so it's working with a flat, upright document rather than a photo of a table. It then works out what kind of document it is, because a German ID card, a US driver's licence and a hotel registration form all need different handling. Next comes reading: turning the pixels into text, either with an OCR model or with a model that goes straight from image to structured output. Finally, the extracted values are parsed, checked and returned as JSON.
That last step matters more than it looks. For identity documents, a lot of the reliability comes from deterministic checks rather than from the model itself: machine-readable zones (MRZ) have fixed formats and check digits, dates must be valid, and an expiry date shouldn't be before a date of birth. Treat the neural network as one stage in the pipeline, not the whole pipeline.
Vision Transformers for documents
A Vision Transformer (ViT) splits an image into small patches, turns each patch into an embedding and lets a transformer reason about how all the patches relate to each other. That global view is useful for documents, where meaning depends on layout: the same string of digits means something different next to "Date of birth" than next to "Document number".
Several families of transformer models are relevant to document scanning. Transformer OCR models such as TrOCR pair a vision encoder with a text decoder to read a cropped line or field of text, and they cope well with varied fonts and imperfect photos. OCR-free document models go further: Donut, from NAVER CLOVA, pairs a Swin Transformer image encoder with a BART text decoder and generates structured output directly from the image. Its authors designed it to avoid the downsides of a separate OCR step: the extra computing cost, OCR engines that struggle with new languages or document types, and OCR mistakes that carry through to every later stage. Layout-aware models such as the LayoutLM family combine text, position and image features and are strong at forms and key-value extraction.
Two practical cautions apply. First, check licences before you build on a pre-trained model. LayoutLMv3, for example, is a popular choice for document AI, but its published model weights are licensed under CC BY-NC-SA 4.0, a non-commercial licence. Second, generative models that write out text token by token can occasionally produce plausible but wrong values. For identity data, always validate the output: check MRZ check digits, cross-check the MRZ against the printed fields, and send low-confidence results for review rather than passing them straight to a customer record.
Transformers aren't automatically the best choice for every stage, either. Lightweight convolutional networks are still excellent for fast document detection and cropping, especially on phones, and a small classifier is often enough to tell document types apart. Many production systems mix model types and use transformers where their extra capacity pays off, usually in reading and field extraction.
Exporting models to ONNX
ONNX (Open Neural Network Exchange) is an open, standard file format for machine learning models. Exporting a model to ONNX separates training from serving: you can train in PyTorch, then run the same model in a lean inference runtime, on a different platform, or on different hardware, without shipping your training stack to production.
In recent PyTorch versions, export uses the torch.export-based exporter. Since PyTorch 2.9, dynamo=True is the default for torch.onnx.export, replacing the older TorchScript-based path, which is nearing end of life. A simple image model exports like this:
import torch
model.eval()
example = torch.randn(1, 3, 224, 224)
batch = torch.export.Dim("batch", min=1, max=32)
onnx_program = torch.onnx.export(
model,
(example,),
input_names=["pixel_values"],
output_names=["logits"],
dynamic_shapes={"pixel_values": {0: batch}}, # allow variable batch size
dynamo=True,
)
onnx_program.save("doc_classifier.onnx")Declare dynamic dimensions for anything that can change at runtime, such as batch size or image width, otherwise the exported graph will only accept the exact shape of your example input. If export fails, run torch.onnx.export() again with report=True. PyTorch will then write a Markdown report that helps you find the operator or construct causing the problem.
Encoder-decoder models like TrOCR and Donut take a little more work, because the decoder runs in a loop. They're usually exported as separate encoder and decoder graphs, with the generation loop handled in your own code or by a library such as Hugging Face Optimum. Whichever route you take, always check the exported model against the original: run the same inputs through both and compare outputs numerically before you trust the ONNX version.
Running models fast with ONNX Runtime
ONNX Runtime is the most common engine for running ONNX models in production. It plugs into hardware acceleration libraries through a system of execution providers, so the same model file can run on a plain CPU, an NVIDIA GPU through CUDA or TensorRT, Intel hardware through OpenVINO, or Apple devices through CoreML. You list providers in order of preference, and ONNX Runtime falls back to the CPU for anything the accelerator can't handle.
Quantization is the other big lever. ONNX Runtime includes Python tools that convert a model's 32-bit floating-point weights to 8-bit integers, with both dynamic and static methods. Dynamic quantization is the quickest to try and needs no calibration data:
from onnxruntime.quantization import quantize_dynamic, QuantType
quantize_dynamic(
"doc_classifier.onnx",
"doc_classifier.int8.onnx",
weight_type=QuantType.QInt8,
)Static quantization uses a calibration set of real images and can be faster still, but it takes more effort, and not every model supports it: Hugging Face Optimum, for example, currently supports only dynamic quantization for sequence-to-sequence models such as TrOCR and Donut. Quantized models are smaller and usually much faster on CPUs, but they can lose some accuracy. Measure field-level accuracy on your own documents before and after, because a small drop in a benchmark can mean a lot of misread document numbers in practice.
A few simpler habits also make a big difference: create the inference session once and reuse it, keep pre-processing (resizing, normalising) efficient, set the runtime's thread counts deliberately rather than leaving several processes fighting over the same CPU cores, and batch requests together where your latency budget allows.
Serving the model with FastAPI
FastAPI is a natural fit for model serving in Python. It's built on Starlette and Pydantic, validates requests and responses against typed models, and generates interactive OpenAPI documentation automatically, which makes your scanning API easy for other teams to try out and integrate.
The most important detail is how FastAPI runs your endpoints. Model inference is CPU- or GPU-bound work that blocks while it runs. If you put it directly inside an async def endpoint, it blocks the event loop, and every other request waits. FastAPI runs endpoints defined with plain def in a threadpool, so the simplest safe pattern is to write inference endpoints as plain def functions, or to call blocking code from an async def endpoint through run_in_threadpool. Here's a minimal document classification endpoint:
from contextlib import asynccontextmanager
import numpy as np
import onnxruntime as ort
from fastapi import FastAPI, File, HTTPException, UploadFile
from pydantic import BaseModel
LABELS = ["passport", "id_card", "driving_licence"]
state = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
# Load the model once at startup, not on every request
state["session"] = ort.InferenceSession(
"doc_classifier.int8.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
yield
state.clear()
app = FastAPI(title="Document scanning API", lifespan=lifespan)
class Prediction(BaseModel):
document_type: str
confidence: float
@app.post("/v1/classify", response_model=Prediction)
def classify(file: UploadFile = File(...)): # plain def: runs in the threadpool
if file.content_type not in {"image/jpeg", "image/png"}:
raise HTTPException(status_code=415, detail="Upload a JPEG or PNG image")
pixels = preprocess(file.file.read()) # your resize + normalise -> (1, 3, 224, 224) float32
logits = state["session"].run(None, {"pixel_values": pixels})[0][0]
probs = np.exp(logits - logits.max())
probs /= probs.sum()
best = int(probs.argmax())
return Prediction(document_type=LABELS[best], confidence=float(probs[best]))A full scanning endpoint follows the same shape, with more stages: detect and crop, classify, read the fields, then parse and validate before returning a typed response that includes per-field confidence. Keep each stage as its own function or service, so you can test, measure and replace models independently.
Taking it to production
A prototype that works on your laptop is the easy part. Running document scanning reliably for real customers brings a different set of problems.
Scaling
Run several worker processes behind a load balancer, but match the number of workers and inference threads to the cores or GPUs you actually have. For heavy models, it's often better to separate the API layer from dedicated inference workers, so slow requests don't hold up fast ones.
Accuracy you can trust
Measure what matters to the business: exact-match accuracy per field (a document number that's one character off is simply wrong), results per document type and country, and performance on real-world captures with glare, blur and odd angles, not just clean scans. Keep a labelled test set that reflects your actual traffic and run it on every new model version.
Model versioning
Version models alongside your code, record which model produced each result, and roll out new models gradually so you can compare them on live traffic and roll back quickly.
Privacy and security
Identity documents are personal data, and under GDPR they need careful handling. Process images in memory where you can, don't write documents or extracted personal data to logs, delete data as soon as it's no longer needed, encrypt everything in transit, and put authentication and rate limiting in front of the API.
Monitoring
Track latency at the median and the tail, error rates, the share of low-confidence results and the document types you're seeing. A sudden rise in low-confidence reads is often the first sign that customers are sending a new document design or that something has changed in your capture flow.
Build or buy?
Building your own document scanning stack makes sense if documents are central to your product, you have machine learning engineers to maintain it, and you need full control over models and data. The real cost isn't the first model. It's collecting and labelling training data across hundreds of document types, keeping up with new document designs, handling MRZ, barcodes and chips, and running the whole system securely around the clock.
If scanning is a feature in a bigger product, such as hotel check-in, car rental or customer onboarding, an existing API or SDK is usually faster and cheaper over time. For customer onboarding, ScanDoc for banks provides that existing API and SDK without the maintenance burden. We cover how to compare options in our guides to choosing a document data extraction solution and what a document scanning SDK is, and explain the differences between OCR, MRZ and chip reading in document information extraction.
How ScanDoc helps
ScanDoc gives you production-ready document scanning without building and maintaining the models yourself. ID and Passport Scan reads passports, ID cards and driving licences from more than 190 countries, extracts the printed details and MRZ, and returns structured, validated data through a REST API, iOS and Android SDKs and web capture.
Add-ons include NFC Verification, Face Recognition and liveness detection. The developer documentation at scandoc.readme.io shows how to integrate it into your own backend, FastAPI included.
Request a demo or try ScanDoc to test it with your own documents.
Visit the ScanDoc homepage to explore the complete document scanning and identity verification platform.
Frequently asked questions
A Vision Transformer (ViT) is a neural network that splits an image into patches and uses a transformer to model how those patches relate to each other. In document scanning, transformer models are used for reading text, understanding layout and extracting fields.
The standard term is Vision Transformer, usually shortened to ViT. You'll sometimes see "visual transformer", but it refers to the same idea.
ONNX separates training from serving. You can train in PyTorch, then run the model in ONNX Runtime on CPUs, GPUs or mobile devices, often faster and with fewer dependencies than running the training framework in production.
Not if inference blocks. Define inference endpoints with plain `def` so FastAPI runs them in its threadpool, or call the blocking code from an `async def` endpoint using `run_in_threadpool`. Running blocking inference directly inside `async def` stalls every other request.
It can. Dynamic INT8 quantization usually gives a large speed-up on CPUs with a small accuracy loss, but you should always measure field-level accuracy on your own documents before deploying a quantized model.
They can replace a traditional OCR engine for reading text, and OCR-free models like Donut can go straight from image to structured data. But for identity documents, you should still validate results with deterministic checks, such as MRZ check digits and date rules, rather than relying on the model alone.