zoltan57andCopilot App 3e418a0889 V4.6 Phase 2: schema re-level in a single atomic pass
These changes all regenerate the same schema, so they land together and revert
together. A partially applied schema pass is not a valid state.

Remove hand-rolled migrations [HIGH-05]
- Delete upgrade_schema and the _upgrade_person_family_search_id /
  _upgrade_v42_evidence_tables / _upgrade_v45_selection_columns chain, plus the
  two tests that exercised them. The DDL was SQLite-shaped raw SQL that would
  not have run on PostgreSQL. create_all now derives everything from metadata
  and remains gated by Settings.should_bootstrap_schema. No raw ALTER TABLE or
  CREATE INDEX string remains in src.

Break the foreign key cycle [HIGH-08]
- Declare Source.preferred_execution_attempt_id with use_alter=True and an
  explicit constraint name. source / job_source / execution_attempt formed an
  unresolvable cycle that made metadata.sorted_tables emit an SAWarning and
  order execution_attempt before source, which would have been a hard
  create_all failure on PostgreSQL and was invisible on SQLite.
- As a side effect the column is now a dialect-aware Uuid rather than the
  hardcoded CHAR(32) the raw upgrade DDL produced, so it emits native UUID on
  PostgreSQL.

Index the hot filters [HIGH-04]
- Add composite Index("ix_job_status_date_created", "status", "date_created")
  for the worker poll, and index the foreign keys the worker and detail pages
  filter on: job.document_id, source.document_id, job_source.job_id,
  job_source.source_id, document.document_type_id, and the three
  document_person foreign keys.

Stop preloading by default [CRIT-02]
- Flip 16 relationships from lazy="selectin" to lazy="raise". The bidirectional
  selectin defaults meant loading one Job pulled a large connected subgraph.
- Three further relationships (ExecutionAttempt.job_source,
  ProcessingArtifact.execution_attempt, ProcessingArtifact.source) declared no
  lazy at all and defaulted to "select", which raises MissingGreenlet under
  async. These are now "raise" as well.
- Only 5 of 262 tests failed under the flip; the service layer already carried
  explicit eager loads. Fixes went into the service queries, never back into
  the models:
  - PeopleService._finalize_link refreshes document, person, and role_ref so
    the DocumentPerson write endpoints can still project them.
  - JobService.update_job_state loads job_sources -> source so the Job it
    returns still answers .error_detail and .filename.
  - Two tests that bypassed the service layer now load explicitly.
- Audited every UI relationship access against its feeding service method; all
  resolve to *_detail / list_*_detail variants with complete eager loads.

Tests
- Assert the composite and hot foreign key indexes exist in a fresh schema.
- Assert metadata.sorted_tables raises no SAWarning and orders source before
  execution_attempt.
- Assert preferred_execution_attempt_id is a Uuid that compiles to UUID on
  PostgreSQL and that its foreign key carries use_alter.
- Guard CRIT-02 from regression: no mapped relationship may declare a lazy
  strategy outside {raise, noload}.

The development database was rebuilt from metadata rather than upgraded; the
previous file is retained out of tree as the Phase 8 migration source.

Verified: 266 passed, 4 skipped; ruff check clean.

Co-authored-by: Copilot App <[email protected]>
2026-08-17 16:06:30 -05:00
2026-08-10 12:34:36 -05:00
2026-08-17 15:25:52 -05:00
2026-08-11 16:42:09 -05:00
2026-06-26 19:17:18 -05:00
2026-06-22 17:32:18 -05:00
2026-06-26 19:17:18 -05:00
2026-06-26 19:17:33 -05:00

Transcription

Historical document transcription system for family-history documents.

The app lets you upload a document image/PDF, queues a background transcription job, and then shows job status and results in a web UI.

What the app does

  • Upload document files (.jpg, .jpeg, .png, .tif, .tiff, .pdf)
  • Persist document + job records in SQLite
  • Process jobs in a background worker (queued -> processing -> transcribed/failed)
  • Store transcript text (or failure detail)
  • Show status and results in the NiceGUI interface

Quick start

1) Install dependencies

uv sync

2) Configure environment

Create a .env file in the project root with the required OpenRouter API key:

OPENROUTER_API_KEY=your_openrouter_api_key

Settings are read from CLI arguments first, then environment variables, then .env, then the defaults below.

Configuration Source Precedence

When the same setting is provided in multiple places, the value is chosen in this order (highest priority first):

  1. CLI arguments (for example --port 8000)
  2. Settings constructor arguments (used mainly in tests)
  3. Environment variables
  4. .env file values
  5. Model defaults in code

Practical examples:

  • --port 8000 overrides both PORT=8000 in the shell and PORT=7000 in .env.
  • DATABASE__PATH=prod.db in the shell overrides DATABASE__PATH=dev.db in .env.

Server and runtime

Environment variable Default Description
HOST 0.0.0.0 Address on which the server listens.
PORT 8000 Server port.
LOG_LEVEL info Uvicorn and application log level.
RELOAD false Restart the development server when source files change.
ENVIRONMENT development Runtime environment: development, test, or production.

Provider

Environment variable Default Description
PROVIDER openrouter Transcription provider.
OPENROUTER_API_KEY Required OpenRouter API key.
PROVIDER_MODEL Provider default Optional model override.
OPENROUTER_HTTP_REFERER Unset Optional OpenRouter attribution URL.
OPENROUTER_APP_TITLE Unset Optional OpenRouter attribution title.

