Skip to content
sirmickPublic

About

Electronic Secratary

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

ย 

History

67 Commits

Folders and files

Repository files navigation

ALFRD Logo

ALFRD - Automated Ledger & Filing Research Database

Your personal AI-powered document management system that ingests, processes, and summarizes documents automatically using AWS Textract OCR and LLM classification via AWS Bedrock.

What is ALFRD?

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

Quick Start

Prerequisites

  • Python 3.11+
  • PostgreSQL 15+
  • AWS credentials (for Textract OCR and Bedrock LLM)

Installation

# 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

Process Your First Document

# 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 text

Architecture Overview

Folder-Based Document Input

Documents are organized in folders with metadata:

data/inbox/
โ””โ”€โ”€ bill_20241125_120000/
    โ”œโ”€โ”€ meta.json          # Document metadata
    โ”œโ”€โ”€ bill.jpg           # Page 1
    โ””โ”€โ”€ page2.jpg          # Page 2

Asyncio Processing Pipeline with Recovery

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_amount vs amount_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_THRESHOLD in .env (default: 0.05)

LLM-Optimized Output

{
  "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
}

Key Features

๐Ÿง  AI-Powered Processing

  • ๐Ÿค– 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

๐Ÿ“„ Document 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

๐Ÿ”ง Robust Architecture

  • โš™๏ธ 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

๐Ÿ“ฑ Web Interface (PWA)

  • ๐Ÿ“ท 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

๐Ÿ—„๏ธ Data & Storage

  • ๐Ÿ˜ 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

โœ… Testing & Quality

  • ๐Ÿงช 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

Project Structure

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)

Usage Examples

Add Documents

# 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 Documents

# 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

Test OCR

# See detailed Textract block output
python samples/test_ocr.py samples/pg\&e-bill.jpg

Run Tests

# Install pytest
pip install pytest pytest-asyncio

# Run storage tests
pytest document-processor/tests/test_storage.py -v

meta.json Format

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

Configuration

Environment Variables

# 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

Common Issues

Database not initialized

# Error: relation "documents" does not exist
# Solution: Initialize database
./scripts/create-alfrd-db

AWS credentials not configured

# 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

Development

Running Tests

# Run all tests
pytest -v

# Run specific test file
pytest document-processor/tests/test_storage.py -v

# Run with coverage
pytest --cov=document_processor

Code Structure

All 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 directory

No wrapper scripts or environment setup needed!

Technical Details

Technologies

  • 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

Database Schema

Key tables:

  • documents - Core document metadata, extracted text, and structured data
  • series - Document series with active_prompt_id and regeneration_pending
  • prompts - Evolving classifier, summarizer, and series prompts (versioned)
  • events - Comprehensive event log for debugging
  • document_types - Dynamic list of known document types
  • classification_suggestions - LLM-suggested new document types

See api-server/src/api_server/db/schema.sql for complete schema.

Statistics

  • ๐Ÿ“ 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

Contributing

See STATUS.md for current status and development roadmap.

License

MIT License - see LICENSE file for details.

Documentation

  • START_HERE.md - Quick start guide
  • ARCHITECTURE.md - System architecture and design decisions
  • STATUS.md - Current status and development roadmap
  • docs/JSON_FLATTENING.md - JSON flattening utilities guide

๐Ÿš€ Process your documents with AI-powered OCR and classification!

About

Electronic Secratary

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages