Skip to content

Repository files navigation

Contract Intelligence Parser

FastAPI Next.js MongoDB Docker Python TypeScript

Intelligent Contract Analysis Platform - Automatically extract, analyze, and score critical financial and legal terms from PDF contracts with advanced OCR, regex-based extraction, and optional LLM enhancement.


Overview

Contract Intelligence Parser is a production-ready document processing system designed for accounts receivable platforms and legal teams. The system automatically processes PDF contracts, extracting critical financial and operational data with confidence scoring and gap analysis to accelerate contract review workflows.

Key Value Propositions:

  • Automated Extraction: Extract 40+ critical contract fields including parties, dates, commercial terms, and legal clauses
  • Confidence Scoring: Advanced multi-signal scoring system with evidence-based validation
  • Gap Detection: Intelligent identification of missing critical information with severity assessment
  • OCR Support: Seamless processing of both digital and scanned contracts
  • Scalable Architecture: Dockerized microservices supporting concurrent document processing

Dashboard Overview Main dashboard showing contract processing pipeline and analytics

πŸ“ Project Structure

contract_intelligence_parser/
β”‚
β”œβ”€β”€ πŸ“‚ backend/                       # FastAPI backend service
β”‚   β”œβ”€β”€ app/                         # Main application code
β”‚   β”‚   β”œβ”€β”€ api/                     # API layer
β”‚   β”‚   β”‚   β”œβ”€β”€ endpoints/           # API route definitions
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ contracts.py    # Contract CRUD operations
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ health.py       # Health check endpoint
β”‚   β”‚   β”‚   β”‚   └── __init__.py
β”‚   β”‚   β”‚   β”œβ”€β”€ middleware/          # Custom middleware (CORS, auth, etc.)
β”‚   β”‚   β”‚   └── __init__.py
β”‚   β”‚   β”œβ”€β”€ core/                    # Core configuration
β”‚   β”‚   β”‚   β”œβ”€β”€ config.py           # Settings management
β”‚   β”‚   β”‚   β”œβ”€β”€ database.py         # MongoDB connection setup
β”‚   β”‚   β”‚   └── __init__.py
β”‚   β”‚   β”œβ”€β”€ models/                  # Data models
β”‚   β”‚   β”‚   β”œβ”€β”€ contract.py         # Contract document schema
β”‚   β”‚   β”‚   └── __init__.py
β”‚   β”‚   β”œβ”€β”€ services/                # Business logic
β”‚   β”‚   β”‚   β”œβ”€β”€ background_processor.py  # Async processing
β”‚   β”‚   β”‚   β”œβ”€β”€ contract_extractor.py    # Field extraction logic
β”‚   β”‚   β”‚   β”œβ”€β”€ extraction_patterns.py   # Regex patterns library
β”‚   β”‚   β”‚   β”œβ”€β”€ pdf_processor.py         # PDF/OCR processing
β”‚   β”‚   β”‚   └── __init__.py
β”‚   β”‚   β”œβ”€β”€ utils/                   # Utility functions
β”‚   β”‚   β”œβ”€β”€ main.py                  # FastAPI application entry
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ tests/                       # Backend test suite
β”‚   β”‚   β”œβ”€β”€ test_api_endpoints.py   # API route tests
β”‚   β”‚   β”œβ”€β”€ test_contract_extractor.py  # Extraction logic tests
β”‚   β”‚   β”œβ”€β”€ test_extraction_patterns.py # Pattern validation
β”‚   β”‚   └── __init__.py
β”‚   β”œβ”€β”€ uploads/                     # Temporary file storage
β”‚   β”œβ”€β”€ Dockerfile                   # Backend container definition
β”‚   β”œβ”€β”€ requirements.txt             # Python dependencies
β”‚   └── pytest.ini                   # Test configuration
β”‚
β”œβ”€β”€ πŸ“‚ frontend/                      # Next.js frontend application
β”‚   β”œβ”€β”€ src/                         # Source code
β”‚   β”‚   β”œβ”€β”€ app/                     # Next.js app directory
β”‚   β”‚   β”‚   β”œβ”€β”€ contracts/           # Contract pages
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ [id]/           # Dynamic contract detail
β”‚   β”‚   β”‚   β”‚   β”‚   └── page.tsx    # Contract detail view
β”‚   β”‚   β”‚   β”‚   └── page.tsx        # Contract list view
β”‚   β”‚   β”‚   β”œβ”€β”€ layout.tsx          # Root layout
β”‚   β”‚   β”‚   └── page.tsx            # Home/upload page
β”‚   β”‚   β”œβ”€β”€ components/              # React components
β”‚   β”‚   β”‚   β”œβ”€β”€ ui/                 # Reusable UI components
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ badge.tsx       # Status/confidence badges
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ button.tsx      # Button component
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ card.tsx        # Card layouts
β”‚   β”‚   β”‚   β”‚   └── progress.tsx    # Progress indicators
β”‚   β”‚   β”‚   β”œβ”€β”€ file-upload.tsx     # File upload component
β”‚   β”‚   β”‚   └── providers.tsx       # Context providers
β”‚   β”‚   β”œβ”€β”€ hooks/                   # Custom React hooks
β”‚   β”‚   β”œβ”€β”€ lib/                     # Utility libraries
β”‚   β”‚   β”‚   β”œβ”€β”€ api.ts              # API client
β”‚   β”‚   β”‚   └── utils.ts            # Helper functions
β”‚   β”‚   └── types/                   # TypeScript definitions
β”‚   β”‚       └── index.ts            # Type exports
β”‚   β”œβ”€β”€ public/                      # Static assets
β”‚   β”œβ”€β”€ Dockerfile                   # Frontend container definition
β”‚   β”œβ”€β”€ next.config.js              # Next.js configuration
β”‚   β”œβ”€β”€ package.json                # Node.js dependencies
β”‚   β”œβ”€β”€ postcss.config.js           # PostCSS configuration
β”‚   β”œβ”€β”€ tailwind.config.js          # Tailwind CSS configuration
β”‚   └── tsconfig.json               # TypeScript configuration
β”‚
β”œβ”€β”€ πŸ“‚ docs/                          # Documentation assets
β”‚   └── images/                      # Screenshots and diagrams
β”‚
β”œβ”€β”€ 🐳 Docker Configuration
β”‚   β”œβ”€β”€ docker-compose.yml          # Main orchestration file
β”‚   β”œβ”€β”€ docker-compose.override.yml # Development overrides
β”‚   └── .env.example                # Environment template
β”‚
β”œβ”€β”€ πŸ“š Documentation
β”‚   β”œβ”€β”€ README.md                   # This file
β”‚   └── TROUBLESHOOTING.md         # Common issues & solutions
β”‚
└── πŸ§ͺ Testing & Samples
    β”œβ”€β”€ test_sample_contract.py    # Integration test script
    └── sample_contract.pdf        # Example PDF for testing

