HomeCase studiesEnterprise AI Document Analyzer with Layout-Aware OCR...

Case study · Frankfurt, Germany

Enterprise AI Document Analyzer with Layout-Aware OCR and Cited Vector Retrieval

Enterprise Document Intelligence

Legal, procurement, and compliance analysts lose days cross-referencing scanned contracts, multi-column financial filings, and vendor annexes that break standard text extractors. We built an enterprise AI document analyzer in Python combining layout-aware OCR, structural table reconstruction, and a Vector Database for hybrid semantic and lexical retrieval. Every extracted clause, risk flag, and natural-language answer links back to exact PDF page numbers and bounding-box coordinates so reviewers verify AI findings directly against source scans.

Industry
Enterprise Document Intelligence
Solution
An asynchronous Python document ingestion, layout-aware OCR, and vector-indexed analysis platform delivering verifiable clause extraction and cited Q&A over a web portal and API.
Platforms
Web & API
Stack
Python · FastAPI · OCR · Vector Database · PostgreSQL · Celery
Location
Frankfurt, Germany · delivered remotely
Role
Engineering, with the team behind for mobile and QA

Delivered remotely for a business based in Frankfurt, Germany. Names withheld by agreement.

Project Overview

Enterprise knowledge rarely arrives as clean Markdown. Organizations routinely ingest scanned supplier agreements, bilingual regulatory appendices, skewed customs declarations, and multi-column audit schedules containing dense footnotes and nested tables. Conventional keyword search misses paraphrased obligations, while naive text-dump LLM wrappers lose table structure and invent plausible-sounding answers without pointing to where a figure actually appeared.

We engineered an enterprise AI document analyzer in Python built for verifiable accuracy. The platform runs incoming files through a deterministic layout-aware OCR pipeline, preserves geometric bounding boxes for every paragraph and table cell, indexes normalized chunks in a Vector Database, and powers a split-screen React review workspace where every extracted field highlights its exact origin on the source page.

Ingestion & Extraction Bottlenecks

Document-heavy teams across legal, procurement, and financial operations struggled with four compounding technical barriers:

  • Broken reading order in complex PDFs: Two-column layouts, margin annotations, and rotated annex pages caused standard pdftotext parsers to interleave unrelated clauses.
  • Unstructured table collapse: Multi-page pricing schedules and compliance matrices lost row-to-column alignment, rendering downstream numerical checks unusable.
  • Zero-trust verification friction: Analysts refused to rely on AI summaries unless they could click a citation and immediately inspect the original scanned paragraph.
  • Exact-term blind spots: Pure semantic embeddings often ranked conceptually similar clauses above exact contract identifiers, SKU codes, or statutory section numbers.

Architectural Strategy

We treated document intelligence as a geometry-preserving compiler problem rather than a prompt-engineering exercise. Every ingested page is normalized into a coordinate-anchored intermediate representation before any language model sees a token.

OCR output retains block types (heading, body paragraph, table cell, header/footer) alongside normalized (x, y, width, height) bounding boxes. Chunking respects section boundaries and keeps tables intact as structured Markdown/JSON units. By storing chunk-to-coordinate mappings in PostgreSQL and embeddings in the Vector Database, retrieval responses always carry verifiable visual provenance back to the React PDF viewer.

Core Capabilities

  • Layout-Aware OCR & Table Reconstruction: Processes native PDFs, scanned TIFFs, and mobile photographs while preserving column flow and cell spans.
  • Schema-Driven Field Extraction: Users define reusable JSON extraction templates (effective dates, liability caps, renewal notice windows, governing law) executed consistently across batches.
  • Hybrid Semantic & Lexical Search: Combines dense vector similarity with keyword/BM25 scoring so both conceptual queries ("indemnity carve-outs") and literal references ("Section 14.2(b)") surface accurately.
  • Click-to-Verify Bounding Highlights: Selecting any extracted attribute or chat citation scrolls the browser canvas directly to the highlighted region on the source page.
  • API & Webhook Automation: Downstream compliance and ERP systems submit documents programmatically and receive validated extraction payloads with confidence scores.

Technical Architecture

Document processing separates synchronous API interactions from compute-heavy background pipelines. Clients upload files to signed object storage via FastAPI, triggering an asynchronous Celery DAG. Compute workers rasterize pages, execute OCR and layout segmentation, run section-aware chunking, and upsert vectors while committing structural metadata and bounding coordinates to PostgreSQL.

Flow: Encrypted Upload (FastAPI) → Celery Compute Queue → Layout-Aware OCR & Table Parser → Section Chunking & Bounding Map → Vector Database + PostgreSQL Metadata → Hybrid Retrieval & Reranking → Cited Extraction & React Highlight Viewer

Separating high-dimensional vectors from transactional state keeps query latencies predictable as document corpora grow. PostgreSQL enforces strict state transitions (queued, ocr_complete, indexed, failed) and stores exact coordinate arrays, ensuring partial pipeline failures retry cleanly at the page level without re-running expensive OCR across an entire archive.

Technology Stack

Category Technology detail
API & Orchestration Python FastAPI handling signed uploads, extraction schemas, and query APIs
OCR & Layout Engine Layout-aware OCR pipeline detecting columns, tables, headers, and bounding boxes
Semantic Index Vector Database storing dense chunk embeddings paired with tenant metadata filters
Relational Metadata PostgreSQL tracking document lineage, schema templates, and audit trails
Distributed Workers Celery worker pools executing CPU/GPU-bound page rasterization and embedding jobs
Review Workbench React and TypeScript split-pane PDF canvas with synchronized bounding-box highlights
Document Storage Encrypted object storage holding original binaries and normalized page images
Hybrid Reranking Combined dense vector similarity and BM25 lexical scoring for exact clause numbers
Export Layer Structured JSON webhook delivery and tabular spreadsheet exports for ERP systems

Engineering Trade-offs & Solutions

Engineering Challenge Solution & Trade-off
Fixed-size token chunking splits clauses and severs table headers from rows Implemented layout-aware semantic chunking that binds section headings and table headers to child chunks; increases preprocessing complexity in exchange for far cleaner extraction precision.
Pure vector search misses exact clause numbers and rare legal acronyms Added hybrid BM25 + dense retrieval with cross-encoder reranking before LLM synthesis, trading modest query latency for dependable exact-match recall.
Running OCR and extraction synchronously times out web requests on large filings Split ingestion into page-parallel Celery tasks with WebSocket/polling status updates, requiring idempotent page-merge steps but supporting arbitrary document sizes.
Storing full-page bounding geometry inside vector payloads bloats index memory Kept only compact chunk IDs and filter metadata inside the Vector Database while hydrating full coordinate polygons from PostgreSQL on citation click.

Security & Governance

Operating across European regulatory environments in Frankfurt demanded strict data residency and auditability guarantees. Uploaded binaries are encrypted at rest with tenant-scoped keys, and temporary page images render inside short-lived signed URLs rather than public buckets.

Every query and schema extraction passes mandatory tenant-isolation predicates before touching the Vector Database, guaranteeing zero cross-tenant semantic leakage. Extraction prompts explicitly prohibit cross-document inference unless the user selects a multi-document comparison workspace, and full audit logs record which user, schema version, and model configuration produced every exported field.

Throughput & Indexing Scale

Enterprise onboarding routinely spikes when clients backfill years of legacy PDF archives alongside live daily uploads. To prevent bulk historical imports from starving interactive analysts reviewing urgent contracts, Celery workers run across prioritized queues—routing real-time single-file uploads to a fast lane while throttling multi-thousand-page archive backfills.

Page-level caching keyed by SHA-256 content hashes skips redundant OCR when duplicate boilerplate annexes appear across vendor packets. Batching embedding generation requests and tuning vector index HNSW parameters keeps interactive hybrid search responsive even as individual tenant collections scale into millions of indexed chunks.

Operational Outcomes

Pairing deterministic OCR geometry with cited vector retrieval transformed how compliance and legal teams work through dense document backlogs:

  • Auditable AI answers: Reviewers verify every extracted obligation or numeric figure in seconds using synchronized page highlights rather than re-reading entire PDFs.
  • Consistent structured outputs: Standardized extraction schemas turn heterogeneous vendor scans into clean, queryable PostgreSQL records and ERP payloads.
  • Resilience on messy scans: Layout-aware parsing and table reconstruction recover usable data from skewed faxes and multi-column filings that broke legacy scripts.
  • Controlled infrastructure scaling: Decoupled Python worker tiers handle sporadic archive backfills smoothly without degrading live search responsiveness.

01 — Questions

asked about this kind of project

Why does standard PDF text extraction fail on enterprise contracts and regulatory filings?

Many archived agreements are flat image scans, skewed faxes, or multi-column PDFs where underlying text streams scramble reading order and collapse financial tables. Layout-aware OCR reconstructs visual reading order, preserves cell relationships in tables, and records exact pixel coordinates for downstream verification.

How do you prevent hallucinations when analysts ask questions across hundreds of pages?

Query responses are grounded strictly in retrieved document chunks and must emit structured citation identifiers referencing page numbers and bounding-box spans. If retrieval confidence falls below threshold or no matching passage exists, the system explicitly reports insufficient evidence rather than synthesizing an answer.

How is tenant data isolated inside a shared Vector Database?

Every embedding record carries mandatory tenant_id and workspace_id payload attributes enforced at the API gateway layer before vector similarity executes, paired with optional collection-per-enterprise partitioning for strict regulatory accounts.

Why pair a Vector Database with PostgreSQL instead of storing everything in one engine?

The Vector Database excels at high-dimensional approximate nearest-neighbor retrieval across millions of text chunks, whereas PostgreSQL guarantees ACID transactions for user permissions, extraction rule versions, document processing state machines, and compliance audit logs.

How are large multi-hundred-page batches processed without blocking interactive queries?

Ingestion runs asynchronously on isolated Celery worker queues split by workload type—heavy PDF rasterization and OCR on compute nodes, embedding generation on batched inference workers—leaving FastAPI query endpoints responsive for interactive document review.

03 — Similar project?

describe what is different about yours

Build yours.

Tell me what exists, what you need and the deadline. Fixed price for a defined scope, or $55/day (8–9 hours work) with a written plan first.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.