DeepSeek OCR and OCR-2: How to Extract Text From Images and PDFs

Last reviewed: November 18, 2026.

DeepSeek OCR turns document images into text or structured output. DeepSeek-OCR 2 is its successor, with a redesigned visual encoder intended to improve reading order on complex pages. You can evaluate downloadable models locally, or use DeepSeek’s separately documented hosted OCR service to process files through an API.

For a new local project, OCR-2 is a sensible starting point to evaluate. For a quick PDF extraction without managing a GPU, start with the hosted service. In either case, check the extracted content against the original pages before using it in search, spreadsheets, or automated workflows.

Jump to: OCR vs. OCR-2 · Choose an access method · Official OCR API · Local setup · PDF workflow · Troubleshooting

What are DeepSeek OCR and OCR-2?

The original DeepSeek-OCR paper investigates optical context compression: representing a document page with a compact set of visual tokens, then generating its content through a language-model decoder. The goal is to make document information usable with a relatively small visual representation.

In practical terms, the model looks at a rendered page and produces text. Layout-aware extraction can retain information about headings, tables, and where content appeared. This is useful when an ordinary text copy loses the relationship between a label and its value or scrambles two columns.

The OCR-2 paper focuses on Visual Causal Flow. Its DeepEncoder V2 learns how visual information should be sequenced before the decoder generates the result. A page’s reading order is therefore a central part of the design, rather than simply its position in a rectangular grid.

DeepSeek OCR-2 Visual Causal Flow diagram showing visual token attention and sequencing.

Optical context compression describes the model’s internal representation. It does not mean the output PDF will be smaller, every transcription will be lossless, or another provider will bill the same visual-token budget.

DeepSeek OCR vs. OCR-2: the differences that matter

DeepSeek’s release announcements date the original model to October 20, 2025, and OCR-2 to January 27, 2026. The original remains relevant when maintaining an existing pipeline or reproducing its research.

ItemDeepSeek-OCRDeepSeek-OCR 2
Original model IDdeepseek-ai/DeepSeek-OCRdeepseek-ai/DeepSeek-OCR-2
Research emphasisCompact visual representations of document textImproved visual sequencing and document reading order
Visual encoderDeepEncoderDeepEncoder V2
Documented visual-input modesNative modes using 64–400 visual tokens, plus dynamic croppingDefault dynamic mode using 256–1,120 visual tokens
Repository licenseMITApache-2.0
Official DeepEncoder V2 architecture diagram from the DeepSeek OCR-2 research paper.

The input modes come from the original repository and OCR-2 repository. These visual-token counts describe image encoding, not output length or a universal pages-per-second rating.

How accurate is DeepSeek OCR-2?

In the authors’ OmniDocBench v1.5 evaluation, covering 1,355 Chinese and English pages, OCR-2 improved on the original model’s nine-crop configuration:

Metric in the paperDeepSeek-OCRDeepSeek-OCR 2
Overall score — higher is better87.3691.09
Reading-order edit distance — lower is better0.0850.057
Official OmniDocBench v1.5 benchmark comparing DeepSeek OCR and DeepSeek OCR-2 performance.

These are author-reported benchmark results. The benchmark’s overall score combines different document-parsing measures; it is not the percentage of every character that a model will recognize correctly. Keep the benchmark version and configuration attached to any comparison.

The original paper’s roughly 97% figure concerns decoding at text-to-vision token ratios below 10× in a 100-page English compression study. It is not an accuracy guarantee for receipts, handwriting, or your document collection.

Official DeepSeek-OCR benchmark charts for Fox compression and OmniDocBench performance.

For your own decision, compare the models on the same pages and settings. A higher aggregate score matters less if the system repeatedly misses the field your workflow depends on.

Choose an access method before following a tutorial

Your goalAppropriate starting pointWhat you manage
Extract a PDF or image without installing a modelDeepSeek’s hosted OCR endpointAPI access, uploads, response validation, and service charges
Run an image through OCR-2 in your environmentThe native Transformers example belowCompatible hardware, model downloads, and saved output
Run the publisher’s OCR-2 implementationThe DeepSeek-OCR-2 repository and its reference environmentCustom model code, pinned dependencies, and repository scripts
Serve many requests from your own applicationA version-matched inference server or batch pipelineDeployment, queues, authentication, memory, and monitoring