Directory Descriptions

Backend (/backend)

  • app/api/: REST API endpoints for contract operations (upload, retrieve, update, delete)
  • app/core/: Core application settings, database connections, and configuration
  • app/models/: Pydantic models and MongoDB document schemas
  • app/services/: Business logic including PDF processing, OCR, field extraction, and confidence scoring
  • app/utils/: Shared utilities and helper functions
  • tests/: Comprehensive test suite with unit and integration tests
  • uploads/: Temporary storage for uploaded PDFs during processing

Frontend (/frontend)

  • src/app/: Next.js 14 app router pages and layouts
  • src/components/: Reusable React components and UI library
  • src/hooks/: Custom React hooks for state management
  • src/lib/: API client, utilities, and shared logic
  • src/types/: TypeScript type definitions and interfaces

Infrastructure

  • Docker files: Container definitions and orchestration for all services
  • Configuration: Environment variables, database settings, and service configs
  • Documentation: Comprehensive guides for setup, deployment, and troubleshooting

✨ Features

πŸ” Advanced Document Processing

  • Multi-format Support: Digital PDFs and scanned documents via OCR (Tesseract)
  • Intelligent Text Extraction: PyMuPDF with coordinate preservation and page mapping
  • Robust Parsing: 40+ field extraction with sophisticated regex patterns
  • Confidence Scoring: Multi-signal confidence calculation (0.0-1.0) with evidence tracking

