# How to OCR Handwritten and Historical Documents with AI: Model Choice and Setup

> AI Release · @ai_releaseorg · https://ai-release.org/guides/kak-raspoznat-rukopisnyy-tekst-i-starinnye-dokumenty-ne_en.html

## TL;DR

- Time to complete: 45–60 minutes
- Difficulty: Intermediate
- You will need: Python 3.9+ with `venv`, Tesseract OCR with the language pack you need, ImageMagick (v6 uses `convert`, v7 uses `magick`), one or two sample scans with a hand-typed transcription, and — for the neural option — `transformers` + PyTorch or `python-doctr`. Optional GPU speeds up neural models; exact hardware requirements per model are on its model card — check the documentation.

## What you will get

- A cleaned, grayscale/deskewed TIFF of each page plus a matching ground-truth `.txt`, so quality is measured, not guessed.
- A working OCR command for the engine you pick (Tesseract, Kraken, docTR or TrOCR) that writes one `.txt` per page into `out/`.
- A CER (character error rate — the share of characters the OCR got wrong) report per page, so you can prove a change helped instead of hoping.

## Quick start

```bash
python3 -m venv ocr-env && source ocr-env/bin/activate
pip install --upgrade pip && pip install pillow jiwer pytesseract python-doctr[torch] transformers torch
sudo apt-get install -y tesseract-ocr tesseract-ocr-eng imagemagick
mkdir -p scans gt out && tesseract --list-langs
```

Details and checks are in the steps below. On Windows use WSL2 and run the same commands inside it.