The hosted OCR reference does not identify its backend as the downloadable OCR-2 checkpoint or provide an OCR-2 selector. Evaluate the hosted service and local checkpoint separately.

Likewise, an OpenAI-compatible endpoint you deploy yourself is your service. A third-party OCR demo has its own operator and data handling. Check who receives the document before uploading private material.

Use the official DeepSeek OCR API

The OCR endpoint accepts PDFs, Word documents, PowerPoint files, and images, returning page-level results. Send multipart form data containing file and purpose.

Official DeepSeek OCR API endpoint and required file and purpose parameters.

1. Submit a document

Set your API key in the DEEPSEEK_API_KEY environment variable, put document.pdf in your working directory, and run this Bash example:

curl --silent --show-error --fail-with-body \
  "https://api.deepseek.com/v1/tools/ocr" \
  --header "Authorization: Bearer $DEEPSEEK_API_KEY" \
  --form "purpose=rich_layout_recognition" \
  --form "[email protected]" \
  --output ocr-response.json

rich_layout_recognition processes each page. text_recognition can extract text directly from Word or PowerPoint files without images. Use the documented form fields; chat-model parameters do not belong in this request.

2. Inspect the result and save each page

The response contains pages with zero-based indexes, raw text, and a finish_reason. A value of length means that page’s output is incomplete. The service guide also warns that an error object can arrive after an HTTP 200 response, so check the body.

Official DeepSeek OCR API JSON response showing page indexes, extracted text, and finish reasons.
import json
from pathlib import Path

result = json.loads(Path("ocr-response.json").read_text(encoding="utf-8"))
if "error" in result:
    raise RuntimeError(result["error"].get("message", "OCR failed"))

pages = result.get("pages")
if not isinstance(pages, list) or not pages:
    raise ValueError("No page results were returned")

folder = Path("ocr-pages")
folder.mkdir(exist_ok=True)
for page in pages:
    number = page["index"] + 1
    target = folder / f"page-{number:04d}.raw.txt"
    target.write_text(page["text"], encoding="utf-8")
    if page["finish_reason"] == "length":
        print(f"Review page {number}: output reached its limit")

print(f"Saved {len(pages)} page results to {folder}")

Preserve this raw response as your audit copy. Layout annotations may need parsing before the text is suitable for an application. Compare the number of returned pages with the source document, and review flagged pages before combining the files.

Service limits and costs

The official guide lists limits of 100 MiB, 1,000 pages, and 180 seconds per request. Meeting the file-size limit does not ensure processing finishes in time. Split demanding documents into smaller, traceable batches.

The hosted service charges by successfully recognized pages; check the linked guide for the current rate. Disconnecting a client does not necessarily stop server-side recognition. Avoid uncontrolled retries, which can repeat work that is still running.

Run DeepSeek OCR-2 locally with Transformers

This example follows Hugging Face’s versioned Transformers 5.14.0 documentation. It uses the community-converted checkpoint, deepseek-community/DeepSeek-OCR-2, with the native model implementation.

Hugging Face Transformers example for DeepSeek OCR-2 grounded Markdown extraction.

The original deepseek-ai/DeepSeek-OCR-2 instructions use custom model code and a different environment. Match the checkpoint, loading classes, and dependency versions from the same route. The native example below uses generate().

1. Prepare an isolated environment

The example targets Linux or a compatible Linux environment, Python 3.12, and an NVIDIA GPU that supports BF16. First create and activate an environment:

python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip

Install a compatible CUDA-enabled torch and torchvision pair using the official PyTorch installation selector. Then install the remaining packages:

python -m pip install "transformers==5.14.0" accelerate pillow
python -m pip check

This pins the Transformers implementation used by the example. Your PyTorch build still depends on the hardware and driver. After a successful sample run, record the resolved environment with python -m pip freeze > requirements-lock.txt.

