Kosmos-2.5 OCR, tested on a Mac
98.7%
of words found, 10-page scan
Free script, 40 lines
40 s for the scan PDF
4 of 4 formulas as right LaTeX
-
Run
pip install "transformers>=4.56" torch pillow. - For PDFs, also run
brew install poppler. - Save kosmos.py, also below.
- Run
python kosmos.py scan.pdf > scan.md.
kosmos.py
# kosmos.py: Kosmos-2.5 reads a PDF or images, Markdown out.
# pip install "transformers>=4.56" torch pillow (PDFs also need poppler's pdftoppm)
# python kosmos.py scan.pdf > scan.md
import html, re, subprocess, sys, tempfile
from pathlib import Path
import torch
from PIL import Image
from transformers import AutoProcessor, Kosmos2_5ForConditionalGeneration
REPO = "microsoft/kosmos-2.5"
dev = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
dtype = torch.bfloat16 if dev == "mps" or (dev == "cuda" and torch.cuda.is_bf16_supported()) else torch.float32
model = Kosmos2_5ForConditionalGeneration.from_pretrained(REPO, dtype=dtype).to(dev)
proc = AutoProcessor.from_pretrained(REPO)
def clean(t): # HTML entities, > quote marks, spaces before ; : ? ! and inside quotes
t = re.sub(r"^(?:>[ \t]?)+", "", html.unescape(t), flags=re.M)
t = re.sub(r" +([;:?!])", r"\1", t)
t = re.sub(r'(^|\s)" (?=\S)', r'\1"', t)
return re.sub(r'(?<=\S) "(?=\s|$)', '"', t)
def pages(path):
if path.suffix.lower() != ".pdf":
return [path]
d = tempfile.mkdtemp()
subprocess.run(["pdftoppm", "-r", "200", "-jpeg", "-jpegopt", "quality=95", str(path), f"{d}/p"], check=True)
return sorted(Path(d).glob("p-*.jpg"))
for f in [p for a in sys.argv[1:] for p in pages(Path(a))]:
inputs = proc(text="<md>", images=Image.open(f).convert("RGB"), return_tensors="pt")
inputs.pop("height"), inputs.pop("width")
inputs = {k: v.to(dev) for k, v in inputs.items() if v is not None}
inputs["flattened_patches"] = inputs["flattened_patches"].to(dtype)
ids = model.generate(**inputs, max_new_tokens=4096) # the card's 1024 cuts dense pages
text = proc.batch_decode(ids, skip_special_tokens=True)[0].replace("<md>", "")
print(clean(text).strip(), end="\n\n", flush=True)
The first run downloads the 5.1 GB model from Hugging Face. Each page comes out as Markdown, with tables as HTML and formulas as LaTeX.
The script beat Tesseract on the same scan
| Run | Words found |
|---|---|
Kosmos-2.5, <ocr> plus cleanup |
1,943 |
| Kosmos-2.5, the script | 1,929 |
Kosmos-2.5, <ocr> as on the card |
1,914 |
| Our Actor | 1,879 |
| Tesseract 5.5.4 | 1,878 |
Kosmos-2.5, <md> as on the card |
1,838 |
The best models on best open source OCR found 1,954 of the same words.
Change two things from the model card
Raise max_new_tokens. The card stops at 1,024 new tokens. That fits a page of prose, but a table comes out as HTML, one tag a line, and the page gets cut.
210 of 234 cells at the card's 1,024
234 of 234 cells at 4,096
Clean the Markdown. <md> writes
> before dialogue, and a space before question
marks. The script's clean() fixes both, and 98 more words
matched.
Tables and two columns came out right
| Tool | Cells of 234 | Words in order of 644 |
|---|---|---|
| Kosmos-2.5, the script | 234 | 639 |
| Docling | 234 | 554 |
| Marker | 216 | 643 |
| MinerU | 216 | 643 |
| Our Actor | 234 | 498 |
The other tools got the PDF files. Kosmos-2.5 got only pictures of the pages.
Headings were weaker. It dropped section numbers such as 2.1, and in the report 4 of 6 headings came out as bold text.
Use the GPU, or wait
3.7 s a scan page, Mac GPU
92 s a scan page, CPU, 4 threads, low priority
bf16 and full fp32 found the same words, give or take 3, and fp32 took 1.5 times as long.
Scanned PDFs to text, no GPU
Run it yourself. Our Apify Actor reads a scanned PDF into Markdown or text, $0.006 a scanned page. On this scan it matched Tesseract, with no GPU.
Or send us the scan. Tack, our AI, does the job for $29, up to 50 pages. Printed text only.
How I tested it
- Model: microsoft/kosmos-2.5 at commit ec3c8051, transformers 5.23.0, torch 2.15.0, on an Apple M5 Max with macOS 26.6. Greedy decoding, as on the card.
- Scan: the 10 book pages of best open source OCR, proofread on Wikisource, as 1920 px JPEGs. Score: true words found in order.
- PDFs: the two Typst files of Docling vs Marker, drawn at 200 dpi, with that page's scorer. Their numbers for Docling, Marker and MinerU come from that page.
- The script's times include the model load and drawing the pages. Drawing the 10 pages as PNG took 19 s, and as JPEG 0.3 s, so the script uses JPEG.
- Our Actor: its code at build 0.1.86, run on this Mac. Tesseract 5.5.4 with its English model. Per-page GPU and CPU times: the scan PDF drawn at 200 dpi, model only.
- One job at a time, at the lowest priority. Other jobs shared the Mac.
What I did not test
- kosmos-2.5-chat, handwriting, receipts and other languages.
- Nvidia GPUs, Linux and Windows.
Sources
Questions people ask
Does Kosmos-2.5 run in Ollama?
Ollama's model search showed no Kosmos-2.5 build on Nov 18, 2026. It runs in Python with transformers 4.56 or newer, as in the script on this page.
Which Kosmos-2.5 prompt should I use, OCR or Markdown?
<ocr> returns text lines with their boxes, and it found the most words on the scan. <md> returns Markdown with headings, HTML tables and LaTeX. Use <md> when the page has tables.
Is Kosmos-2.5 free for business use?
Its model card names the MIT license, with no extra terms that I found. Read the card yourself before you ship it.