Receipt tracker setup

From zocomputer/skills · View interactive version

Receipt tracker setup is an AI agent skill from the GitHub repository zocomputer/skills. Automatically scans receipts you drop in a folder, extracts the details, and saves them to a searchable database

How to use this skill

Skill file

Set Up Receipt Tracker Service on Zo Computer

How to Use This File

This file will be included in a user request. If it is, Zo should interpret this as the current task at hand and use its tools to carry out the task until completion. Zo should not ask for user confirmation to continue if it has all required parameters to execute this function. Zo should effectively treat the inclusion of this file as a user request to "run" this task.

Purpose

This document codifies the procedure for setting up an automated receipt and invoice processing system on Zo Computer. The system watches a designated folder for new image or PDF files, uses the Zo AI API to parse receipt/invoice data, stores parsed line items in a SQLite database, and moves processed files to an archive folder. The watcher runs as a managed user service with automatic restarts and persistence across reboots.

Inputs

No user inputs required - this setup is fully self-contained.

Procedure

1. Install Required Python Dependencies

pip install aiohttp watchfiles

These packages provide:

2. Create Project Directory Structure

mkdir -p /home/workspace/receipt-processor/input
mkdir -p /home/workspace/receipt-processor/processed

This creates:

3. Create SQLite Database and Schema

sqlite3 /home/workspace/receipt-processor/invoices.db "
CREATE TABLE invoices (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    merchant_name TEXT NOT NULL,
    transaction_date DATETIME,
    description TEXT NOT NULL,
    amount_minor INTEGER NOT NULL,
    currency TEXT NOT NULL DEFAULT 'USD',
    processed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    source_file_absolute TEXT NOT NULL
);"

Database Schema Explanation:

4. Create the Watcher Script

Create file receipt-processor/watcher.py with the following content:

import asyncio
import json
import os
from pathlib import Path
import aiohttp
from watchfiles import awatch

ACCEPTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp", ".tiff", ".tif", ".pdf"}
API_URL = "https://api.zo.computer/zo/ask"
API_TOKEN = os.environ.get("ZO_CLIENT_IDENTITY_TOKEN")