GPU memory needs include model weights, image processing, temporary activations, and generated tokens. Image size, cropping, batching, and output length all affect the workload. Test a representative page before sizing a larger deployment; a model’s parameter label is not a complete VRAM requirement.

2. Extract a local image to grounded Markdown

Save the following as ocr_page.py, with a document image named page.png beside it. The first model load downloads the checkpoint. The output file is created by the script:

from pathlib import Path

import torch
from PIL import Image, ImageOps
from transformers import AutoModelForImageTextToText, AutoProcessor

checkpoint = "deepseek-community/DeepSeek-OCR-2"
destination = Path("output/page.grounded.mmd")
token_budget = 4096

if not torch.cuda.is_available():
    raise RuntimeError("This example needs a CUDA-enabled GPU")
if not torch.cuda.is_bf16_supported():
    raise RuntimeError("This example needs BF16 GPU support")

reader = AutoProcessor.from_pretrained(checkpoint)
network = AutoModelForImageTextToText.from_pretrained(
    checkpoint, dtype=torch.bfloat16, device_map="auto"
).eval()

with Image.open("page.png") as source:
    page_image = ImageOps.exif_transpose(source).convert("RGB")

batch = reader(
    images=page_image,
    text="<image>\n<|grounding|>Convert the document to markdown.",
    return_tensors="pt",
).to(network.device, dtype=network.dtype)

with torch.inference_mode():
    sequence = network.generate(
        **batch, do_sample=False, max_new_tokens=token_budget
    )

new_tokens = sequence[0, batch["input_ids"].shape[1]:]
document = reader.decode(new_tokens, skip_special_tokens=False)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(document, encoding="utf-8")
print(f"Saved {destination}")

if new_tokens.numel() == token_budget:
    print("Check for truncation: the output reached its token budget")
python ocr_page.py

The file contains raw grounded Markdown, including layout markers such as <|ref|> and <|det|>. Retaining those markers is intentional. Create a separate cleaned version after inspecting them, so you can trace cleanup mistakes back to the original output.

The 4,096-token ceiling is a starting choice for this example, not a promise that every page will fit. Check the end of dense pages and compare it with the source. Automatic device placement may also use memory outside the GPU; it does not guarantee that the full workload fits in GPU memory.

Choose the right OCR prompt

The OCR-2 repository documents two main task prompts. In these strings, \n represents a newline. Keep the special-token spelling exactly as shown:

TaskPrompt string
Layout-aware Markdown<image>\n<|grounding|>Convert the document to markdown.
Text extraction without layout grounding<image>\nFree OCR.

Start with a documented prompt and judge the result before adding instructions. A request to summarize or rewrite can change the goal of your workflow; preserve faithful extraction as a separate stage.

How to process PDFs and keep page order

First determine whether the PDF already contains usable text. Direct PDF text extraction may be sufficient for a digitally generated document. Scanned pages, damaged text layers, and difficult layouts are reasons to evaluate an image-based route.

The local example above reads an image. To build a PDF pipeline around it:

  1. Render pages individually. Use a PDF renderer and a resolution that preserves the smallest text you need. Compare a sample at different settings before choosing a batch configuration.
  2. Keep the model loaded. Load it once, then process page images through the same processor and model. Repeated model loading adds avoidable setup work.
  3. Retain page identity. Save document ID, page number, extraction settings, raw output, and any failure status together.
  4. Write results as you go. Use a bounded page loop or small batches instead of holding all rendered pages in memory.
  5. Reconcile the result. Check for missing, duplicated, or truncated pages before combining outputs in numerical order.

DeepSeek provides an original PDF batch runner as a separate implementation reference. Its environment belongs to the repository’s vLLM route; keep it separate from the native Transformers environment above.

Exporting Markdown or text does not add a searchable text layer to the original PDF. If your requirement is a searchable PDF, include a separate output stage that writes and verifies that text layer.

Validate text, tables, and formulas before scaling

Build a small test set that reflects the documents you will actually process. The following worksheet is a suggested evaluation method, not a report of tests performed for this guide:

