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.

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.
| Item | DeepSeek-OCR | DeepSeek-OCR 2 |
|---|---|---|
| Original model ID | deepseek-ai/DeepSeek-OCR | deepseek-ai/DeepSeek-OCR-2 |
| Research emphasis | Compact visual representations of document text | Improved visual sequencing and document reading order |
| Visual encoder | DeepEncoder | DeepEncoder V2 |
| Documented visual-input modes | Native modes using 64–400 visual tokens, plus dynamic cropping | Default dynamic mode using 256–1,120 visual tokens |
| Repository license | MIT | Apache-2.0 |

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 paper | DeepSeek-OCR | DeepSeek-OCR 2 |
|---|---|---|
| Overall score — higher is better | 87.36 | 91.09 |
| Reading-order edit distance — lower is better | 0.085 | 0.057 |

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.

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 goal | Appropriate starting point | What you manage |
|---|---|---|
| Extract a PDF or image without installing a model | DeepSeek’s hosted OCR endpoint | API access, uploads, response validation, and service charges |
| Run an image through OCR-2 in your environment | The native Transformers example below | Compatible hardware, model downloads, and saved output |
| Run the publisher’s OCR-2 implementation | The DeepSeek-OCR-2 repository and its reference environment | Custom model code, pinned dependencies, and repository scripts |
| Serve many requests from your own application | A version-matched inference server or batch pipeline | Deployment, 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.

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.

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.

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:
| Task | Prompt 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:
- 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.
- Keep the model loaded. Load it once, then process page images through the same processor and model. Repeated model loading adds avoidable setup work.
- Retain page identity. Save document ID, page number, extraction settings, raw output, and any failure status together.
- Write results as you go. Use a bounded page loop or small batches instead of holding all rendered pages in memory.
- 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 page | What to inspect | Useful pass criterion |
|---|---|---|
| Ordinary text or a form | Names, dates, identifiers, punctuation, and missing lines | Required fields match the source exactly. |
| Two-column document | Paragraph order, headings, captions, and footnotes | Reading order remains coherent when converted to plain text. |
| Table or invoice | Row alignment, merged cells, decimal points, units, and totals | Each important value stays attached to the correct label. |
| Mathematical content | Operators, superscripts, subscripts, and equation boundaries | Key expressions preserve the intended meaning. |
| Poor scan, handwriting, or mixed scripts | Ambiguous characters, omissions, repeated text, and substitutions | Errors 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
| Symptom | What to check | First action |
|---|---|---|
| Model class or architecture is unrecognized | Checkpoint 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() method | The tutorial may mix custom and native APIs. | The native example uses generate(); follow one complete route. |
| CUDA or BF16 check fails | Driver, PyTorch build, and GPU capability. | Verify the selected PyTorch build and hardware before loading the model. |
| GPU runs out of memory | Batch 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 page | Generation limit or the hosted API’s length finish reason. | Flag the page as incomplete and reprocess it with an appropriate strategy. |
| Output contains layout tags | Grounded extraction intentionally includes annotations. | Preserve the raw file; parse annotations into a separate cleaned copy. |
| Rows merge or paragraphs repeat | Source 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 content | Page 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.