πŸ“Š Smart Analytics & Scoring

  • Weighted Scoring System: Financial completeness (30%), Party identification (25%), Payment terms (20%), SLAs (15%), Contacts (10%)
  • Gap Analysis: Automatic identification of missing critical fields with severity levels
  • Evidence Tracking: Page-level source attribution for all extracted values
  • Processing Metrics: Performance monitoring with duration and success tracking

🎯 Extracted Field Categories

  • Parties: Company names, roles, signatories, contact information
  • Financial Terms: Contract values, currencies, billing frequencies, payment terms
  • Dates: Effective dates, termination dates, renewal terms, notice periods
  • Legal Clauses: Governing law, liability caps, indemnification, IP ownership
  • Service Terms: SLAs, performance metrics, support requirements

πŸ”§ Enterprise Features

  • RESTful API: Comprehensive FastAPI backend with OpenAPI documentation
  • Real-time Processing: Asynchronous processing with status tracking
  • Data Persistence: MongoDB with structured document storage
  • File Management: Secure upload handling with hash-based deduplication
  • Error Recovery: Graceful degradation and retry mechanisms

πŸ—οΈ Technology Stack

Backend

  • FastAPI 0.109.0 - High-performance Python web framework
  • Pydantic 2.5.3 - Data validation and serialization
  • Beanie/Motor - Async MongoDB ODM with Motor driver
  • PyMuPDF 1.23.21 - PDF text extraction and analysis
  • OpenCV + Tesseract - OCR processing for scanned documents
  • Celery + Redis - Background task processing

Frontend

  • Next.js 14.1.0 - React framework with TypeScript
  • Tailwind CSS - Utility-first styling framework
  • shadcn/ui - Modern React component library
  • React Query - Server state management and caching
  • React Hook Form - Form handling and validation
  • Lucide React - Icon library

Infrastructure

  • Docker + docker-compose - Containerized deployment
  • MongoDB 4.0+ - Document database
  • Redis - Caching and task queue
  • Nginx (Production) - Reverse proxy and static serving

Processing Results Processing Results Contract analysis results with confidence indicators and gap detection

πŸš€ Quick Start

Prerequisites

  • Docker and Docker Compose
  • Git

Installation

  1. Clone the Repository first

  2. Environment Setup

    # Copy environment template
    cp .env.example .env
    
    # Edit environment variables as needed
    nano .env
  3. Start the Application

    # Build and start all services
    docker-compose up --build
    
    # Or run in detached mode
    docker-compose up -d --build
  4. Verify Installation

    # Check service status
    docker-compose ps
    
    # View logs
    docker-compose logs -f

Access Points

Contract Analysis Contract Analysis Contract Analysis Detailed contract view with extracted fields, confidence scores, and evidence

πŸ“‹ Usage Examples

API Usage

1. Upload Contract

curl -X POST "http://localhost:8000/api/contracts" \
  -H "Content-Type: multipart/form-data" \
  -F "file=@sample_contract.pdf"

Response:

{
  "id": "66f2a1b8e4b0c1234567890a",
  "filename": "sample_contract.pdf",
  "status": "processing",
  "message": "Contract uploaded successfully"
}

2. Check Processing Status

curl "http://localhost:8000/api/contracts/66f2a1b8e4b0c1234567890a"

3. Retrieve Extracted Data

curl "http://localhost:8000/api/contracts/66f2a1b8e4b0c1234567890a/fields"

