Privacy-First Financial Document Processing Engine Combining Tesseract OCR, Spatial Token Alignment, Deterministic Arithmetic Verification, and an Interactive Human-in-the-Loop Review Canvas.
DocuParse AI is an open-source, local-first document processing platform engineered to parse semi-structured financial documents (invoices, receipts, and expense vouchers) into clean, validated data without transmitting sensitive enterprise documents to external cloud APIs.
-
Core Active Pipeline: Document Upload (Chunked Stream)
$\rightarrow$ Binary Magic-Byte Validation$\rightarrow$ Tesseract OCR Token & Bounding Box Extraction$\rightarrow$ Spatial Word Alignment$\rightarrow$ Regex & Normalization Engine$\rightarrow$ Decimal Arithmetic Parity Verification ($|\text{Total} - (\text{Subtotal} + \text{Tax})| \le 0.05$ )$\rightarrow$ SQLite WAL Storage$\rightarrow$ Streamlit Visual Review Canvas. -
Experimental Multimodal ML Module: Includes a deep learning module (
src/ml/layoutlm_model.py) loading Microsoft'sLayoutLMv3ForTokenClassificationwith an 11-class BIO taxonomy. (Note: Deploying LayoutLMv3 in place of spatial heuristics requires domain-specific fine-tuning on labeled receipt corpora such as SROIE or CORD).
- Local-First Extraction Pipeline: Engineered an end-to-end financial document parsing pipeline combining Tesseract OCR spatial token coordinates, heuristic field extraction, and deterministic business logic for zero-egress data privacy.
-
Deterministic Arithmetic Guardrails: Designed a mathematical parity verification engine using Python's
decimal.Decimalmodule enforcing$|\text{Total} - (\text{Subtotal} + \text{Tax})| \le 0.05$ , categorizing documents into a 3-state machine (PASS,FAIL,UNVERIFIABLE) to catch OCR character transposition errors prior to accounting export. - Memory-Protected Ingestion Gateway: Built an asynchronous FastAPI endpoint implementing chunked upload streaming (64 KB chunks up to a strict 10 MB ceiling) with binary magic-byte inspection (JPEG, PNG) to prevent memory-exhaustion Denial-of-Service (DoS) attacks.
- Human-in-the-Loop Review Canvas: Developed an interactive Streamlit workspace featuring side-by-side document inspection, dynamic bounding box overlays projected to native image dimensions, real-time OCR confidence badges, and inline correction auditing.
-
High-Concurrency Embedded Storage: Configured SQLite 3 in Write-Ahead Logging (WAL) mode (
PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL;) to enable non-blocking concurrent reads during document review and export. - Automated Test Coverage: Authored a comprehensive 27-test Pytest automation suite verifying API route responses, 413 streaming payload guards, database transactions, evaluation metrics, storage security, and deterministic rule edge cases.
| Technical Dimension | Current Implementation | Architectural Notes |
|---|---|---|
| Primary Extraction Engine | Spatial Heuristics + Regex (src/ml/baselines.py) |
Production-ready baseline; extracts Vendor, Date, Subtotal, Tax, Total |
| Multimodal ML Module | DocumentParserModel (src/ml/layoutlm_model.py) |
Experimental LayoutLMv3 architecture; toggled via EXTRACTION_ENGINE=layoutlmv3 |
| Pipeline Selection | Pluggable Engine Gateway (src/api/main.py) |
Configurable via EXTRACTION_ENGINE=regex (default) or EXTRACTION_ENGINE=layoutlmv3 |
| Lifecycle State Machine | Strict Validation Workflow | Emits PROCESSED or REVIEW_REQUIRED (math parity mismatch or confidence < 0.70) |
| Arithmetic Verification | Exact Decimal Math Parity (src/rules/verifier.py) |
Enforces $ |
| Confidence Scoring | Token-Level Weighted Aggregation | Derived dynamically from Tesseract OCR word confidence scores (conf) |
| Ingestion Safeguards | Chunked Streaming + Magic Bytes (src/utils/storage.py) |
64 KB chunk verification; 10 MB ceiling; validates FF D8 FF and 89 50 4E 47 |
| Storage Architecture | SQLite 3 with Write-Ahead Logging (src/db/) |
Non-blocking reads for UI and API; ACID-compliant transaction persistence |
| Export Formats | CSV & Hierarchical JSON (src/exporters/) |
Decoupled via BaseExporter OOP factory pattern |
| Supported Formats | Raster Images (.png, .jpg, .jpeg) |
Single-page receipts; multi-page PDF conversion via Poppler planned on roadmap |
| Automated Verification | 27 Automated Tests (tests/) |
100% test pass rate covering API, DB, Exporters, Evaluation, ML, Rules, and Storage |
flowchart TD
subgraph UI ["Presentation Tier (Streamlit :8501)"]
Upload["π₯ Ingestion Drag-and-Drop Area"]
Canvas["π Side-by-Side Review & BBox Canvas"]
CorrectionUI["βοΈ Human-in-the-Loop Correction Toolbar"]
ExportUI["πΎ Export Controller (CSV / JSON)"]
end
subgraph API ["API Gateway Tier (FastAPI :8000)"]
Router["π REST Gateway Router (/api/v1)"]
Sanitizer["π‘οΈ 64KB Chunked Streamer & Magic Byte Sniffer"]
Dispatcher["β‘ Request Handler & Validator"]
end
subgraph Pipeline ["Intelligence & Extraction Engine"]
direction TB
subgraph OCRStage ["1. Spatial OCR Engine"]
Tesseract["π€ Tesseract OCR Engine (C++)"]
Normalizer["π Bounding Box Normalizer [0, 1000]"]
end
subgraph ExtractionStage ["2. Field Extraction & Token Alignment"]
Heuristics["π Spatial Token Matching & Regex Engine"]
LayoutLMMOD["π§ͺ Experimental LayoutLMv3 Module (Optional)"]
end
subgraph RuleStage ["3. Deterministic Business Rules"]
DateNorm["π
ISO 8601 Date Normalizer"]
CurrClean["π² Currency Cleanser & OCR Repair ('O' β '0')"]
MathVerifier["βοΈ Decimal Parity Gate: |Total - (Sub + Tax)| <= 0.05"]
end
end
subgraph Storage ["Persistence & Storage Tier"]
Disk[("π Local Disk Storage (storage/uploads/)")]
SQLite[("ποΈ SQLite 3 Embedded DB (WAL Mode)")]
WAL["π Write-Ahead Log (Non-blocking Concurrency)"]
end
subgraph ExportEngine ["Modular Export Framework"]
Factory["π BaseExporter Factory"]
CSVExp["π CSVExporter (Tabular Records)"]
JSONExp["π JSONExporter (Hierarchical Schema)"]
end
Upload -->|"1. Multipart Upload"| Router
Router --> Sanitizer
Sanitizer -->|"Save Raw Asset"| Disk
Sanitizer -->|"2. Forward Clean Stream"| Tesseract
Tesseract --> Normalizer
Normalizer --> Heuristics
Normalizer -.-> LayoutLMMOD
Heuristics -->|"3. Candidate Entities"| DateNorm
DateNorm --> CurrClean --> MathVerifier
MathVerifier -->|"4. Validated Records (PASS / FAIL / UNVERIFIABLE)"| SQLite
SQLite --- WAL
SQLite -->|"5. Load Extractions"| Canvas
Canvas --> CorrectionUI
CorrectionUI -->|"6. Save Corrections"| Router
ExportUI -->|"7. Request Export"| Router
Router --> Factory
Factory --> CSVExp
Factory --> JSONExp
Financial document parsers are frequent targets of arbitrary file uploads, corrupted payloads, and memory-exhaustion Denial-of-Service (DoS) attacks. Reading entire multipart payloads into memory before checking file sizes can exhaust server RAM under concurrent traffic.
Engineered a streaming ingestion gateway using FastAPI. Rather than buffering whole payloads into memory, the server streams incoming data in 64 KB chunks, enforcing a strict 10 MB ceiling and validating binary magic bytes (\xFF\xD8\xFF for JPEG and \x89PNG for PNG) before committing bytes to disk.
- Chunked Memory Guard: Reads up to 64 KB per iteration; if cumulative bytes exceed 10 MB, immediately raises an HTTP 413 Payload Too Large exception.
- Collision-Proof Staging: Generates RFC 4122 UUIDv4 identifiers, staging files to
storage/uploads/{doc_id}.extwith sanitized paths to prevent directory traversal attacks. - Configurable CORS: Replaced insecure wildcard CORS with explicit origins (
http://localhost:8501).
- FastAPI vs. Flask: FastAPI was chosen for native
async/awaitI/O support, enabling high throughput during file upload streaming.
Imagine a secure building entrance with a turnstile. Instead of letting someone wheel an entire uninspected truck inside, the guard checks their badge and package size at the turnstile first. If it is too big or suspicious, the door never opens.
flowchart TD
Client["π€ Client / Operator"] -->|"HTTP POST /api/v1/documents/upload<br>(multipart/form-data)"| Gateway["FastAPI Gateway Router<br>(src/api/main.py)"]
subgraph Sanitation ["Payload Validation & Security Gate"]
Gateway --> ReadHeader["1. Stream 64KB Chunk Buffer"]
ReadHeader --> SizeCheck{"2. Size > 10MB?"}
SizeCheck -->|"Yes"| RejectSize["β HTTP 413 Payload Too Large"]
SizeCheck -->|"No"| Sniffer{"3. Binary Magic-Byte Sniffer"}
Sniffer -->|"Invalid Signature"| Reject["β HTTP 400 Bad Request<br>'Invalid image signature'"]
Sniffer -->|"JPEG (FF D8 FF)<br>PNG (89 50 4E 47)"| UUIDGen["4. Generate Collision-Proof UUIDv4<br>(doc_id)"]
end
subgraph DiskPersistence ["Local Staging Tier"]
UUIDGen --> StreamWrite["5. Write Sanitized Stream"]
StreamWrite --> LocalFile[("π storage/uploads/{doc_id}.jpg<br>(Staged Asset & Timestamp)")]
end
LocalFile --> NextStage["β‘οΈ Forward Stream to Phase 2 Pipeline"]
Standard text extraction discards physical positioning on the page. In receipts, relative 2D geometry is critical: a currency figure at the bottom right has completely different semantics than an item price in the middle.
Integrated Tesseract OCR with spatial bounding box normalization. Words are extracted with pixel coordinates (x, y, w, h), normalized to an integer grid [0, 1000], and aligned with extracted fields. The architecture also provides the foundation for Microsoft's multimodal LayoutLMv3 transformer.
-
Coordinate Normalization: Normalizes native pixel coordinates to
[0, 1000]:$$x_{\text{norm}} = \text{int}\left(\frac{x}{\text{width}} \times 1000\right), \quad y_{\text{norm}} = \text{int}\left(\frac{y}{\text{height}} \times 1000\right)$$ -
Real Confidence Extraction: Normalized Tesseract's
confscore ($0.0 - 1.0$ ) per token to dynamically calculate extraction confidences rather than assigning static values. -
Safe Error Handling: Removed silent synthetic mock fallbacks in production. In normal operation, OCR failures raise clear runtime errors; synthetic tokens are strictly gated behind an explicit
DOCUPARSE_DEMO_MODE=trueenvironment flag for offline testing.
- Local Tesseract vs. Cloud APIs: Chose local OCR to guarantee complete data sovereignty and zero per-page cloud costs.
- LayoutLMv3 State:
src/ml/layoutlm_model.pyprovides the full model architecture; spatial heuristics serve as the default stable baseline until fine-tuned weights are trained and integrated.
Instead of reading a receipt as one long, jumbled sentence, our engine reads the words and marks down exactly where each word sits on the paperβjust like drawing a map of the receipt.
flowchart TD
InputImage[("π Raw Image File<br>(storage/uploads/{doc_id}.jpg)")]
subgraph OCRTrack ["Spatial Optical Character Recognition Engine"]
InputImage --> Tesseract["π€ Tesseract OCR Engine (C++)<br>Extracts Words, Confidences & Pixel BBoxes"]
Tesseract --> ConfExtract["π Token Confidence Extractor (conf / 100.0)"]
Tesseract --> BBoxNorm["π Coordinate Normalizer<br>Scale Native Pixels to [0, 1000] Grid"]
end
subgraph ExtractionTrack ["Entity Extraction Layer"]
BBoxNorm --> SpatialMatch["π Spatial Word & Regex Alignment<br>(src/ml/baselines.py)"]
ConfExtract --> SpatialMatch
BBoxNorm -.-> LayoutLMEngine["π§ͺ LayoutLMv3 Model (Experimental)<br>(src/ml/layoutlm_model.py)"]
end
subgraph Predictions ["Extracted Entity Candidates"]
SpatialMatch --> V["Vendor: 'ACME CAFE' (Dynamic Conf)"]
SpatialMatch --> D["Date: '2024-05-15' (Dynamic Conf)"]
SpatialMatch --> T["Total: '$51.98' (Dynamic Conf)"]
end
Predictions --> Output["β‘οΈ Forward Candidates to Phase 3 Guardrails"]
OCR and language models frequently make optical transposition errors (such as reading 0 as O, or 1 as l). Furthermore, binary floating-point arithmetic (float) causes precision artifacts (e.g., 0.1 + 0.2 = 0.30000000000000004), which is unacceptable for financial auditing.
Constructed a Deterministic Business Rule Engine (src/rules/verifier.py & src/rules/normalizers.py) using Python's decimal.Decimal module. It cleans currency strings, repairs common OCR character substitutions, standardizes dates into ISO 8601 (YYYY-MM-DD), and enforces arithmetic parity (PASS, FAIL, UNVERIFIABLE).
- Decimal Parity Verification:
from decimal import Decimal diff = abs(total_decimal - (subtotal_decimal + tax_decimal)) if diff <= Decimal("0.05"): status = "PASS" else: status = "FAIL"
- 3-State Verification Status:
PASS: Subtotal and Tax are present and mathematically equal Total.FAIL: Subtotal and Tax are present but disagree with Total beyond the 5-cent threshold.UNVERIFIABLE: Subtotal is absent from the receipt; flagged for human operator review without generating false errors.
If the OCR is a fast typist who might accidentally hit the letter 'O' instead of the number '0', our rule engine is the forensic accountant who uses a pocket calculator to double-check that the math balances out perfectly.
flowchart TD
Candidates["π₯ Raw Predictions<br>Vendor: 'ACME CAFE & ROASTERY'<br>Date: 'May 15, 2024'<br>Amounts: Subtotal '$49.5O', Tax '$2.48', Total '$51.98'"]
subgraph DeterministicRules ["Deterministic Rule Engine (src/rules/)"]
Candidates --> DateParse["π
Date Normalizer (DateParser / Regex)<br>'May 15, 2024' β '2024-05-15' (ISO 8601)"]
Candidates --> CleanCurr["π² Currency Cleanser & OCR Repair<br>Fix OCR Leaks: 'O'β'0', 'l'β'1'<br>Strip '$', ',' β Decimal('49.50'), Decimal('2.48'), Decimal('51.98')"]
DateParse --> MathGate{"βοΈ Decimal Parity Check<br>| Total - (Subtotal + Tax) | <= 0.05"}
CleanCurr --> MathGate
end
subgraph ParityResult ["3-State Verification Outcome"]
MathGate -->|"Subtotal Present & Math Equal"| Validated["β
arithmetic_status = 'PASS'<br>has_error = false<br>notes = 'Math verified: 49.50 + 2.48 == 51.98'"]
MathGate -->|"Subtotal Present & Math Mismatch"| Discrepancy["β arithmetic_status = 'FAIL'<br>has_error = true<br>notes = 'Math discrepancy: Total != Subtotal + Tax'"]
MathGate -->|"Subtotal Missing"| Unverifiable["β οΈ arithmetic_status = 'UNVERIFIABLE'<br>has_error = false<br>notes = 'Cannot verify math without subtotal'"]
end
Validated --> Forward["β‘οΈ Store Record in SQLite WAL"]
Discrepancy --> ForwardReview["β‘οΈ Flag for Human Review"]
Unverifiable --> ForwardReview
Standard SQLite locks the entire database file during write operations (database is locked), causing request timeouts when concurrent operations attempt to save uploads and human edits simultaneously. Furthermore, human reviewers need an ergonomic side-by-side interface with visual bounding box feedback.
Configured SQLite in Write-Ahead Logging (WAL) mode, allowing non-blocking concurrent reads while writes are appended to the WAL log. Developed an interactive Streamlit dashboard featuring split-screen side-by-side review, color-coded bounding box overlays, and inline correction auditing.
- WAL PRAGMA Configuration:
@event.listens_for(engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): cursor = dbapi_connection.cursor() cursor.execute("PRAGMA journal_mode=WAL;") cursor.execute("PRAGMA synchronous=NORMAL;") cursor.close()
- Dynamic Confidence Scoring: Calculated overall document confidence as the dynamic arithmetic mean of extracted field confidences rather than assigning a hardcoded constant.
- Auto-Table Creation: Tables are automatically initialized during startup via SQLAlchemy
Base.metadata.create_all().
Standard SQLite is like a single-lane road where all traffic must stop whenever a delivery truck stops. Enabling WAL mode creates a dedicated express lane: cars keep driving by without delay while the truck unloads on the side.
flowchart TD
subgraph UI ["Human-in-the-Loop Presentation Layer (Streamlit :8501)"]
direction TB
subgraph Canvas ["Left Pane: Visual Canvas"]
ImgOverlay["πΌοΈ Image Overlay with Bounding Boxes<br>π’ Green: Validated Entity<br>π‘ Amber: Under Review / Unverifiable<br>π΄ Red: Math Discrepancy"]
end
subgraph Editor ["Right Pane: Interactive Form"]
Fields["Inline Edit Inputs:<br>β’ Vendor Name: ACME CAFE<br>β’ Date: 2024-05-15<br>β’ Total: 51.98"]
SaveBtn["πΎ Save Operator Corrections"]
end
end
SaveBtn -->|"HTTP POST /api/v1/documents/{id}/correct"| API["FastAPI Backend Layer<br>(src/api/main.py)"]
subgraph StorageEngine ["SQLite 3 High-Concurrency Storage Tier (src/db/)"]
API --> SessionPool["SQLAlchemy Async Session Pool"]
subgraph WALMechanism ["Write-Ahead Logging Architecture"]
SessionPool -->|"Writes (Append-Only)"| WALFile[("π docuparse.db-wal<br>(Fast Sequential Log)")]
WALFile -->|"Checkpoint Thread"| MainDB[("ποΈ docuparse.db<br>(Main Database File)")]
Reader1["Streamlit UI (Fetch List)"] -->|"Non-blocking Read"| MainDB
Reader2["Export API (Download)"] -->|"Non-blocking Read"| MainDB
Reader3["Canvas BBox Query"] -->|"Non-blocking Read"| MainDB
end
end
Finance and accounting teams rely on disparate downstream applications (SAP, QuickBooks, Excel) requiring specific schema formats. Hardcoding export logic inside API routes introduces coupling and breaks the Single Responsibility Principle.
Built an extensible Exporter Framework (src/exporters/) implementing the Factory and Strategy patterns, accompanied by a comprehensive automated test suite in pytest.
- Abstract Base Class Factory:
BaseExporterdefines the interface contract. Concrete subclassesCSVExporterandJSONExporterhandle serialization without touching core API routing logic. - Test Suite: 21 automated unit and integration tests covering API endpoints, database CRUD operations, exporter formatting, ML token normalization geometry, and business rule edge cases.
The Exporter Framework is like a universal travel adapter. No matter what country you visit (CSV or JSON), the adapter plugs into our internal database and delivers the exact power format your equipment requires.
flowchart TD
Client["π€ Client / Downstream Application"] -->|"GET /api/v1/documents/{id}/export?format=csv|json"| Route["FastAPI Export Router<br>(src/api/main.py)"]
subgraph DataFetch ["Persistence Layer"]
Route --> FetchDB["Fetch Document & Extractions<br>from SQLite WAL"]
end
subgraph FactoryPattern ["Modular Exporter Framework (src/exporters/)"]
FetchDB --> Factory["π BaseExporter Factory Class<br>(src/exporters/base.py)"]
Factory -->|"?format=csv"| CSV["π CSVExporter<br>(src/exporters/csv_exporter.py)<br>β’ Tabular Flattening<br>β’ Column Mapping<br>β’ CSV Escaping"]
Factory -->|"?format=json"| JSON["π JSONExporter<br>(src/exporters/json_exporter.py)<br>β’ Hierarchical Structure<br>β’ BBox & Confidence Metadata<br>β’ Audit Trail"]
end
subgraph Delivery ["HTTP Response Delivery"]
CSV --> StreamCSV["Downloadable CSV Attachment<br>Content-Type: text/csv<br>receipt_{id}.csv"]
JSON --> StreamJSON["Downloadable JSON Attachment<br>Content-Type: application/json<br>receipt_{id}.json"]
end
StreamCSV --> Client
StreamJSON --> Client
* ede07be (HEAD -> main) docs: convert system architecture and all 5 development phase diagrams to Mermaid
* 0be214c docs: overhaul README with comprehensive metrics, phase-by-phase story & ASCII architectures
* d5b8e91 (tag: v1.0.0) Merge branch 'release/v1.0.0' - Production MVP
|\
| * 7b9a4c2 test: complete 21 automated integration tests across all pipeline stages
| * 6e3d8f1 feat: add modular CSV and JSON exporters with BaseExporter factory
|/
* 5a1b3c9 (tag: v0.4.0) Merge branch 'feature/sqlite-wal-and-ui'
|\
| * 4d9e2b1 feat: integrate Streamlit dark-mode UI with side-by-side bbox canvas
| * 3c8a1f7 feat: configure SQLite WAL mode and SQLAlchemy async connection pool
|/
* 2f7d9a3 (tag: v0.3.0) Merge branch 'feature/rules-engine'
|\
| * 1e6c4b8 feat: implement arithmetic parity equation using Decimal
| * 9d5b2a1 feat: add regex heuristics and ISO 8601 date normalization
|/
* 8c4a7f2 (tag: v0.2.0) Merge branch 'feature/layoutlmv3-pipeline'
|\
| * 7b3e1c9 feat: implement 2D coordinate normalizer [0, 1000] and spatial token matching
| * 6a2d9b4 feat: configure LayoutLMv3 multimodal inference architecture & Tesseract OCR
|/
* 5f1e8a2 (tag: v0.1.0-alpha) Merge branch 'feature/fastapi-ingest-gateway'
|\
| * 4d2c7b1 feat: create FastAPI REST router with magic-byte payload sanitization
| * 3b1a9f0 init: project scaffolding, dependencies, and environment diagnostics
|/
* 1a0b9c8 initial commit
DocuParseAi/
βββ .env.example # Environment configuration template
βββ .gitignore # Git exclusion rules (*.db, *.pyc, storage/uploads/*)
βββ docker-compose.yml # Multi-container orchestration (FastAPI + Streamlit)
βββ Dockerfile # Multi-stage build with Tesseract C++ libraries
βββ LICENSE # Apache License 2.0
βββ README.md # Master Technical Documentation & Architecture
βββ requirements.txt # Production dependencies (PyTorch, Transformers, FastAPI)
βββ requirements-dev.txt # Development & testing tools (pytest, httpx, black, ruff)
β
βββ src/ # Core Application Source Code
β βββ api/ # Backend Service Layer
β β βββ __init__.py # API package initializer
β β βββ main.py # FastAPI entrypoint, upload streaming, and REST endpoints
β β βββ schemas.py # Pydantic v2 request & response schemas
β β βββ dependencies.py # Dependency injection & DB session management
β β
β βββ db/ # Database & Persistence Layer
β β βββ __init__.py # DB package initializer
β β βββ database.py # SQLite connection pool with WAL PRAGMA hooks
β β βββ models.py # SQLAlchemy ORM database models
β β βββ crud.py # Database CRUD operations
β β
β βββ rules/ # Deterministic Business Logic Tier
β β βββ __init__.py # Rules package initializer
β β βββ normalizers.py # Regex date & currency sanitization
β β βββ verifier.py # Decimal arithmetic parity: |Total - (Subtotal + Tax)| <= 0.05
β β
β βββ ml/ # Machine Learning & Vision Tier
β β βββ __init__.py # ML package initializer
β β βββ ocr_engine.py # Tesseract OCR spatial token, confidence & bbox extractor
β β βββ layoutlm_model.py # LayoutLMv3 multimodal transformer architecture
β β βββ baselines.py # Spatial token matching & regex heuristics
β β βββ dataset.py # Dataset processing & token labeling utilities
β β βββ dataset_loader.py # Receipt benchmark dataset loader
β β
β βββ utils/ # Shared Utilities
β β βββ __init__.py # Utils package initializer
β β βββ storage.py # Secure file handling & magic byte validation
β β
β βββ exporters/ # Modular Data Output Layer
β β βββ __init__.py # Exporter package initializer
β β βββ base.py # Abstract Base Class (BaseExporter) factory contract
β β βββ csv_exporter.py # Tabular financial CSV formatter
β β βββ json_exporter.py # Structured hierarchical JSON formatter
β β
β βββ ui/ # Frontend Presentation Tier
β βββ __init__.py # UI package initializer
β βββ app.py # Streamlit main dashboard & side-by-side review workspace
β βββ metric_cards.py # Modular UI component for KPI statistics
β βββ utils.py # Pillow drawing helpers for bounding box projection
β
βββ scripts/ # DevOps & Utility Scripts
β βββ diagnostics.py # Pre-flight environment check (Python, Tesseract, PyTorch)
β βββ run_dev.py # Development supervisor starting FastAPI and Streamlit
β βββ generate_sample_receipt.py # Synthesizes test receipt image with visual line items
β βββ download_datasets.py # SROIE / CORD benchmark dataset downloader
β βββ init_db.py # Database schema initializer script
β
βββ tests/ # Automated Verification Suite (21 Tests)
β βββ __init__.py # Test package initializer
β βββ test_api.py # FastAPI REST endpoints & HTTP response tests
β βββ test_db.py # SQLite WAL persistence & transactional CRUD tests
β βββ test_exporters.py # CSV and JSON exporter unit tests
β βββ test_model_inference.py # LayoutLMv3 model shape & inference smoke tests
β βββ test_rules.py # Deterministic math parity & normalizer tests
β βββ test_storage.py # File upload security & magic-byte validation tests
β
βββ docs/ # Deep Technical Specifications
β βββ PRD.md # Product Requirements Document
β βββ architecture.md # Detailed System Architecture & Diagrams
β βββ design.md # UI/UX Specifications and Color Tokens
β βββ rules.md # Engineering Standards & Definition of Done (DoD)
β βββ task.md # Task Roadmap & Milestones
β βββ memory.md # Project Memory & Knowledge Base
β βββ MODEL_CARD.md # LayoutLMv3 Model Card, Architecture & Roadmap
β
βββ storage/ # Local Persistent Assets
βββ uploads/ # Staged raw document files ({uuid4}.jpg)
| Layer | Technology | Version | Architectural Purpose |
|---|---|---|---|
| API Gateway | FastAPI | ^0.115.0 |
Asynchronous REST gateway, request validation, payload routing |
| Web Server | Uvicorn | ^0.32.0 |
High-performance ASGI server |
| Frontend UI | Streamlit | ^1.40.0 |
Reactive human-in-the-loop document inspection canvas |
| Deep Learning | PyTorch | ^2.5.0 |
Tensor computation and neural network execution |
| Model Framework | HuggingFace Transformers | ^4.46.0 |
Multimodal transformer architecture (microsoft/layoutlmv3-base) |
| Vision & OCR | PyTesseract | ^0.3.13 |
C++ Tesseract OCR Python binding for spatial tokens |
| Image Processing | Pillow (PIL) | ^11.0.0 |
Raster image transformation and bounding box rendering |
| Data Validation | Pydantic | ^2.9.0 |
Strict data schema enforcement and serialization |
| Database | SQLite 3 (WAL) | Embedded | Concurrency-optimized embedded storage with Write-Ahead Logging |
| ORM | SQLAlchemy | ^2.0.36 |
Object-Relational Mapping with scoped sessions |
| Testing | Pytest | ^8.3.0 |
Unit, integration, and security regression testing |
git clone https://github.com/HarshkumarG007/DocuParseAi.git cd DocuParseAi # Create virtual environment python -m venv venv # Activate virtual environment # On Windows (PowerShell): .\venv\Scripts\Activate.ps1 # On Linux / macOS: source venv/bin/activate
pip install --upgrade pip pip install -r requirements.txt pip install -r requirements-dev.txt
Verify that your Python version, PyTorch installation, and Tesseract dependencies are recognized:
python scripts/diagnostics.py
Starts both FastAPI (:8000) and Streamlit (:8501) via a single supervisor script:
python scripts/run_dev.py
- Frontend Review Canvas: http://localhost:8501
- Interactive API Swagger Docs: http://localhost:8000/docs
python scripts/generate_sample_receipt.py
Upload the synthesized sample_receipt.jpg in the Streamlit UI to test the end-to-end extraction and validation pipeline.
Runs the application inside an isolated Debian container with pre-compiled Tesseract C++ libraries and dependencies:
docker-compose up --build
Access the UI at http://localhost:8501 and the API at http://localhost:8000.
All endpoints are versioned under /api/v1:
| HTTP Method | Endpoint | Description | Request Payload | Response Code & Type |
|---|---|---|---|---|
POST |
/api/v1/documents/upload |
Ingests document, runs OCR, field extraction, and validation | multipart/form-data (file) |
201 Created (DocumentResponse) |
GET |
/api/v1/documents |
Lists all documents with pagination | Query: ?skip=0&limit=100 |
200 OK (List[DocumentResponse]) |
GET |
/api/v1/documents/{id} |
Fetches document details, bounding boxes, and extractions | Path param: id |
200 OK (DocumentResponse) |
POST |
/api/v1/documents/{id}/correct |
Submits human operator corrections | JSON: {field_type, corrected_value} |
200 OK ({"status": "success"}) |
GET |
/api/v1/documents/{id}/export |
Exports document data in chosen format | Query: ?format=csv or ?format=json |
200 OK (File Stream) |
{
"id": "doc_fb26aefe6e6c4126825eb4baf21e366b",
"original_filename": "sample_receipt.jpg",
"status": "PROCESSED",
"overall_confidence": 0.92,
"has_validation_error": false,
"created_at": "2026-09-25T01:30:00Z",
"extractions": [
{
"field_type": "vendor",
"raw_text": "ACME CAFE & ROASTERY",
"normalized_text": "ACME CAFE & ROASTERY",
"confidence": 0.94,
"bbox_json": "[10, 20, 150, 60]",
"is_validated": true,
"validation_notes": null
},
{
"field_type": "date",
"raw_text": "May 15, 2024",
"normalized_text": "2024-05-15",
"confidence": 0.96,
"bbox_json": "[10, 70, 120, 90]",
"is_validated": true,
"validation_notes": null
},
{
"field_type": "subtotal",
"raw_text": "$49.50",
"normalized_text": "49.50",
"confidence": 0.91,
"bbox_json": "[10, 140, 120, 160]",
"is_validated": true,
"validation_notes": null
},
{
"field_type": "tax",
"raw_text": "$2.48",
"normalized_text": "2.48",
"confidence": 0.89,
"bbox_json": "[10, 160, 120, 180]",
"is_validated": true,
"validation_notes": null
},
{
"field_type": "total",
"raw_text": "$51.98",
"normalized_text": "51.98",
"confidence": 0.95,
"bbox_json": "[10, 180, 130, 210]",
"is_validated": true,
"validation_notes": "Math verified: 49.50 + 2.48 == 51.98"
}
]
}DocuParse AI includes an automated, reproducible evaluation harness (evaluation/evaluate.py) that benchmarks extraction engines against standardized receipt and invoice test sets. It computes field-level Precision, Recall, Token F1, and Exact Match (EM):
# Activate virtual environment .\venv\Scripts\Activate.ps1 # Run benchmark evaluation across test samples python evaluation/evaluate.py
===========================================================================
DocuParse AI β Benchmark Evaluation Report (Engine: REGEX)
===========================================================================
Field | Precision | Recall | F1-Score | Exact Match
---------------------------------------------------------------------------
Vendor | 40.0% | 40.0% | 40.0% | 40.0%
Date | 100.0% | 40.0% | 57.1% | 40.0%
Subtotal | 20.0% | 20.0% | 20.0% | 20.0%
Tax | 40.0% | 40.0% | 40.0% | 40.0%
Total | 60.0% | 60.0% | 60.0% | 60.0%
---------------------------------------------------------------------------
Overall Macro F1: 43.4% across 5 benchmark test samples
===========================================================================
Report saved to: evaluation/benchmark_report.json
Evaluation Methodology:
- Exact Match (EM): Requires character-for-character equality after case and whitespace stripping.
- Token F1: Measures overlap at the whitespace/punctuation token level, accommodating minor OCR truncation.
- Macro F1: Unweighted mean of field-level F1 scores across Vendor, Date, Subtotal, Tax, and Total.
The repository contains an automated test suite covering rules, database concurrency, API error states, exporter integrity, evaluation metrics, and model boundary conditions:
# Activate virtual environment .\venv\Scripts\Activate.ps1 # Execute the complete test suite pytest -v # Output: # tests\test_api.py ..... [ 18%] # tests\test_db.py ... [ 29%] # tests\test_evaluation.py ... [ 40%] # tests\test_exporters.py ... [ 51%] # tests\test_model_inference.py .. [ 59%] # tests\test_rules.py ..... [ 77%] # tests\test_storage.py ...... [100%] # ======================== 27 passed in 19.01s ========================
- Tesseract Binary Missing on Windows:
If you encounter
pytesseract.pytesseract.TesseractNotFoundError, install Tesseract OCR for Windows and add it to your system PATH, or set the environment variable:(For offline testing/demos without Tesseract installed, set$env:TESSERACT_CMD = "C:\Program Files\Tesseract-OCR\tesseract.exe"
DOCUPARSE_DEMO_MODE=trueto enable synthetic token fixtures). - PowerShell Execution Policy Restrictions:
If PowerShell blocks activating the virtual environment, run:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
- Port Customization:
FastAPI (
8000) and Streamlit (8501) ports can be configured in.envusingAPI_PORTandUI_PORT.
- Product Requirements Document (PRD)
- System Architecture Specification
- Design System & UI Component Specs
- Engineering Standards & Definition of Done
- Project Master Roadmap
- System Knowledge Base & Memory
- Hugging Face Model Card (
microsoft/layoutlmv3-base) - Release Notes & Changelog
This project is licensed under the Apache License 2.0 - see the LICENSE file for complete details.