Quickstart Code Example

Submit a document, poll for completion, and read the text — in Python

The OCR API takes a file as a raw request body and returns layout-aware text. This page builds up a working client in four steps; the complete script is at the end.

You need an API key. Set it in your environment rather than putting it in code:

$export OCR_API_KEY='...'

Create a session

Authentication is an API key sent as a bearer token. Putting it on a requests.Session means every call below carries it.

1import os
2import requests
3
4BASE = "https://ocr.emtelligent.com"
5
6session = requests.Session()
7session.headers["Authorization"] = f"Bearer {os.environ['OCR_API_KEY']}"

Submit a document

Post the file as the raw request body — not multipart, and not a JSON wrapper. The format is detected from the file’s own bytes, so the Content-Type header is ignored; PDF, PNG, JPEG and TIFF are accepted. X-Filename sets the job’s display name and is optional.

1with open("report.pdf", "rb") as fp:
2 response = session.post(
3 f"{BASE}/jobs",
4 data=fp,
5 headers={"X-Filename": "report.pdf"},
6 )
7response.raise_for_status()
8job_id = response.json()["job_id"]

Wait for it to finish

A job moves through queuedrenderingocrdone, or ends in failed. Poll the status endpoint until it reaches a terminal state.

1import time
2
3while True:
4 status = session.get(f"{BASE}/jobs/{job_id}").json()
5 if status["state"] in ("done", "failed"):
6 break
7 time.sleep(2)
8
9if status["state"] == "failed":
10 raise RuntimeError(status.get("error") or "OCR failed")

Add ?timings=true to the status call to get per-page render and OCR durations, which is the quickest way to see where time goes on a large document.

Read the result

1result = session.get(f"{BASE}/jobs/{job_id}/result").json()

Results auto-purge after retrieval or a short retention window, so read them once and store what you need. To release the input file and rendered pages immediately:

1session.delete(f"{BASE}/jobs/{job_id}")

The whole thing

ocr_quickstart.py
1import os
2import time
3
4import requests
5
6BASE = "https://ocr.emtelligent.com"
7
8session = requests.Session()
9session.headers["Authorization"] = f"Bearer {os.environ['OCR_API_KEY']}"
10
11
12def ocr(path):
13 """Submit one file and return its OCR result."""
14 with open(path, "rb") as fp:
15 response = session.post(
16 f"{BASE}/jobs",
17 data=fp,
18 headers={"X-Filename": os.path.basename(path)},
19 )
20 response.raise_for_status()
21 job_id = response.json()["job_id"]
22
23 while True:
24 status = session.get(f"{BASE}/jobs/{job_id}").json()
25 if status["state"] in ("done", "failed"):
26 break
27 time.sleep(2)
28
29 if status["state"] == "failed":
30 raise RuntimeError(status.get("error") or "OCR failed")
31
32 return session.get(f"{BASE}/jobs/{job_id}/result").json()
33
34
35if __name__ == "__main__":
36 print(ocr("report.pdf"))

Next