async def call_zo_api(prompt: str, timeout: int = 240) -> dict:
    """Call the Zo API with the given prompt."""
    headers = {
        "authorization": API_TOKEN,
        "content-type": "application/json"
    }

    payload = {
        "input": prompt
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(
            API_URL,
            headers=headers,
            json=payload,
            timeout=aiohttp.ClientTimeout(total=timeout)
        ) as response:
            response.raise_for_status()
            return await response.json()

async def process_image(image_path: Path, processed_dir: Path) -> None:
    """Process an image or PDF file using the Zo API to parse receipts/invoices."""
    print(f"🔍 Processing: {image_path.name}")

    # Get absolute path for the file
    absolute_path = image_path.resolve()

    prompt = f"""
Process this receipt or invoice file: {absolute_path}

If it is a receipt or invoice:
1. Parse it as separate line items
2. For each line item, insert a row into the SQLite database at: /home/workspace/receipt-processor/invoices.db

Database schema:
CREATE TABLE invoices (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    merchant_name TEXT NOT NULL,
    transaction_date DATETIME,
    description TEXT NOT NULL,
    amount_minor INTEGER NOT NULL,
    currency TEXT NOT NULL DEFAULT 'USD',
    processed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    source_file_absolute TEXT NOT NULL
);

Notes:
- amount_minor should be in cents (e.g., $25.99 = 2599)
- transaction_date can be NULL if not available
- source_file_absolute should be set to: {absolute_path}
- After successfully inserting all items, move the file to: {processed_dir}

After successfully adding database rows, EMAIL the user (using the send_email tool) that the receipt has been processed, and include in the body of the email the merchant name and total amount.
"""

    try:
        result = await call_zo_api(prompt)

        print(f"✅ Successfully processed: {image_path.name}")
        print(f"Response: {result.get('output', 'No output field')}")

        # Move to processed directory
        processed_dir.mkdir(exist_ok=True)
        destination = processed_dir / image_path.name
        image_path.rename(destination)
        print(f"📦 Moved to: {destination}")

    except asyncio.TimeoutError:
        print(f"⏱️ Timeout processing {image_path.name}")
    except aiohttp.ClientResponseError as e:
        print(f"❌ API error processing {image_path.name}: {e.status} - {e.message}")
    except Exception as e:
        print(f"❌ Unexpected error processing {image_path.name}: {e}")

async def main():
    base_path = Path(__file__).parent
    watch_path = base_path / "input"
    processed_path = base_path / "processed"

    watch_path.mkdir(exist_ok=True)

    print(f"👀 Watching for new files (images & PDFs) in: {watch_path}")
    print(f"📁 Processed files will be moved to: {processed_path}")

    async for changes in awatch(watch_path):
        for change_type, file_path in changes:
            file_path = Path(file_path)

            # Only process newly added files
            if (change_type.name == "added" and
                not file_path.name.startswith(".") and
                file_path.suffix.lower() in ACCEPTED_EXTENSIONS):

                await process_image(file_path, processed_path)

if __name__ == "__main__":
    asyncio.run(main())

5. Test the Watcher Script

Before registering as a service, verify the script starts without errors:

cd /home/workspace/receipt-processor
python3 -c "
import asyncio
from pathlib import Path
from watchfiles import awatch

async def test():
    watch_path = Path.cwd() / 'input'
    watch_path.mkdir(exist_ok=True)
    print(f'👀 Watching for new files in: {watch_path}')
    print(f'📁 Processed files will be moved to: {Path.cwd() / \"processed\"}')
    return True

print('✅ Watcher can start successfully' if asyncio.run(test()) else '❌ Failed')
"

This validates that dependencies are installed and the basic file watching functionality works.

6. Register the Watcher as a Managed User Service

register_user_service(
label="receipt-tracker",
protocol="tcp",
local_port=44444,
entrypoint="python3 watcher.py",
workdir="/home/workspace/receipt-processor"
)

Service Configuration:

The service will:

7. Verify the Service is Running

# Verify the watcher process is running
ps aux | grep watcher.py | grep -v grep

# Check that directories exist
ls -la /home/workspace/receipt-processor/

You should see the watcher process running in the background. Logs will be written to /dev/shm/receipt-tracker.log and /dev/shm/receipt-tracker_err.log once files are processed.

Expected Output

After successful setup:

Notification to the User

After successful setup, communicate to the user:

How to Use the Receipt Tracker

  1. Add a receipt: Drop any receipt image (JPG, PNG, PDF, etc.) into /home/workspace/receipt-processor/input/
  2. Wait for processing: The watcher will automatically detect the file and send it to the Zo AI API
  3. Check your email: You'll receive an email notification with the merchant name and amount
  4. View the data: Query the database to see parsed line items

Querying the Database

# View all processed receipts
sqlite3 /home/workspace/receipt-processor/invoices.db "SELECT * FROM invoices;"

# View receipts from a specific merchant
sqlite3 /home/workspace/receipt-processor/invoices.db "SELECT * FROM invoices WHERE merchant_name LIKE '%Target%';"

# Calculate total spending
sqlite3 /home/workspace/receipt-processor/invoices.db "SELECT SUM(amount_minor) / 100.0 AS total_dollars FROM invoices;"

# View recent receipts
sqlite3 /home/workspace/receipt-processor/invoices.db "SELECT merchant_name, description, amount_minor / 100.0 AS amount, processed_at FROM invoices ORDER BY processed_at DESC LIMIT 10;"

Service Management

Viewing Logs

Monitor the watcher in real-time:

tail -f /dev/shm/receipt-tracker.log

View error logs:

tail -f /dev/shm/receipt-tracker_err.log

Updating the Service

If you need to modify the watcher script:

  1. Edit file receipt-processor/watcher.py
  2. Restart the service using update_user_service or by deleting and re-registering

Stopping the Service

Use the delete_user_service tool with the service_id to stop the receipt tracker.

Technical Notes

Database Design Notes

Troubleshooting

Service not starting:

Files not being processed:

Database errors:

AI parsing issues:

Future Enhancements

Consider these potential improvements:


This prompt provides a complete, production-ready automated receipt processing system that runs continuously on your Zo Computer. The service will persist across restarts and automatically process any receipts you add to the input folder.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.