Your personal AI-powered document management system that ingests, processes, and summarizes documents automatically using AWS Textract OCR and LLM classification via AWS Bedrock.
ALFRD (Automated Ledger & Filing Research Database) is a personal document management system that uses AI to automatically process, categorize, and summarize your documents. Drop a document folder in the inbox and ALFRD will:
- Extract text using AWS Textract OCR with block-level data preservation
- Process folders with multiple documents (multi-page bills, receipts, etc.)
- Classify via MCP using LLM-powered document type detection (AWS Bedrock)
- Extract structured data (vendor, amount, due date, line items) from bills automatically
- Organize into series with schema-consistent extraction across recurring documents
- Store in PostgreSQL with full-text search capability
- Preserve for LLMs with combined text + block-level structure for spatial reasoning
- Python 3.11+
- PostgreSQL 15+
- AWS credentials (for Textract OCR and Bedrock LLM)
# Clone the repository
git clone https://github.com/yourusername/alfrd.git
cd alfrd
# Install dependencies
pip install -r requirements.txt
# Configure AWS credentials in .env
cp .env.example .env
# Edit .env and add AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION
# Initialize database (REQUIRED!)
./scripts/create-alfrd-db# 1. Add a document (creates folder with meta.json)
python scripts/add-document.py ~/Downloads/bill.jpg --tags bill utilities
# 2. Process documents (OCR + storage)
python3 document-processor/src/document_processor/main.py
# 3. Check results
ls -la data/processed/ # Processed folders
ls -la data/documents/ # Stored documents with extracted textDocuments are organized in folders with metadata:
data/inbox/
โโโ bill_20241125_120000/
โโโ meta.json # Document metadata
โโโ bill.jpg # Page 1
โโโ page2.jpg # Page 2
User adds document โ Folder created in inbox (PENDING)
โ
OCR Step โ AWS Textract OCR (OCR_COMPLETED)
โ
Classify Step โ Bedrock LLM classification (CLASSIFIED)
โ
Background: Score Classification (for prompt evolution)
โ
Summarize Step โ Type-specific summarization (SUMMARIZED)
โ
Background: Score Summary (for prompt evolution)
โ
File Step โ Series detection & tagging (FILED)
โ
Series Summarize โ Series-specific extraction (SERIES_SUMMARIZED)
โ
Background: Score Series Extraction
โ
Complete โ Updates status (COMPLETED)
Processing Features:
- Asyncio orchestrator with semaphore-based concurrency control
- Automatic retry on failure (max 3 attempts per document)
- Periodic recovery scan for stuck work (every 5 minutes)
- 30-minute timeout for stale work detection
- Scoring steps run in background (fire-and-forget)
- PostgreSQL advisory locks prevent race conditions
- Comprehensive event logging for debugging
Series-Specific Extraction (Schema Consistency):
- Each document series gets its own extraction prompt
- All documents in a series have identical field names
- Eliminates schema drift (e.g.,
total_amountvsamount_due) - Enables clean data tables and aggregation
- Prompts evolve together (all documents regenerated)
Self-Improving Features:
- Classifier prompt evolution based on classification accuracy
- Summarizer prompt evolution based on extraction quality
- Series prompt evolution with automatic regeneration
- LLM can suggest new document types
- Configure via
PROMPT_UPDATE_THRESHOLDin .env (default: 0.05)
{
"full_text": "--- Document: bill.jpg ---\n[extracted text]\n\n--- Document: page2.jpg ---\n[more text]",
"blocks_by_document": [
{
"file": "bill.jpg",
"blocks": {
"PAGE": [...],
"LINE": [...],
"WORD": [...]
}
}
],
"document_count": 2,
"total_chars": 1234,
"avg_confidence": 0.95
}- ๐ค Self-improving prompts - Classifier, summarizer, and series prompts evolve based on quality
- ๐ฎ Dynamic classification - LLM can suggest new document types automatically
- ๐ Type-specific summarization - DB-driven, customizable per document type
- ๐ฏ Series-specific extraction - Each document series gets consistent field names
- โก Nova Lite inference - Fast, cost-effective AWS Bedrock processing
- ๐๏ธ AWS Textract OCR - 95%+ accuracy with block-level data preservation
- ๐ฆ Multi-page support - Process multiple images as single document
- ๐ท๏ธ Flexible tagging - Secondary tags for rich classification
- ๐ Series detection - Automatic grouping of recurring documents
- โป๏ธ Series regeneration - All documents updated when series prompt improves
- โ๏ธ Asyncio orchestration - Semaphore-based concurrency control
- ๐ PostgreSQL advisory locks - Prevent race conditions in concurrent processing
- ๐ Automatic recovery - Retry on failure (max 3 attempts) + stale work detection
- ๐ Event logging system - Comprehensive debugging with
./scripts/view-events - ๐ Prompt versioning - All prompt changes tracked with version history
- ๐ท Camera capture - Take photos directly from mobile devices
- ๐ Document list - Real-time data from API with refresh
- ๐ Document detail - Full metadata, OCR text, structured data display
- ๐ Data tables - Flattened JSONB visualization
- ๐ PostgreSQL - Full-text search and structured JSONB data
- ๐ JSON flattening - Convert nested data to flat tables with 4 array strategies
- ๐ค CSV export - CLI tool for data extraction and analysis
- ๐ LLM-optimized format - Combined text + block-level structure for spatial reasoning
- ๐งช 113+ tests - Comprehensive pytest suite
- ๐ฌ Workflow tests - End-to-end scenarios with real data
- ๐ก๏ธ Database tests - Direct PostgreSQL operation validation
- ๐ API tests - FastAPI endpoint coverage
alfrd/
โโโ document-processor/ # Asyncio orchestrator
โ โโโ src/document_processor/
โ โ โโโ main.py # Entry point
โ โ โโโ orchestrator.py # SimpleOrchestrator with recovery
โ โ โโโ tasks/
โ โ โ โโโ document_tasks.py # Processing steps
โ โ โ โโโ series_regeneration.py # Series regeneration worker
โ โ โโโ utils/
โ โ โ โโโ locks.py # PostgreSQL advisory locks
โ โ โโโ extractors/
โ โ โโโ aws_textract.py # AWS Textract OCR with blocks
โ โโโ tests/ # Pytest test suite
โโโ api-server/ # REST API (30+ endpoints)
โโโ mcp-server/ # LLM tools (library functions)
โ โโโ src/mcp_server/tools/
โ โโโ summarize_series.py # Series-specific extraction
โ โโโ ...
โโโ scripts/
โ โโโ create-alfrd-db # Database initialization (REQUIRED!)
โ โโโ add-document # Add documents to inbox
โ โโโ view-events # Event log viewer
โ โโโ start-processor # Process documents wrapper
โโโ shared/ # Shared configuration and types
โ โโโ database.py # PostgreSQL client
โ โโโ event_logger.py # Event logging utilities
โ โโโ tests/
โโโ data/ # Runtime data (not in git)
โโโ inbox/ # Document folders (input)
โโโ processed/ # Processed folders (archived)
โโโ documents/ # Stored documents (output)
โโโ postgres/ # PostgreSQL data (Docker)
# Single image
python scripts/add-document.py photo.jpg --tags receipt
# Multiple pages
python scripts/add-document.py page1.jpg page2.jpg page3.jpg --tags bill electric
# With source
python scripts/add-document.py doc.jpg --source mobile --tags insurance# Process all documents in inbox (continuous mode)
python3 document-processor/src/document_processor/main.py
# Run once and exit
python3 document-processor/src/document_processor/main.py --once
# Process single document
python3 document-processor/src/document_processor/main.py --doc-id <UUID>
# Or use wrapper script
./scripts/start-processor# See detailed Textract block output
python samples/test_ocr.py samples/pg\&e-bill.jpg# Install pytest
pip install pytest pytest-asyncio
# Run storage tests
pytest document-processor/tests/test_storage.py -vEach document folder requires a meta.json file:
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"created_at": "2024-11-25T02:00:00Z",
"documents": [
{"file": "bill.jpg", "type": "image", "order": 1},
{"file": "page2.jpg", "type": "image", "order": 2}
],
"metadata": {
"source": "mobile",
"tags": ["bill", "utilities"]
}
}The add-document.py script creates this automatically.
# AWS Credentials (Required)
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1
# Paths (Optional - defaults for local development)
DATABASE_URL=postgresql://alfrd_user@/alfrd?host=/var/run/postgresql
POSTGRES_PASSWORD=alfrd_dev_password
INBOX_PATH=./data/inbox
DOCUMENTS_PATH=./data/documents
SUMMARIES_PATH=./data/summaries
# Logging
LOG_LEVEL=INFO
ENV=development# Error: relation "documents" does not exist
# Solution: Initialize database
./scripts/create-alfrd-db# Error: AWS authentication failed
# Solution: Set up credentials in .env
AWS_ACCESS_KEY_ID=your-key
AWS_SECRET_ACCESS_KEY=your-secret
AWS_REGION=us-east-1# Run all tests
pytest -v
# Run specific test file
pytest document-processor/tests/test_storage.py -v
# Run with coverage
pytest --cov=document_processorAll main scripts have built-in PYTHONPATH setup for standalone execution:
# At top of file
_script_dir = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(_script_dir)) # Project root
sys.path.insert(0, str(Path(__file__).parent.parent)) # src directoryNo wrapper scripts or environment setup needed!
- Python 3.11+ - Core language
- AWS Textract - Production OCR ($1.50/1000 pages)
- AWS Bedrock - LLM for classification/summarization (Nova Lite)
- PostgreSQL 15+ - Production database with full-text search
- FastAPI - REST API framework
- Asyncio - Orchestration and concurrency
- Pytest - Testing framework
Key tables:
documents- Core document metadata, extracted text, and structured dataseries- Document series with active_prompt_id and regeneration_pendingprompts- Evolving classifier, summarizer, and series prompts (versioned)events- Comprehensive event log for debuggingdocument_types- Dynamic list of known document typesclassification_suggestions- LLM-suggested new document types
See api-server/src/api_server/db/schema.sql for complete schema.
- ๐ Lines of Code: ~8,000+ lines (orchestrator + tasks + MCP tools + API + Web UI + events)
- ๐งช Test Coverage: 113+ tests passing (database, API, workflow, locks)
- ๐๏ธ OCR Accuracy: 95%+ with AWS Textract
- โก Processing Speed: ~2-3 seconds per page
- โ๏ธ Orchestration: Simple asyncio with semaphore-based concurrency control
- ๐ Recovery: Automatic retry (3 attempts) + periodic stale work detection (5 min)
- ๐ค LLM Integration: AWS Bedrock with Amazon Nova Lite
- ๐ Prompt Evolution: Enabled with threshold=0.05 (configure via PROMPT_UPDATE_THRESHOLD)
- ๐ Series Prompts: One per series for schema-consistent extraction
- ๐ท๏ธ Document Types: 6 default types + unlimited LLM-suggested types
- ๐ API Endpoints: 30+ endpoints (health, documents, files, series, tags, prompts, events)
- ๐ Event Logging: Full audit trail with
./scripts/view-events - ๐ฑ Web UI: Ionic React PWA with data visualization
- ๐ Data Analysis: JSON flattening utility with 4 array strategies and pandas integration
See STATUS.md for current status and development roadmap.
MIT License - see LICENSE file for details.
START_HERE.md- Quick start guideARCHITECTURE.md- System architecture and design decisionsSTATUS.md- Current status and development roadmapdocs/JSON_FLATTENING.md- JSON flattening utilities guide
๐ Process your documents with AI-powered OCR and classification!