Representative pageWhat to inspectUseful pass criterion
Ordinary text or a formNames, dates, identifiers, punctuation, and missing linesRequired fields match the source exactly.
Two-column documentParagraph order, headings, captions, and footnotesReading order remains coherent when converted to plain text.
Table or invoiceRow alignment, merged cells, decimal points, units, and totalsEach important value stays attached to the correct label.
Mathematical contentOperators, superscripts, subscripts, and equation boundariesKey expressions preserve the intended meaning.
Poor scan, handwriting, or mixed scriptsAmbiguous characters, omissions, repeated text, and substitutionsErrors are detected and routed for review.

For structured records, measure exact matches on the fields that drive your application. A dropped minus sign or a shifted table column can matter even when most surrounding text is correct. Track failures and correction time alongside throughput.

Keep preprocessing and generation settings constant when comparing systems. Once you change resolution, crop strategy, prompt, or token budget, record that change so you can explain differences in results.

For retrieval-augmented generation, keep source document IDs and page numbers with the extracted content. Review cleanup before chunking and indexing. OCR supplies the source material; retrieval and answer generation are additional stages, each with its own possible errors.

Common DeepSeek OCR problems and fixes

SymptomWhat to checkFirst action
Model class or architecture is unrecognizedCheckpoint and Transformers implementation may not match.Use the native checkpoint with the versioned native example, or the original checkpoint with its documented custom environment.
The model has no infer() methodThe tutorial may mix custom and native APIs.The native example uses generate(); follow one complete route.
CUDA or BF16 check failsDriver, PyTorch build, and GPU capability.Verify the selected PyTorch build and hardware before loading the model.
GPU runs out of memoryBatch size, other GPU processes, image workload, and generation length.Start with one page, reduce concurrent work, and measure memory before scaling.
Output ends halfway through a pageGeneration limit or the hosted API’s length finish reason.Flag the page as incomplete and reprocess it with an appropriate strategy.
Output contains layout tagsGrounded extraction intentionally includes annotations.Preserve the raw file; parse annotations into a separate cleaned copy.
Rows merge or paragraphs repeatSource quality, layout complexity, and the exact page result.Compare with the image, improve the input where possible, and validate the affected fields.
Combined PDF output is missing contentPage counts, per-page failures, and batch skip settings.Reconcile the output against every source page.

For hosted failures, the OCR guide distinguishes invalid requests, oversized files, account limits, and temporary service failures. Fix an invalid or unsupported file before retrying. For temporary errors, use controlled retries and preserve the original response for diagnosis.

Frequently asked questions

Is DeepSeek OCR free?

The downloadable releases have the licenses linked in the comparison table. Running them still requires computing resources, storage, and maintenance. A hosted API or third-party service has its own charges. Compare the total cost of your workflow, including corrections, rather than only the model download.

Can DeepSeek OCR-2 read handwriting and multiple languages?

The original DeepSeek-OCR paper reports multilingual document support. That is not an OCR-2 language-by-language benchmark or a handwriting guarantee. Evaluate your expected languages, scripts, scan quality, and handwriting, and route uncertain fields for review.

Does it export directly to Excel, Word, or searchable PDF?

The examples here produce text or grounded Markdown. Spreadsheet rows, Word documents, and searchable PDF text layers require additional conversion and validation. The hosted service’s ability to accept an Office file describes its input formats, not a promise to return an editable Office document.

Can I run this local example on a CPU or Mac?

The provided example explicitly requires a CUDA GPU with BF16 support. A CPU, Apple Silicon, or quantized implementation needs a separate compatible runtime and its own validation. If you want to avoid GPU setup, evaluate the hosted OCR route instead.

Is local OCR private?

Local processing gives you control over where inference runs, but privacy also depends on logs, saved page images, backups, remote tools, and access to the machine. Review the complete workflow before using confidential files. A hosted or community demo sends the file into someone else’s environment.

Sources and testing scope

This guide uses the original DeepSeek repositories and papers, the official hosted-service reference, and versioned library documentation. Benchmark numbers are attributed to their authors. The examples were reviewed against the documentation and checked for syntax; GPU inference and paid API requests were not executed for this article.