Skip to content
Projetos

samestrin/llm-pdf-ocr-api

Ver no GitHub

Sobre

PDF and image to Markdown or JSON: uses the text layer first, then Tesseract OCR, then an optional vision model.

Design e mídia

Como estes números são medidos

Crescimento medido de estrelas

em 24 h
0
em 7 dias
0
em 15 dias
0
em 1 mês
0

Variações líquidas em períodos sobrepostos, não totais diários. Medições ausentes ficam em branco. Estrelas indicam interesse, não qualidade.

README.md

Original

llm-pdf-ocr-api

LLM PDF OCR logo

A small self-hosted FastAPI service, for anyone who needs the text out of PDFs, that reads a PDF page by page, scanned or not, and returns Markdown or JSON that says how each page was read.

Live demo: https://ocr.samestrin.com

Try it: bring your own API key from OpenAI, OpenRouter, Synthetic or Alibaba (DashScope), or ask me for a demo code.

CI Latest release License: MIT

Demo

A recorded session of the web page: under the sticky PDF OCR app bar with its Extract and API reference links and the theme button, Try a sample reads the bundled four-page PDF, each page's text sits beside its image with the method that read it (Text layer for the pages with a text layer, Tesseract with a confidence for the scanned ones), the find box highlights a word and steps through its matches, and the API reference at /docs opens on POST /v1/extract

The GIF is a real session, recorded by uv run python docs/make_demo_gif.py: the app runs on a local port, the bundled sample is read by the text layer and by Tesseract, and nothing is stubbed.

The web page in the light theme at desktop width, after reading a two-page PDF: the sticky PDF OCR app bar with its Extract and API reference links, the theme button and the PDF OCR title and tagline above the form, then each page's image beside its text, then the full Markdown with copy and download buttons, and the footer with the copyright, API link and version

The web page in the dark theme at desktop width, after reading a two-page PDF: the sticky PDF OCR app bar with its Extract and API reference links, the theme button and the PDF OCR title and tagline above the form, then each page's image beside its text, then the full Markdown with copy and download buttons, and the footer with the copyright, API link and version

The web page before a file is chosen: the PDF OCR app bar and title, the form with its limits and a Try a sample button, and a results panel that explains each method

Light, phone Dark, phone
The web page in the light theme at phone width, with the app bar and its menu button, the upload card, the two pages stacked and the Markdown output The web page in the dark theme at phone width, with the app bar and its menu button, the upload card, the two pages stacked and the Markdown output

The screenshots are made by uv run python docs/make_screenshots.py, with a stubbed jobs API, so they are the same on every machine.

Why

  • Running every page through OCR is slow and loses good text. Each page is read the cheapest way that works: text_layer, the PDF's own text, when it has a usable one; tesseract, OCR with Tesseract, for scanned pages, with a 0 to 1 confidence; or vision, a vision model you point it at (local or in the cloud), if you configure one.
  • You need to know how far to trust each page. The response says which way each page was read.
  • A blank page in the output hides a failure. A page that cannot be read is reported as failed with a reason; it is never returned as an empty page.
  • Long PDFs time out a single request. They can run as jobs with per-page progress.
  • Not every user has curl at hand. A web page at / reads a PDF from the browser, shows each page's image beside its text, and has a sample to try.

Install

Run the published image (no GPU and no model download; Tesseract is inside):

docker run -p 5000:5000 ghcr.io/samestrin/llm-pdf-ocr-api

Or build it from this checkout and run that:

docker build -t llm-pdf-ocr-api .
docker run -d --name api -p 5000:5000 llm-pdf-ocr-api

docker compose up runs the same image, and docker compose --profile vision up -d adds a local Ollama server for the vision backend. To run without Docker, install uv and Tesseract, then:

uv sync
uv run uvicorn llm_pdf_ocr.app:app --port 5000

Quick start

On a fresh clone, with only Docker installed:

git clone https://github.com/samestrin/llm-pdf-ocr-api
cd llm-pdf-ocr-api
docker compose up --build

Open http://localhost:5000 and press Try a sample, or drop in tests/fixtures/born_digital.pdf, a two-page PDF with a text layer. The pages show their text and say they were read by text_layer.

Or send the same file with curl from a second terminal:

curl -F file=@tests/fixtures/born_digital.pdf localhost:5000/v1/extract
## Page 1

Method: text_layer

Quarterly Report

Left column first paragraph. Revenue grew in
every region this quarter, led by strong
demand for the new product line.
...

Usage

Endpoint What it does
POST /v1/extract Read a PDF page by page and return Markdown or JSON. Fields: file, format, pages, method, model.
POST /v1/jobs, then GET /v1/jobs/{id} The same request as a job, for a long PDF: progress per page, then the result.
GET /v1/jobs/{id}/pages/{n}.png A page the job read, as a PNG.
GET /v1/capabilities The methods a request may use, the vision models it may pick, the model presets, whether demo codes work and the public notice.
GET / The web page.
GET /health Returns {"status": "ok"}.
POST /ocr Deprecated alias kept for 0.0.1. Use /v1/extract.

