Overview
How It Works
- A document gets tagged ocr-redo in Paperless (manually or through automation rules)
- The container polls for documents with that tag, downloads the original PDF
- Each page is rendered as a high-resolution image at 300 DPI using PyMuPDF
- The page image is sent to an LLM vision API with a specialized OCR prompt
- The system writes the extracted text back to Paperless's content field for full-text search, and also builds a searchable PDF artifact internally for validation and future replacement workflows
- The trigger tag is swapped for ocr-complete (or ocr-failed if something went wrong)
Multi-Page Context Awareness
- Immediate context: The last 1,500 characters of the previous page's text, so the model knows what it just read
- Rolling summary: Context notes the model writes after each page, joined into a summary capped at 1,500 characters
- Automatic condensation: Every 10 pages, older notes are shortened to make room for recent ones, which keeps the prompt size manageable for long documents
Multi-Model Fallback Chain
- Primary model processes the page. It is the most accurate one I run, currently a Gemini Flash model, but any supported provider works
- If blocked by content filters or the response is empty, it falls through to Fallback 1, a Claude Opus model in my deployment
- If that also fails, it tries Fallback 2, a Grok model, the most lenient of the three
- Every call retries transient errors, including rate limits, timeouts, and server errors, with exponential backoff: up to 5 attempts, waiting 2, 4, 8, and 16 seconds
Concurrent Processing
Why Not Just Use Tesseract?
- Handwritten notes scribbled on printed forms
- Complex tables where Tesseract loses column alignment and merges cells
- Low-contrast scans where faded text becomes unreadable
- Checkboxes and form fields that Tesseract ignores entirely
- Mixed content with printed text, stamps, signatures, and handwriting on the same page
Configuration
Tech Stack
- Python with async/await for concurrent document processing
- PyMuPDF for 300 DPI page rendering and internal searchable PDF artifact generation
- OpenAI-compatible, Anthropic, and Google Gemini SDKs for OpenAI, xAI, Anthropic, and Gemini vision OCR
- Paperless-ngx REST API for document retrieval and content updates
- Docker / Kubernetes with automated GitHub Actions CI/CD publishing to GHCR
- Exponential backoff retry logic (up to 5 attempts, 2 s base) for resilient API interaction