Flask OCR in 41 lines, tested
97.4%
of words on 40 JPGs, RapidOCR in Flask
The app: one file, two readers
pip install flask pytesseract rapidocr onnxruntime pillow-heif
flask --app app run
curl -F [email protected] "http://127.0.0.1:5000/ocr?engine=rapid"
app.py, all 41 lines
"""Flask OCR server. POST an image as form field "file", get JSON text back.
Run: flask --app app run (production: gunicorn -w 2 app:app)
Call: curl -F [email protected] http://127.0.0.1:5000/ocr
curl -F [email protected] "http://127.0.0.1:5000/ocr?engine=rapid"
"""
import pytesseract
from flask import Flask, jsonify, request
from PIL import Image, ImageOps, UnidentifiedImageError
from pillow_heif import register_heif_opener
from rapidocr import RapidOCR
register_heif_opener() # lets Pillow open iPhone .heic photos
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 20 * 1024 * 1024 # bigger uploads get 413
# One RapidOCR for all requests: it loads its models on the first call. 1 thread was my test setting.
rapid = RapidOCR(params={"EngineConfig.onnxruntime.intra_op_num_threads": 1})
def read_image(file):
img = Image.open(file.stream)
img = ImageOps.exif_transpose(img) # phone photos are often stored sideways
img = img.convert("RGB")
img.format = "TIFF" # pytesseract hands Tesseract a temp file: TIFF is fast, PNG slow, BMP adds 96 dpi
return img
@app.post("/ocr")
def ocr():
file = request.files.get("file")
if file is None:
return jsonify(error="send the image as form field 'file'"), 400
try:
img = read_image(file)
except UnidentifiedImageError:
return jsonify(error="not an image I can open"), 415
if request.args.get("engine") == "rapid":
text = "\n".join(rapid(img).txts or ())
else:
text = pytesseract.image_to_string(img)
return jsonify(text=text)
The answer is JSON: {"text": "..."}. Leave out
?engine=rapid for Tesseract. pytesseract needs the
tesseract program too.
RapidOCR read photos, Tesseract mostly did not
| 10 JPGs of each | Tesseract | RapidOCR |
|---|---|---|
| Book scans | 96.0% | 96.9% |
| Phone photos | 31.9% | 96.9% |
| Screenshots | 79.4% | 100.0% |
| Sideways phone photos | 33.1% | 96.9% |
True words found in order. These are the 40 JPGs of JPG to text, and HTTP lost nothing: every Tesseract scan, photo and screenshot read the same as there.
A scan took a median 7.0 s with RapidOCR and 2.9 s with Tesseract, one thread each. They ran at different times, so the gap is rough.
What the usual tutorial gets wrong
The usual short version (14 lines here) passes the upload straight to the reader.
| Upload | Tutorial | This app |
|---|---|---|
| Sideways photos, Tesseract | 0.3% of words | 33.1% |
| Sideways photos, RapidOCR | 47.5% of words | 96.9% |
| A .heic photo | 500 error | 200, RapidOCR 199 of 202 words |
| 30.6 MB photo | 200 after 9.5 s (RapidOCR) | 413 (HTML) in 4 ms |
| A text file | 500 error | 415, JSON |
-
Sideways: phones store some photos turned, with an EXIF tag for up.
ImageOps.exif_transposeturns them. - RapidOCR turns them itself only when you pass a file path, not an upload.
-
HEIC: Pillow opens it only after
register_heif_opener(). -
Size: Flask 3.1.3 has no upload limit until you set
MAX_CONTENT_LENGTH.
pytesseract writes a temp file
Hand pytesseract a Pillow image and it saves the image for Tesseract,
in the format in img.format. With no format, that is PNG.
| Temp file | Pillow write, median scan | Words |
|---|---|---|
| PNG (no format) | 699 ms | Same as the file |
| TIFF | 9 ms | Same as PNG, 20 of 20 |
| BMP | 10 ms | Fewer on photos: 574, not 623 |
| JPEG (the tutorial) | 33 ms | Saved again at quality 75 |
So my app sets img.format = "TIFF". Pillow writes 96 dpi
into a BMP, and Tesseract trusts it.
RapidOCR needs the memory
| Server | At start | Peak, 40 JPGs |
|---|---|---|
| Flask, Tesseract | 88 MB | 301 MB |
| Flask, RapidOCR | 88 MB | 1,668 MB |
| Django, Tesseract | 64 MB | 276 MB |
-
Tesseract peaks count the server and its
tesseractprocess together. - RapidOCR still held 1,177 MB after the last image.
-
With
gunicorn, each worker loads its own RapidOCR: 750 and 877 MB after 4 screenshots. - Two requests at once shared one RapidOCR: the same text on 10 of 10 screenshots.
Django: the same view, plus csrf_exempt
The Django view, as tested, has no TIFF line, so pytesseract writes a PNG. It found the same words as Flask on 40 of 40 JPGs.
@csrf_exempt # curl and other API callers have no CSRF cookie: without this, 403
@require_POST
def ocr(request):
...
if file.size > MAX_BYTES:
return JsonResponse({"error": "file too large"}, status=413)
views.py, all 25 lines
"""Django view: app.py's OCR, Tesseract only, no TIFF line (PNG temp file). urls.py: path("ocr", views.ocr)."""
import pytesseract
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from PIL import Image, ImageOps, UnidentifiedImageError
from pillow_heif import register_heif_opener
register_heif_opener()
MAX_BYTES = 20 * 1024 * 1024 # Django has no size cap for uploaded files
@csrf_exempt # curl and other API callers have no CSRF cookie: without this, 403
@require_POST
def ocr(request):
file = request.FILES.get("file")
if file is None:
return JsonResponse({"error": "send the image as form field 'file'"}, status=400)
if file.size > MAX_BYTES:
return JsonResponse({"error": "file too large"}, status=413)
try:
img = ImageOps.exif_transpose(Image.open(file)).convert("RGB")
except UnidentifiedImageError:
return JsonResponse({"error": "not an image I can open"}, status=415)
return JsonResponse({"text": pytesseract.image_to_string(img)})
Django's 2.5 MB DATA_UPLOAD_MAX_MEMORY_SIZE leaves out
files. The size check runs after the upload arrives: 413 in 38 ms
here, on one machine.
No server: one call to our Actor
PDF OCR to Markdown, our Apify Actor, reads a JPG, PNG, WEBP, TIFF, HEIC or PDF by URL and returns Markdown.
curl -X POST "https://api.apify.com/v2/actors/brasspage~pdf-ocr-to-markdown/run-sync-get-dataset-items" \
-H "Authorization: Bearer $APIFY_TOKEN" \
-H "Content-Type: application/json" \
-d '{"documentUrls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"], "pages": "1-2"}'
- It turns sideways photos itself: its code found 90.0% of their words, on image to text API.
- $0.006 an image or scanned page, and digital PDF pages are free. Each run adds $0.00005 at the default 1 GB, billed to your Apify account. Files go to Apify's servers.
What I tested, and what I did not
How I tested
-
Flask 3.1.3 with its own server, threads on, and Django 6.1.3 with
runserver. - Python 3.13 on an Apple M5 Max, macOS 26.6.
- Tesseract 5.5.4 (Homebrew), pytesseract 0.3.13, RapidOCR 3.10.0 with its default models.
- onnxruntime 1.31.1, Pillow 13.0.0, pillow-heif 1.9.0.
- Requests went one at a time by curl 8.7.1. The servers ran at background priority (nice 19, taskpolicy -b), most next to a second test lane. Seconds are rough.
- Memory: resident memory of the server, plus its children, read every 50 ms with psutil. One MB here is 1,048,576 bytes.
- Scans: 10 proofread public domain book pages. Photos: the same pages on drawn desks, made up. Screenshots: 10 made-up web, chat and sheet pages.
-
Sideways photos: the photos stored turned, with EXIF Orientation
6. HEIC: the photos saved by macOS
sips. - The big file: a photo enlarged to 48 MP, with grain. Through the tutorial app, Tesseract found none of its 202 words, RapidOCR all but 1.
- RapidOCR matched the JPG to text run on 36 of 40 files. The others differ by a word or two.
- The Tesseract numbers on all 40 JPGs, and the Flask Tesseract memory row, are from this app before its TIFF line, when pytesseract wrote PNG. With TIFF, the 20 scans and photos read the same words. I did not rerun the screenshots or sideways photos.
Not tested
- FastAPI, or async views.
- PDF uploads. This app reads images only.
- Many users at once, or a real server on Linux.
- RapidOCR with all CPU threads, or a GPU. Loading it inside the route.
- Languages other than English.
Sources
- Flask MAX_CONTENT_LENGTH
- Django DATA_UPLOAD_MAX_MEMORY_SIZE
- pytesseract, RapidOCR and pillow-heif on PyPI
- My test code is in our repo folder research/bench/flask-ocr-2026-11-27.
- We make the Apify Actor, not Flask or the OCR readers.
Questions people ask
Why does my Flask OCR app return nothing for phone photos?
Phones often store a photo turned, with an EXIF tag for which way is up. Pillow ignores it until you call ImageOps.exif_transpose. On my sideways photos, Tesseract found 0.3% of words in the tutorial app, which skips that line, and 33.1% in mine.
Should I use pytesseract or RapidOCR in Flask?
RapidOCR, if you can give it the memory. It found 97.4% of the words on my test JPGs, and Tesseract 58.1%, mostly because Tesseract failed on phone photos. Its server grew to 1,668 MB.
How do I limit the upload size in Flask?
Set app.config["MAX_CONTENT_LENGTH"]. Flask has no limit by default. With a 20 MB limit, my app answered a 30.6 MB photo with 413 right away.