The interactive API reference is at /docs (Scalar), reading the raw spec at /openapi.json.

Read two pages as JSON:

curl -F [email protected] -F format=json -F pages=1-2 localhost:5000/v1/extract

Run a long PDF as a job, then follow it:

curl -F [email protected] -F format=json localhost:5000/v1/jobs
curl localhost:5000/v1/jobs/<id>

Every field, the job lifecycle and the error codes are in docs/api.md. The web page, its theme button, the sample and its screenshots are in docs/web-page.md.

Configuration

Everything is an environment variable; none is required.

Variable Default Meaning
OCR_LLM_BASE_URL empty Root of an OpenAI-compatible endpoint (ending in /v1). The vision backend is off while this is empty.
OCR_LLM_DEFAULT_MODEL none Vision model used when a request names none; required when OCR_LLM_BASE_URL is set.
OCR_LLM_ALLOWED_MODELS the default model Comma list of models a request may pick.
OCR_LLM_API_KEY empty Bearer key for the endpoint.
OCR_LLM_TIMEOUT_SECONDS 60 Per-request timeout to the vision endpoint.
OCR_LLM_CONCURRENCY 2 Vision requests in flight at once.
OCR_LLM_MAX_TOKENS 16384 Most tokens the vision model may write for one page, the visitor's preset or demo code included; a thinking model's reasoning counts against it. At most 65536. An answer cut off at this cap is a failed read (vision_failed), never a page with its end missing.
OCR_LLM_FALLBACK_TO_TESSERACT false (true in docker-compose.yml) Read a page with Tesseract when the vision model fails it.
OCR_MAX_FILE_MB 50 Largest upload; over it, 413 file_too_large. The web page states it.
OCR_MAX_PAGES 500 Most pages in one PDF; over it, 413 too_many_pages. The web page states it.
OCR_PAGE_TIMEOUT_SECONDS 120 Time allowed per page.
OCR_LOW_CONFIDENCE 0.6 A page with no usable text layer that Tesseract failed or scored under this (over 0, at most 1) is marked needs_vision; the Markdown still shows its Tesseract text after the note.
OCR_JOB_TTL_SECONDS 3600 How long a finished job's result is kept. The web page states it.
OCR_MAX_JOBS 20 Jobs held at once.
OCR_MAX_IMAGE_MB 200 Memory all held jobs may use for page images, together. Past it, a job still reads every page but renders no more images.
OCR_WEB_PAGE true Serve the web page at /. Set false for an API-only deployment: / and its files answer 404.
DEMO_GATEWAY_URL empty Internal address of the demo-code gateway (an OpenAI-compatible root ending in /v1). Demo codes work only while this is set; it is never returned to a caller.
PUBLIC_DEMO_NOTICE empty A notice for a public demo, returned as notice by GET /v1/capabilities.

Vision setup, with vLLM, Ollama and cloud examples, is in Vision model backend.

Public demo

This service can run as a public demo without spending the operator's money on anonymous visitors. Reading a PDF's text layer and scanning it with Tesseract need no model, so they are free and always on. A public demo leaves the server's own OCR_LLM_* vision backend off; vision is then the one method that costs money, and a visitor turns it on for one page at a time with a demo code or their own provider key.

  • Free, no key or code: text_layer and tesseract reads, through the web page, POST /v1/extract or a job. A page with no usable text layer is still read by Tesseract and returned, with a note when the result is doubtful.
  • Needs a demo code or key: a page that auto read with Tesseract and failed, or scored under OCR_LOW_CONFIDENCE, is marked needs_vision with the reason. On the web page, press Read with a vision model on that page; the Model access panel above the form holds the credentials. Through the API, call POST /v1/jobs/{id}/pages/{n}/vision for that page.
  • Demo code: the operator hands one out. The page sends it as X-Demo-Code; the service forwards it to the operator's internal demo gateway, which holds the provider key and the code's budget. Demo codes are offered only when the operator sets DEMO_GATEWAY_URL (demo_available in /v1/capabilities). A code whose budget is spent is told this demo code is used up or expired; a gateway that is only rate limiting says the provider is limiting requests, and that read may be tried again.
  • Your own key: choose a preset on the page and paste your key, or send X-Model-Preset with X-Model-Key. Only a preset id is accepted; a request can never name a base URL.
  • Where the key lives: only in your browser, in sessionStorage by default or localStorage when you tick Remember on this device, and only in the request headers of the vision read. The service uses it for that one request and never stores or logs it. This applies to the page route only: POST /v1/extract and POST /v1/jobs always use the operator's own OCR_LLM_* backend and ignore the credential headers, so whole-document vision stays an operator setting.