## Requirements and setup
![Illustration: Requirements and setup](https://ai-release.org/guides/img/kak-raspoznat-rukopisnyy-tekst-i-starinnye-dokumenty-ne-en-1.jpg?v=1795510207)


- Linux, macOS, or Windows with WSL2. Native Windows works for Tesseract but most neural OCR wheels expect Linux.
- Python 3.9 or newer in a virtual environment; confirm the minimum version for `python-doctr` and `transformers` in their docs.
- Tesseract installed system-wide plus a language pack (`tesseract-ocr-eng`, `tesseract-ocr-deu`, etc.). Package names differ per distro.
- Free disk: model weights range from a few hundred MB to a few GB — check the model card before downloading.
- Rights to the scans you process; historical archives often have their own reuse terms.
- A folder with 1–2 pages of your document and a hand-typed transcription of at least ~200 words. Without ground truth you cannot tell a good OCR run from a bad one.

## Step 1. Assemble a ground-truth sample and clean the scans

**What to do:** create the working tree, convert each scan to grayscale, deskew it, and type a reference transcription by hand.

**Why:** OCR quality collapses on skewed, colored or noisy scans, and every later decision (which engine, which settings) depends on comparing output to a reference text.

**Example:**

```bash
mkdir -p scans gt out
magick scans/page-001.jpg -colorspace Gray -deskew 40% -sharpen 0x1 scans/page-001-clean.tif
# ImageMagick 6: use `convert` instead of `magick`
```

`-deskew 40%` asks ImageMagick to search up to 40 degrees of rotation and straighten the page; `-sharpen 0x1` restores edge contrast lost to blur.

Then transcribe the page into `gt/page-001.txt` (UTF-8, same basename as the scan). Keep line breaks as they appear on the page — historical abbreviations, long s (`ſ`) and ligatures included.

**How to check:** run `identify scans/page-001-clean.tif`. You should see `TIFF`, a size close to the original, and `8-bit grayscale`. Open the file and confirm the text lines are horizontal.

**Checklist before moving on:**

- [ ] One cleaned TIFF per page in `scans/`
- [ ] Matching hand-typed `.txt` in `gt/`
- [ ] Page rotated so baselines are horizontal
- [ ] Text is at least ~300 px wide per line; if not, rescan at higher DPI — recommended DPI is model-specific, check the documentation

## Step 2. Pick an OCR engine and run a full-page pass
![Illustration: Step 2. Pick an OCR engine and run a full-page pass](https://ai-release.org/guides/img/kak-raspoznat-rukopisnyy-tekst-i-starinnye-dokumenty-ne-en-2.jpg?v=1795510214)


**What to do:** choose an engine from the table, run it on the clean TIFF, and write output to `out/`.

**Why:** engines differ in what they were trained on. Printed 19th-century type and cursive handwriting are different problems, and no single engine wins on both.

| Engine | Handwriting | Old printed text | How it runs |
|---|---|---|---|
| Tesseract (LSTM mode) | weak on cursive, usable on neat hands | strong with the right language pack | local CLI, `--oem 1` |
| Kraken | built for historical and handwritten scripts | good with a segmentation model | local CLI, needs a model trained on your script |
| TrOCR (Hugging Face Transformers) | trained on handwritten line images | line-level only | local Python, one text line per call |
| docTR | mixed print/handwriting | good | local Python, does detection + recognition |
| Transkribus | strongest option for archival handwriting | — | hosted service; check pricing and limits on the vendor site |

For an overview of which model families are current, see [Best AI models and neural networks in 2026](https://ai-release.org/guides/luchshie-nejroseti-i-modeli-2026.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide).

**Example — Tesseract full page:**

```bash
tesseract scans/page-001-clean.tif out/page-001 -l eng --oem 1 --psm 6
```

`--oem 1` forces the LSTM engine (no legacy engine fallback), `--psm 6` tells Tesseract the page is one uniform block of text — right for a single-column letter, wrong for a newspaper with columns (try `--psm 3`).

**Example — docTR full page:**

```python
from doctr.models import ocr_predictor

model = ocr_predictor(pretrained=True)
result = model(["scans/page-001-clean.tif"])
for page in result.pages:
    for block in page.blocks:
        for line in block.lines:
            print(" ".join(w.value for w in line.words))
```

**Example — TrOCR on a single cropped line** (it expects a line image, not a whole page, so crop first or use docTR's detector):

```python
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")
image = Image.open("scans/line-001.png").convert("RGB")
pixel_values = processor(images=image, return_tensors="pt").pixel_values
ids = model.generate(pixel_values)
print(processor.batch_decode(ids, skip_special_tokens=True)[0])
```

Model IDs and available checkpoints change — copy the exact one from the model card.

**How to check:** `head -20 out/page-001.txt` should show readable words in the right order. If you get one giant line of garbage, the page layout confused the segmenter: re-run with `--psm 3` or feed line crops instead.

## Step 3. Measure CER, fix the weakest stage, then post-correct
![Illustration: Step 3. Measure CER, fix the weakest stage, then post-correct](https://ai-release.org/guides/img/kak-raspoznat-rukopisnyy-tekst-i-starinnye-dokumenty-ne-en-3.jpg?v=1795510223)


**What to do:** score the output against `gt/page-001.txt`, change one thing at a time, and only then hand the remaining text to a language model for cleanup.

**Why:** CER turns “looks better” into a number. Most OCR errors come from one stage — binarization, segmentation, or recognition — and you can only tell which by measuring.

**Example:**

```python
import jiwer, pathlib

reference = pathlib.Path("gt/page-001.txt").read_text(encoding="utf-8")
hypothesis = pathlib.Path("out/page-001.txt").read_text(encoding="utf-8")
print("CER:", round(jiwer.cer(reference, hypothesis), 4))
print("WER:", round(jiwer.wer(reference, hypothesis), 4))
```

`jiwer` computes Levenshtein distance over characters (CER) and words (WER). Record the baseline number, change one setting (e.g. `--psm 3` instead of `6`, or a sharper binarization), re-run, compare. We publish no target CER here because it is document-specific — treat your first score as the baseline and only accept changes that lower it.

For leftover, clearly systematic mistakes (broken ligatures, `rn` for `m`), a local language model can fix spelling without seeing the image. Set it up with [How to connect n8n to a local LLM: step-by-step private automation setup with Ollama](https://ai-release.org/guides/kak-podklyuchit-n8n-k-lokalnoy-yazykovoy-modeli-poshago.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide) and constrain the prompt: “fix OCR errors only, keep line breaks and original spelling of names”.

**How to check:** the script prints a CER between 0 and 1, e.g. `CER: 0.0812`. After your post-correction pass, run the same script on the corrected file — the number must go down. If it goes up, the model rewrote historical spellings; revert.

## Troubleshooting

**Problem. Tesseract runs but finds no language data.**
- Error: `Error: Tesseract couldn't load any languages!`
- Cause: the language pack is not installed, or `TESSDATA_PREFIX` points to the wrong directory.
- Solution: install the pack (`sudo apt-get install -y tesseract-ocr-eng`), then verify with `tesseract --list-langs --tessdata-dir /usr/share/tesseract-ocr/5/tessdata`. The path differs per distro — locate it with `dpkg -L tesseract-ocr-eng | grep tessdata`.

**Problem. The neural model cannot download its weights.**
- Error: `OSError: We couldn't connect to 'https://huggingface.co' to load this file`
- Cause: the machine is offline or behind a proxy, and the weights are not in the local cache.
- Solution: download once on a connected machine, copy the cache, and point to it: `export HF_HOME=/data/hf-cache`, then set `TRANSFORMERS_OFFLINE=1` before running the script.

**Problem. A full page kills the GPU.**
- Error: `torch.cuda.OutOfMemoryError: CUDA out of memory. Tried to allocate 2.00 GiB`
- Cause: full-page images are far larger than the line-sized crops these models were trained on.
- Solution: run on CPU (`model.cpu()` / `device="cpu"`), or crop the page into lines first and process them one by one. Batch size is not the only lever — resolution is.

## Summary and next steps

You now have a cleaned page set, a measurable OCR baseline in CER, and at least one engine producing per-page text files. Next, extend the same loop to your handwriting engine of choice and wire the corrected output into a retrieval pipeline — the indexing side is covered in [How to build an AI shopping assistant on a local model](https://ai-release.org/guides/kak-sobrat-ii-pomoschnika-dlya-internet-magazina-na-lok.html?utm_source=tg&utm_medium=channel&utm_campaign=guide_inline&utm_content=guide_to_guide), whose document-loading step applies to any archive.

## FAQ

**Can Tesseract read handwriting?**
Only neat, regular handwriting. Its LSTM models are trained mainly on printed type; for cursive archival pages use Kraken with a script-specific model, TrOCR on line crops, or a hosted service such as Transkribus.

**Do I need a GPU for handwritten text recognition?**
No. Tesseract and Kraken run on CPU. Neural models like TrOCR and docTR run on CPU too, just slower per page; a GPU mainly shortens the loop when you re-run hundreds of pages.

**How accurate is OCR on 18th-century documents?**
It depends on the hand, the paper and the language, so any single number is meaningless. Build a 1–2 page ground truth, compute CER with `jiwer`, and treat that as your only reliable benchmark.

**Which is better: a cloud OCR service or a local model?**
A hosted service wins when you need a model already trained on a specific archive and cannot train one yourself; local engines win on cost control, privacy and unlimited re-runs. Hosted pricing and page limits change — check the vendor site.