Frontend Workflow

  1. Upload: Drag and drop PDF files or click to browse
  2. Monitor: Real-time processing status with progress indicators
  3. Review: Examine extracted fields with confidence indicators
  4. Validate: Review gaps and low-confidence extractions
  5. Edit: Manual corrections with evidence preservation
  6. Export: Download processed data in multiple formats

API Documentation FastAPI automatic documentation with interactive endpoint testing

πŸ›οΈ Architecture Overview

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Frontend      β”‚    β”‚     Backend      β”‚    β”‚    Database     β”‚
β”‚   (Next.js)     │◄──►│    (FastAPI)     │◄──►│   (MongoDB)     β”‚
β”‚                 β”‚    β”‚                  β”‚    β”‚                 β”‚
β”‚ β€’ Upload UI     β”‚    β”‚ β€’ PDF Processing β”‚    β”‚ β€’ Document      β”‚
β”‚ β€’ Results View  β”‚    β”‚ β€’ Text Extract   β”‚    β”‚   Storage       β”‚
β”‚ β€’ Analytics     β”‚    β”‚ β€’ Field Parse    β”‚    β”‚ β€’ Metadata      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚ β€’ Confidence     β”‚    β”‚ β€’ Search Index  β”‚
                       β”‚   Scoring        β”‚    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚ β€’ Gap Detection  β”‚    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚     Redis       β”‚    β”‚ β€’ API Endpoints  β”‚    β”‚   File Storage  β”‚
β”‚   (Caching)     │◄──►│                  │◄──►│   (Local/S3)    β”‚
β”‚                 β”‚    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚                 β”‚
β”‚ β€’ Task Queue    β”‚    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚ β€’ PDF Files     β”‚
β”‚ β€’ Session       β”‚    β”‚   OCR Engine     β”‚    β”‚ β€’ Thumbnails    β”‚
β”‚ β€’ Cache         β”‚    β”‚  (Tesseract)     β”‚    β”‚ β€’ Temp Files    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Processing Pipeline

  1. Ingestion: PDF upload with validation and hash generation
  2. Text Extraction: PyMuPDF for digital text, OCR fallback for scanned docs
  3. Field Extraction: Regex-based pattern matching with 40+ field definitions
  4. Confidence Scoring: Multi-signal algorithm with evidence weighting
  5. Gap Detection: Missing field identification with severity assessment
  6. Storage: MongoDB persistence with full-text search indexing
  7. Response: Structured JSON with confidence metrics and evidence

πŸ”§ Development

Local Development Setup

  1. Backend Development

    cd backend
    python -m venv venv
    source venv/bin/activate #venv\Scripts\activate
    pip install -r requirements.txt
    uvicorn app.main:app --reload --port 8000
  2. Frontend Development

    cd frontend
    npm install
    npm run dev
  3. Database Setup

    # Start MongoDB
    docker-compose up mongodb -d
    
    # Initialize database (optional)
    python backend/scripts/init_db.py

Testing

# Backend tests
cd backend
pytest --cov=app tests/

# Frontend tests
cd frontend
npm test

# Integration tests
python test_sample_contract.py

Code Quality

# Python linting
flake8 backend/
black backend/
mypy backend/

# TypeScript checking
cd frontend
npm run lint
npm run type-check

πŸ› οΈ Troubleshooting

For some issues I faced; to read, refer to Troubleshooting Guide.

Quick Fixes

Container Issues:

# Reset Docker environment
docker-compose down -v
docker-compose up --build

Database Connection:

# Check MongoDB status
docker-compose logs mongodb

# Reset database
docker-compose down -v mongodb
docker-compose up mongodb -d

Built with ❀️ by Himangshu Shekhar

About

The Contract Intelligence Parser is a full-stack application that automatically processes PDF contracts to extract key business terms, legal clauses, and financial information. The system provides confidence scores for extracted data and identifies gaps in critical information.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages