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
pdftotextparsers 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.