Database and files

Use nested env vars for database settings (recommended):

DATABASE__DRIVER=sqlite
DATABASE__PATH=app.db
# BOOTSTRAP_SCHEMA_ON_STARTUP=true
SQLITE_CHECK_SAME_THREAD=false
UPLOAD_DIR=./uploads
PROMPT_DIR=./prompts
DEFAULT_PROMPT_NAME=transcribe_document.md
# TRANSCRIPTION_TEMPERATURE=0.2  # range: 0.0-2.0
# TRANSCRIPTION_TOP_P=0.9       # range: 0.0-1.0

For PostgreSQL:

DATABASE__DRIVER=postgres
DATABASE__HOST=localhost
DATABASE__PORT=5432
DATABASE__DATABASE=transcription
DATABASE__USER=postgres
DATABASE__PASSWORD=change-me

This uses Pydantic nested settings (env_nested_delimiter='__') and avoids JSON blobs in .env. A top-level DATABASE={...} JSON value is still supported as a fallback, and nested keys such as DATABASE__PATH take precedence over conflicting JSON keys.

BOOTSTRAP_SCHEMA_ON_STARTUP creates missing tables when the app starts. When unset, it is enabled in development and test, and disabled in production; set it explicitly to override that policy. SQLITE_CHECK_SAME_THREAD defaults to false.

Worker

WORKER_MAX_RETRIES=0
WORKER_RETRY_BACKOFF_SECONDS=0
WORKER_PROVIDER_TIMEOUT_SECONDS=20
WORKER_MIN_TRANSCRIPTION_CHARS=0
WORKER_MIN_TRANSCRIPTION_LINES=0
WORKER_FAIL_ON_FINISH_REASON_LENGTH=false

3) Run the app

uv run python -m transcription --port 8000 --reload --database.driver sqlite --bootstrap-schema-on-startup

This starts the development server with SQLite, creates missing tables, and enables automatic reload. Run uv run python -m transcription --help for all CLI options; CLI names use kebab case and nested database options use dot notation, such as --database.path ./data/transcription.db.

4) Open in browser

Replace localhost with the server's hostname or IP address when connecting from another machine.

How to navigate the GUI

  • Upload page (/ui)

    • Select a supported file to upload.
    • The app creates a queued transcription job.
    • Use the View jobs link to inspect progress.
  • Jobs page (/ui/jobs)

    • See all jobs and their status.
    • Use Refresh to reload current states.
    • Open a specific job to see details.
  • Job detail page (/ui/jobs/{job_id})

    • Shows job metadata and status.
    • Displays transcript text when successful.
    • Displays failure detail when transcription fails.

Prompt artifacts

Prompt files are stored directly in PROMPT_DIR (default: ./prompts). DEFAULT_PROMPT_NAME must be a filename, not a path. Each job snapshots the validated prompt text, SHA-256 hash, and sampling values for reproducibility.

The canonical MVP prompt is:

  • prompts/transcribe_document.md

Destructive test procedure (with data backup)

AI execution policy: before the first unit-test run in a test/fix cycle, create one backup of ./data. Reuse that same backup for every subsequent test run in the cycle. After tests succeed, always pause and ask whether to restore now.

Use the cross-platform Python wrapper below whenever an AI agent runs tests against this repository.

  1. Create one backup of ./data and mark it as the active test-cycle backup.
  2. Run your test command.
  3. On failure, fix the errors and run the wrapper again; it reuses the active backup and never backs up post-test data.
  4. On success, always prompt whether to restore now (do not auto-restore unless explicitly approved).
  5. Close the cycle only by restoring the active backup or explicitly accepting the current data.

Preflight behavior:

  • Backup preflight is warning-only when data/transcription.db appears in use.
  • Restore preflight is blocking: the script prompts you to close conflicting applications, then type retry to re-check or cancel to skip restore.

Run with confirmation-gated restore (default)

uv run python tools/run_destructive_tests.py -- pytest tests/services/test_job_service.py tests/ui/test_jobs_page.py

After tests pass, the script asks whether to restore backup immediately.

This is the required default mode for AI-assisted test runs because it gives time to verify and accept code changes before any restoration happens.

Run with automatic restore (non-interactive)

uv run python tools/run_destructive_tests.py --auto-restore -- pytest

Run without terminal prompt (decide restore later)

uv run python tools/run_destructive_tests.py --skip-restore-prompt -- pytest

This keeps both the current post-test state and the backup, so restore can be decided explicitly later.

Repeated wrapper invocations reuse the backup recorded in .test-backups/.active-backup. If that backup is missing, the wrapper stops rather than creating a replacement from potentially destructive post-test data.

Restore later from a saved backup

uv run python tools/run_destructive_tests.py --restore-from data-backup-YYYYMMDD-HHMMSS

To keep the current data and close the active cycle without restoring:

uv run python tools/run_destructive_tests.py --accept-current-data

Backups are stored in .test-backups/ and ignored by git.

S
Description
A project to transcribe several thousand pages of family history documents
Readme
25 MiB
Languages
Python 98.4%
CSS 0.9%
Shell 0.6%
Dockerfile 0.1%