Preset X-Model-Preset Vision model Notes
OpenAI openai gpt-5-nano Model name from OpenAI's documentation; not yet checked with a real key.
OpenRouter openrouter qwen/qwen3.7-flash No speech model (not used here).
Synthetic synthetic syn:small:vision No embeddings or speech model in its public catalog (neither is used here).
Alibaba (DashScope intl) alibaba qwen-vl-plus No OpenAI-compatible speech model (not used here); model name from Alibaba's documentation and not yet checked with a real key.
Demo code demo demo-vision Only when DEMO_GATEWAY_URL is set; the gateway holds the provider key.

This service uses only each preset's vision model. A preset that fails a real-key check is marked as a gap in this table. The page side of the panel is in The web page; the headers and the route are in the API reference.

Performance

Twenty freely licensed PDFs (born-digital, two-column, tables, forms, scans and poor scans) with reference text, in benchmarks/. Results from uv run python benchmarks/run.py, in the run of 2026-11-16 with Tesseract 5.5.4 and, for the vision row, qwen2.5vl:7b served by a local Ollama on an Apple M4 Mac mini, committed in benchmarks/results/2026-11-16.md (raw results in 2026-11-16.json), which also has the per-document rows. The results file does not record the machine.

Method Text score (1 − CER) Table F1 Seconds per page Failed pages
text_layer 0.557 0.000 0.01 7
tesseract 0.702 0.000 2.47 0
vision 0.786 0.682 30.78 0

A document with a failed page scores 0, so text_layer is penalised for the seven scanned pages it cannot read (it fails them rather than guessing). Neither plain-text method recovers Markdown tables, so Table F1 is 0 for both. The vision row is from one run against a local Ollama with qwen2.5vl:7b; its seconds per page depend on that machine.

To run the vision row yourself, locally with Ollama:

docker compose --profile vision up -d
docker compose exec ollama ollama pull qwen2.5vl:7b
export OCR_LLM_BASE_URL=http://localhost:11434/v1
export OCR_LLM_DEFAULT_MODEL=qwen2.5vl:7b
export OCR_LLM_TIMEOUT_SECONDS=300
uv run python benchmarks/run.py

The 2026-11-16 row was run this way against a local Ollama. The result file names the model (qwen2.5vl:7b) only, never the endpoint URL or a key.

How it works

  1. The upload is checked against the limits while it arrives, and the selected pages are opened with PyMuPDF.
  2. With method=auto, each page uses its text layer when it is usable, else the vision model if the operator configured one, else Tesseract.
  3. Each page's result names its method (and its model or confidence); a page that fails carries an error code and message, and the other pages are still returned.
  4. A job does the same in a background thread of the one process, and also renders each page as a PNG for the web page.

Limits

  • Jobs are held in the service's memory and run one at a time. Run a single uvicorn worker, as the Docker image does, and expect jobs to be lost on a restart.
  • Uploads are limited to 50 MB and 500 pages by default (OCR_MAX_FILE_MB, OCR_MAX_PAGES); a page gets 120 seconds (OCR_PAGE_TIMEOUT_SECONDS).
  • A finished job's result and page images are kept for 3600 seconds by default (OCR_JOB_TTL_SECONDS), then deleted; at most 20 jobs are held at once (OCR_MAX_JOBS).
  • A job drops its PDF when it ends, unless a page is marked needs_vision (no usable text layer, and Tesseract failed or scored under OCR_LOW_CONFIDENCE): then it keeps the PDF in memory until it expires, so that page can be read with a vision model (POST /v1/jobs/{id}/pages/{n}/vision). These PDFs take at most OCR_MAX_FILE_MB x OCR_MAX_JOBS (1000 MB by default).
  • Neither text_layer nor tesseract recovers Markdown tables (Table F1 0 in the benchmark). The vision method recovers tables (Table F1 0.682 with qwen2.5vl:7b) but takes about 30 seconds a page on local hardware.
  • There is no auth. Put an auth proxy in front before you expose it to a network you do not trust.
  • The web page's copy button needs localhost or HTTPS, as the browser allows the clipboard only there.

Documentation

Development

uv sync
uv run playwright install chromium   # for the browser tests and the screenshots
uv run pytest                        # tests, with an 80% coverage gate
uv run ruff check . && uv run ruff format --check .
uv run python docs/make_screenshots.py
uv run python docs/make_demo_gif.py    # the README demo GIF, a real session (needs Tesseract)
uv run python tests/fixtures/make_fixtures.py

The tests that read scanned pages need Tesseract installed. Contributions are welcome: fork the repository and open a pull request.

Changelog

See CHANGELOG.md.

License

MIT; see LICENSE.

Explore projetos relacionados

Carregando…