DeepSeek API guide
DeepSeek OCR API: Extract Text from PDFs and Images
Send a scanned PDF or image to the standalone OCR endpoint and get recognized text back by page. DeepSeek lists OCR at $0.225 per 1,000 processed pages.
Send a PDF to the OCR endpoint
Make a POST request to https://api.deepseek.com/v1/tools/ocr with your DeepSeek API key in the Bearer header. Send two multipart fields, file with the filename and bytes, and purpose with one of the following values. DeepSeek rejects extra form fields, so omit chat parameters such as model and messages. DeepSeek OCR API reference
| Purpose | When to use it |
|---|---|
text_recognition |
Start here when you need the text from a scanned PDF. This mode also extracts embedded text directly from Word and PowerPoint documents that contain no images. |
rich_layout_recognition |
Use this when you want page-by-page recognition even for Word and PowerPoint files that contain no images. The OCR response can include text and region coordinates for your own layout processing. |
DeepSeek recognizes PDFs page by page with either purpose. It also accepts Word, PowerPoint, and common image formats. The service detects the type from the file content. DeepSeek OCR guide
Python example for a scanned PDF or image
For a small test, use a one-page PDF scan that you own. A sheet with a few lines of sample text works well. The example reads the original file without changing it, makes one paid call when you run it, and prints the recognized text to the terminal. Keep the key in the DEEPSEEK_API_KEY environment variable. Install the client with python -m pip install requests, save the code as ocr_document.py, and run python ocr_document.py sample-scan.pdf from the folder containing the file. To try an image, use python ocr_document.py sample.png.
import argparse
import mimetypes
import os
from pathlib import Path
import requests
OCR_URL = "https://api.deepseek.com/v1/tools/ocr"
MAX_FILE_BYTES = 100 * 1024 * 1024
def main():
parser = argparse.ArgumentParser(description="Read a scanned PDF or image with DeepSeek OCR.")
parser.add_argument("document", type=Path)
path = parser.parse_args().document
key = os.environ.get("DEEPSEEK_API_KEY")
if not key:
raise SystemExit("Set DEEPSEEK_API_KEY in your terminal environment.")
supported = {".pdf", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".tif", ".tiff"}
if path.suffix.lower() not in supported or not path.is_file():
raise SystemExit("Pass the path to an existing PDF or supported image.")
if not 0 < path.stat().st_size <= MAX_FILE_BYTES:
raise SystemExit("Choose a non-empty file of at most 100 MiB.")
media_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
try:
with path.open("rb") as document:
response = requests.post(
OCR_URL,
headers={"Authorization": f"Bearer {key}"},
data={"purpose": "text_recognition"},
files={"file": (path.name, document, media_type)},
timeout=(10, 200),
allow_redirects=False,
)
except requests.RequestException as exc:
raise SystemExit(
f"Request interrupted ({type(exc).__name__}). Check before resubmitting."
) from None
try:
result = response.json()
except ValueError:
raise SystemExit(f"OCR returned HTTP {response.status_code} without JSON.") from None
if not isinstance(result, dict):
raise SystemExit("Unexpected response from OCR.")
error = result.get("error")
if response.status_code != 200 or "error" in result:
message = "See the OCR error guide."
if isinstance(error, dict):
message = error.get("message") or message
raise SystemExit(f"OCR failed (HTTP {response.status_code}): {message}")
pages = result.get("pages")
page_count = result.get("page_count")
if (
result.get("object") != "ocr.result"
or not isinstance(pages, list)
or page_count != len(pages)
):
raise SystemExit("Unexpected OCR result shape.")
print(f"{page_count} pages, recognition ID: {result['id']}")
incomplete = False
for page in pages:
number = page["index"] + 1
print(f"\nPage {number}")
print(page["text"])
if page["finish_reason"] != "stop":
print(f"Page {number} is incomplete ({page['finish_reason']}).")
incomplete = True
return 2 if incomplete else 0
if __name__ == "__main__":
raise SystemExit(main())
Let requests set the multipart boundary and content type. The example uses a 10-second connect timeout and a 200-second read timeout. The read timeout measures inactivity. Set any gateway or job timeout to accommodate DeepSeek's 180-second processing window and network overhead. During recognition the service may send blank lines, followed by a single JSON object. The script parses that object and checks for an error even if the HTTP status is 200. DeepSeek OCR guide
Read the result one page at a time
This is an illustrative response using fictional document content and sample token counts. It shows the response structure from the reference.
{
"id": "ocr-00000000-0000-4000-8000-000000000001",
"object": "ocr.result",
"created": 1795046400,
"purpose": "text_recognition",
"page_count": 1,
"pages": [
{
"index": 0,
"text": "Sample packing slip\nBox A: 12 pencils\nBox B: 6 notebooks",
"finish_reason": "stop"
}
],
"usage": { "input_tokens": 880, "output_tokens": 24, "total_tokens": 904 }
}
pages[].index starts at zero. Keep that index alongside the text so you can trace a result back to the source page. DeepSeek marks a page that reaches its output limit with finish_reason: length; hold that page for review before importing the text. A stop status means recognition finished, so spot-check figures, dates, and identifiers before relying on them. DeepSeek OCR API reference
Real output may include region markers such as <|ref|> and <|box|> in pages[].text. Coordinates count from the upper left and are scaled from 0 to 1000 relative to the page dimensions. Keep the raw output for troubleshooting and make a separate copy for your display or search index. DeepSeek OCR response guide
DeepSeek OCR pricing per page
At the published USD rate, multiply the returned page_count by $0.000225. The OCR token totals in usage are informational. These estimates cover a single successful recognition of each page. A 10,000-page job needs multiple uploads because each document has a 1,000-page limit. Pricing checked November 19, 2026. DeepSeek tool pricing
| Pages | Estimated OCR cost |
|---|---|
| 10 | $0.00225 |
| 100 | $0.0225 |
| 1,000 | $0.225 |
| 10,000 | $2.25 |
DeepSeek charges for completed recognitions using the result's page_count. Service-side failures and timeouts are unbilled. Once DeepSeek receives a file, a dropped client connection can leave recognition running, and DeepSeek bills it if it completes. Check the first attempt before submitting the same file again. DeepSeek OCR billing
Standalone OCR or File Parsing?
| Your goal | Use | What comes back |
|---|---|---|
| Add scanned-page text to your own search index or review screen | Standalone OCR at POST /v1/tools/ocr |
Page text in the response, with any region markers present in the text. This request creates no Files API entry. |
| Ask DeepSeek questions about a PDF or summarize it in chat | File Parsing at POST /files, followed by a deepseek-flash request that references its file_id |
An ID after parsing, then an answer from the chat model. Use rich layout parsing when relevant charts or images should be passed into the model. |
DeepSeek quotes the same per-page rate for OCR and File Parsing. File Parsing incurs its page charge when upload parsing succeeds. Conversations that reference the parsed file then incur model token charges. DeepSeek File Parsing guide
Fix common OCR errors without losing the original
| What you see | What to check |
|---|---|
| HTTP 400 or a JSON error about the file | Confirm you sent just purpose and a multipart file with a filename. Try opening the original locally. If the file is damaged, export a fresh copy. For a password-protected document, create an unlocked copy only if you are authorized to open and upload it. |
| HTTP 402 | Check your API balance before sending another request. |
| HTTP 408, 413, or a page-limit error | Keep each file at or below 100 MiB and at or below 1,000 pages. A valid upload must finish within 120 seconds with no pause over 30 seconds. Export a smaller chunk to a new file to preserve the original. |
| HTTP 429 | Queue requests and keep fewer recognitions in flight. DeepSeek allows up to 15 OCR recognitions per account at a time, separate from chat limits. |
HTTP 200 with an error body, or a local timeout |
Read the provider's JSON before retrying. If DeepSeek reports a recognition timeout, send a smaller copy. If your client alone lost the connection, investigate the first attempt before paying for another. |
| HTTP 500 or 503 | For an explicit busy or internal error, retry later with bounded backoff. Start with a test page before resuming a large batch. |
finish_reason: length or garbled text |
Keep the output separate from approved data. Check the source page for blur, rotation or dense layout, and retry only the affected page on a clean copy. |
The timeout budget is 180 seconds from the start of the upload, including recognition. Log the HTTP status, job ID if one is returned, and completion state so you can match each result to its file. Keep credentials and document text out of shared logs. DeepSeek OCR limits and errors
Frequently asked questions
How much does the DeepSeek OCR API cost?
DeepSeek lists $0.225 per 1,000 pages, equivalent to $0.000225 per page. Billing uses the successful result’s page_count. Requests that fail recognition or time out at DeepSeek are unbilled.
Can the DeepSeek OCR API read a scanned PDF?
Yes. Upload a PDF with purpose set to text_recognition to receive the recognized text by page. The endpoint accepts up to 100 MiB and 1,000 pages per document.
Should I use OCR or the DeepSeek Files API for PDF questions?
Use standalone OCR when your own app needs page text or coordinates. For document questions in DeepSeek chat, upload it with the Files API, then reference the returned file_id in a deepseek-flash request. Choose rich layout parsing when the model needs to see figures in the document.
Why did the OCR API return HTTP 200 with an error?
DeepSeek can send HTTP 200 when recognition starts. If recognition fails after that, the JSON body contains an error object. Check the JSON body before treating the job as successful.
Can a client timeout cause a second OCR charge?
A client timeout can leave accepted work running, and that request is billed if it completes. A repeat upload can start another billable recognition. Use the recorded response or your job logs to resolve the first attempt before resubmitting.