generated from john/python-template
5.6 KiB
5.6 KiB
System Architecture (Version 2)
This document describes the V2 production architecture of the personal historical-document transcription system.
Architecture Objectives
- Preserve source material as immutable transcribed text alongside page-level spatial AI metadata.
- Support batching multi-image and folder uploads cleanly into sequential pages (
page_number). - Leverage asynchronous worker pools (
asyncio) for parallel single-image API execution bounded by rate limiters (asyncio.Semaphore). - Migrate persistence to PostgreSQL using native
UUID,TIMESTAMPTZ, andJSONBdocument storage. - Standardize all data validation, API parsing, and database models on Pydantic V2.
- Support rich historical attribution (multi-author and multi-recipient relationships).
Runtime Topology
The V2 runtime operates as an asynchronous Python application:
- FastAPI + NiceGUI web application process.
- In-process
asynciobackground task orchestrator for parallel API execution. - Relational persistence via PostgreSQL (using
asyncpgorpsycopg3). - Pydantic V2 validation layer wrapping API payloads and PostgreSQL
JSONBschemas.
flowchart LR
U[Browser User] --> A[FastAPI + NiceGUI App]
A --> W[Asyncio Worker Engine]
A --> DB[(PostgreSQL Database)]
W --> P[Vision Provider APIs\nOpenAI / Claude]
W --> DB
Lifecycle Ownership
Application lifespan owns runtime setup/teardown:
- Initialize environment logging and Pydantic configuration.
- Manage asynchronous PostgreSQL connection pools (
asyncpg/psycopg3). - Execute database migrations and index initialization.
- Recover stale processing jobs on startup.
- Manage graceful shutdown of active
asyncioworker pools.
Layered Module Structure
Interface Layer
src/transcription/ui/**(NiceGUI pages, multi-page renderers, person cards)src/transcription/api/**(FastAPI routes and JSON error handlers)
Application & Async Worker Layer
src/transcription/services/workflows.pysrc/transcription/worker.py
Responsibilities:
- Batch orchestration and status transitions (
queued->processing->completed|partial_success|failed). - Parallel single-image API execution using
asyncio.gatherbounded byasyncio.Semaphore. - Pydantic schema parsing (
PageAIMetadata) and validation prior to database storage.
Domain & Service Layer
src/transcription/db/models.py(SQLModel/Pydantic V2 schema definitions for the current implementation)src/transcription/services/*.py(Transactional operations forDocument,Person,Source,Job, andJobSource)
Infrastructure Layer
src/transcription/db/**(PostgreSQL connection pooling and raw parameterized SQL execution)src/transcription/providers/**(OpenAI & Anthropic Vision SDK adapters)
Processing Workflow
- User uploads a folder or batch of images for a
Document. - System creates
Document,Job(status='queued'), and orderedSourcepages (page_number = 1..N). - Worker claims job, sets
Job.status = 'processing', and spawns parallelasynciotasks bounded by semaphore. - Each task calls Vision API for a single
Sourceimage. - On task completion:
- Writes a
JobSourcerecord containingstatus='transcribed',raw_transcription,ai_metadata(bounding boxes/confidence), andraw_api_response. - Caches active text to
Source.raw_transcription.
- On page failure:
- Writes
JobSourcerecord withstatus='failed'anderror_detail.
- Once all page tasks resolve:
- Marks
Job.statusascompleted(100% success),partial_success(at least 1 success, 1 failure), orfailed(all failed).
Domain Ownership & Invariants
- Immutable AI Outputs:
source.raw_transcriptionandjob_source.raw_transcriptionstore original, point-in-time machine output and are immutable. - Inlined Revisions: Human corrections occur on
source.revised_text. UI rendersCOALESCE(revised_text, raw_transcription). - Sequential Integrity: Multi-page documents are strictly ordered by
source.page_number ASC. - Page Execution Isolation: A failure on one page image does not invalidate successful transcriptions on sister pages in the same batch job.
Data Model Summary
Documenthas manySourcepages, manyJobruns, and manyPersonrecords viaDocumentPersonjunction (authororrecipient).Sourcebelongs to oneDocumentand can be processed across manyJobSourceexecutions.Jobhas manyJobSourceexecution records.
Test Strategy
- Unit tests for Pydantic V2 schemas, custom validators, and JSONB serialization.
- Integration tests for async PostgreSQL connection handling and parameterized queries.
- Async workflow tests using mock AI providers to verify
partial_successand retry logic. - UI integration tests for multi-page rendering and person management.
Technology References
- FastAPI documentation
- NiceGUI documentation
- PostgreSQL documentation
- Python asyncio
- Pydantic Validation
- Pydantic AI
Related Local References
- System Overview
- System Design Intent
- Transcription Methodology
- System Architecture (this document)
- System Requirements
- Data model
- Error Handling Policy
- Implementation Plan