generated from john/python-template
Compare commits
60
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b3baf5a3e | ||
|
|
9b4d6f0340 | ||
|
|
5753eb0135 | ||
|
|
e6549277c6 | ||
|
|
b59d3da23e | ||
|
|
4bf6c9e2f3 | ||
|
|
4dac9349c1 | ||
|
|
5a741de0a9 | ||
|
|
58faa00d7b | ||
|
|
89cac3c378 | ||
|
|
4b5e7ac23e | ||
|
|
21a7e83563 | ||
|
|
fce7107863 | ||
|
|
5090e238ff | ||
|
|
75f263c2b6 | ||
|
|
be152a028e | ||
|
|
9219adaf0c | ||
|
|
fd3ca60008 | ||
|
|
72bc96ab3a | ||
|
|
4eeb552273 | ||
|
|
d9f5fbb1a4 | ||
|
|
271633d1d5 | ||
|
|
6c6589d8ff | ||
|
|
759d4c2434 | ||
|
|
323f12d911 | ||
|
|
f80834d589 | ||
|
|
752346025b | ||
|
|
4f6e1fd913 | ||
|
|
47aef0e26e | ||
|
|
c098013a68 | ||
|
|
49e2e48df1 | ||
|
|
0ab7ad50f2 | ||
|
|
9653060c2a | ||
|
|
ed6f9dfe25 | ||
|
|
5946867ff3 | ||
|
|
646a360aca | ||
|
|
2b3d33e50e | ||
|
|
dfe6f121ff | ||
|
|
51ac2d0b98 | ||
|
|
61cc8a200b | ||
|
|
c46d1bd0bc | ||
|
|
00ed176ac1 | ||
|
|
99a128e981 | ||
|
|
aa94f34de4 | ||
|
|
661e2b1bec | ||
|
|
d75083a666 | ||
|
|
d0a3ca0289 | ||
|
|
209c48987c | ||
|
|
4ed1f43eda | ||
|
|
ce8fcce6b0 | ||
|
|
6b5b0500b3 | ||
|
|
bbf7fe28c2 | ||
|
|
c4d25c1be8 | ||
|
|
1fa5eb1127 | ||
|
|
ec6617a1c4 | ||
|
|
9eb0f40c08 | ||
|
|
f769d29da1 | ||
|
|
8afc462a6d | ||
|
|
3d6daec561 | ||
|
|
1cc2f319d5 |
+53
-7
@@ -1,8 +1,54 @@
|
||||
PROVIDER=openrouter
|
||||
OPENROUTER_API_KEY=sk-or-...
|
||||
# PROVIDER_MODEL= # optional: OpenRouter adapter supplies default
|
||||
# --- NiceGUI Server ---
|
||||
# HOST=`0.0.0.0` (default)
|
||||
# PORT=8000 (default)
|
||||
# LOG_LEVEL: [`critical`, `error`, `warning`, `info` (default), `debug`, `trace`]
|
||||
# RELOAD=false (default)
|
||||
|
||||
# --- AI provider ---
|
||||
# PROVIDER=[`openrouter`(default), `google_genai`]
|
||||
PROVIDER=openrouter
|
||||
# OPENROUTER_API_KEY - Required when `PROVIDER=openrouter`
|
||||
OPENROUTER_API_KEY=your-api-key-goes-here
|
||||
# GEMINI_API_KEY - Required when `PROVIDER=google_genai`
|
||||
# PROVIDER_MODEL= specify model. If left blank OpenRouter will supply default.
|
||||
PROVIDER_MODEL=google/gemini-2.5-flash
|
||||
# OPENROUTER_HTTP_REFERER=https://example.com
|
||||
# OPENROUTER_APP_TITLE=Historical Transcription MVP
|
||||
# DATABASE_URL=sqlite:///./transcription.db
|
||||
# UPLOAD_DIR=./uploads
|
||||
# PROMPT_DIR=./prompts
|
||||
# OPENROUTER_APP_TITLE="Google: Gemini 2.5 Flash (openrouter)"
|
||||
|
||||
# --- runtime environment ---
|
||||
# ENVIRONMENT: [`development`(default), `test`, `production`]
|
||||
|
||||
# --- persistence ---
|
||||
# Use nested settings with double underscore because env_nested_delimiter="__".
|
||||
# SQLite example:
|
||||
# DATABASE__DRIVER=sqlite
|
||||
# DATABASE__PATH=app.db
|
||||
#
|
||||
# SQLite with custom relative path:
|
||||
# DATABASE__DRIVER=sqlite
|
||||
DATABASE__PATH=./data/transcription.db
|
||||
#
|
||||
# Postgres example:
|
||||
# DATABASE__DRIVER=postgres
|
||||
# DATABASE__HOST=localhost
|
||||
# DATABASE__PORT=5432
|
||||
# DATABASE__DATABASE=transcription
|
||||
# DATABASE__USER=postgres
|
||||
# DATABASE__PASSWORD=change-me
|
||||
#
|
||||
# Optional persistence flags:
|
||||
# BOOTSTRAP_SCHEMA_ON_STARTUP=false
|
||||
# SQLITE_CHECK_SAME_THREAD=false
|
||||
|
||||
# --- filesystem paths ---
|
||||
UPLOAD_DIR="./data"
|
||||
PROMPT_DIR="./prompts"
|
||||
|
||||
# --- worker reliability ---
|
||||
WORKER_MAX_RETRIES=0
|
||||
WORKER_RETRY_BACKOFF_SECONDS=0
|
||||
# WORKER_PROVIDER_TIMEOUT_SECONDS=[0-20]
|
||||
WORKER_PROVIDER_TIMEOUT_SECONDS=20
|
||||
WORKER_MIN_TRANSCRIPTION_CHARS=0
|
||||
WORKER_MIN_TRANSCRIPTION_LINES=0
|
||||
WORKER_FAIL_ON_FINISH_REASON_LENGTH=false
|
||||
|
||||
@@ -1,6 +1,53 @@
|
||||
---
|
||||
description: Copilot rules for modifying the UI
|
||||
description: "Use when modifying the NiceGUI application under src/transcription/ui. Defines ownership and dependency boundaries for UI registration, pages, components, services, persistence, state, and static assets."
|
||||
applyTo: 'src/transcription/ui/**/*.py'
|
||||
---
|
||||
|
||||
The UI is forbidden from directly touching the database. All interactions should be done using the [services](../../src/transcription/services/)
|
||||
# UI Conceptual Boundaries
|
||||
|
||||
Keep dependencies flowing in this direction:
|
||||
|
||||
`ui/__init__.py` -> `pages` -> `components`
|
||||
|
||||
Pages may depend on application services and framework-provided dependencies. Components may depend on smaller components and shared presentation helpers. Services and domain modules must never depend on the UI.
|
||||
|
||||
## Package Root
|
||||
|
||||
- Keep `ui/__init__.py` as the UI composition root: register global assets, register pages, and mount NiceGUI on FastAPI.
|
||||
- Do not put feature rendering, service calls, persistence, or route-specific state in the package root.
|
||||
|
||||
## Pages
|
||||
|
||||
- Pages own route registration and route-level orchestration.
|
||||
- Resolve request or application dependencies, call [services](../../src/transcription/services/), adapt returned data for presentation when needed, and coordinate refresh, navigation, and notifications here.
|
||||
- Do not query, mutate, commit, or roll back the database from a page. Do not import database engines, sessions, operations, or query-building APIs. Persistence belongs to services or workflow functions.
|
||||
- Framework dependency types may cross into page handlers only to construct or invoke services; do not pass sessions or session factories into components.
|
||||
- Keep business rules, lifecycle transitions, transaction boundaries, and cross-service workflows out of page callbacks.
|
||||
|
||||
## Components
|
||||
|
||||
- Components own reusable rendering, widget-local state, input normalization, and presentation-only formatting.
|
||||
- Expose user actions through typed callback parameters. The calling page decides which service or workflow runs and what refresh or navigation follows.
|
||||
- Do not register routes, resolve request/app state, instantiate services, or access persistence from components.
|
||||
- Components may accept ORM models returned by services as read-only snapshots. Only use fields and relationships that the service loaded eagerly; never mutate models, trigger lazy loading, or expose session behavior.
|
||||
- A component may compose lower-level components, but it must not import from `pages`.
|
||||
|
||||
## Shared UI Infrastructure
|
||||
|
||||
- Keep app-wide navigation and layout primitives in `components/app_shell.py`.
|
||||
- Keep generic table/event adaptation in `components/table/common.py`; feature-specific columns, row read models, and formatting belong in the feature table module.
|
||||
- Keep exception normalization and user-facing error display in `components/error_presenter.py`; preserve `AppError` details and operation identifiers at page/component boundaries.
|
||||
|
||||
## CSS Assets
|
||||
|
||||
- Keep CSS under `ui/static` and split it into manageable, feature-oriented files. Do not grow a monolithic stylesheet or embed substantial style blocks in Python components.
|
||||
- Load each stylesheet from the page, component, or composition root that needs it with `ui.add_css(...)`. Use shared registration only for genuinely application-wide styles.
|
||||
- Read stylesheet text through `importlib.resources.files(...)` so loading works from installed packages and is independent of the working directory.
|
||||
- Centralize CSS reading in one typed helper cached by relative resource path with `functools.cache` or an equivalent unbounded `lru_cache`. Cache the immutable stylesheet text to avoid repeated resource I/O during component renders; keep NiceGUI registration decisions at the caller.
|
||||
- Do not encode application behavior in CSS or other static assets.
|
||||
|
||||
## State and Side Effects
|
||||
|
||||
- Limit component state to ephemeral interaction state such as loading flags, form values, dialogs, and expansion state.
|
||||
- Application and worker state must be resolved at the page or application boundary and passed through narrow interfaces such as callbacks or notifier protocols.
|
||||
- Keep filesystem, network, provider, and worker orchestration behind application services or dedicated adapters. UI code may trigger those operations but must not implement them.
|
||||
|
||||
@@ -17,3 +17,7 @@ wheels/
|
||||
|
||||
# Document images
|
||||
uploads/*
|
||||
data/*
|
||||
|
||||
# Local destructive-test backups
|
||||
.test-backups/
|
||||
|
||||
Vendored
+4
-8
@@ -8,14 +8,10 @@
|
||||
"module": "debugpy",
|
||||
"args": [
|
||||
"-m",
|
||||
"uvicorn",
|
||||
"transcription.app:create_app",
|
||||
"--factory",
|
||||
"--host",
|
||||
// "127.0.0.1",
|
||||
"0.0.0.0",
|
||||
"--port",
|
||||
"8080"
|
||||
"transcription",
|
||||
"--host", "127.0.0.1",
|
||||
"--port", "9999",
|
||||
"--database.driver", "sqlite"
|
||||
],
|
||||
"justMyCode": true,
|
||||
"console": "integratedTerminal",
|
||||
|
||||
@@ -22,18 +22,80 @@ uv sync
|
||||
|
||||
### 2) Configure environment
|
||||
|
||||
Create a `.env` file in the project root (minimum required setting shown):
|
||||
Create a `.env` file in the project root with the required OpenRouter API key:
|
||||
|
||||
```env
|
||||
OPENROUTER_API_KEY=your_openrouter_api_key
|
||||
```
|
||||
|
||||
Optional settings (defaults shown):
|
||||
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 9999`)
|
||||
2. Settings constructor arguments (used mainly in tests)
|
||||
3. Environment variables
|
||||
4. `.env` file values
|
||||
5. Model defaults in code
|
||||
|
||||
Practical examples:
|
||||
|
||||
- `--port 9999` 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):
|
||||
|
||||
```env
|
||||
DATABASE_URL=sqlite:///./transcription.db
|
||||
DATABASE__DRIVER=sqlite
|
||||
DATABASE__PATH=app.db
|
||||
# BOOTSTRAP_SCHEMA_ON_STARTUP=true
|
||||
SQLITE_CHECK_SAME_THREAD=false
|
||||
UPLOAD_DIR=./uploads
|
||||
PROMPT_DIR=./prompts
|
||||
```
|
||||
|
||||
For PostgreSQL:
|
||||
|
||||
```env
|
||||
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
|
||||
|
||||
```env
|
||||
WORKER_MAX_RETRIES=0
|
||||
WORKER_RETRY_BACKOFF_SECONDS=0
|
||||
WORKER_PROVIDER_TIMEOUT_SECONDS=20
|
||||
@@ -45,13 +107,17 @@ WORKER_FAIL_ON_FINISH_REASON_LENGTH=false
|
||||
### 3) Run the app
|
||||
|
||||
```bash
|
||||
uv run uvicorn transcription.app:create_app --factory --reload
|
||||
uv run python -m transcription --port 9999 --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
|
||||
|
||||
- GUI: [http://[IP_ADDRESS]:8000/ui](http://[IP_ADDRESS]:8000/ui)
|
||||
- Health check: [http://[IP_ADDRESS]:8000/healthz](http://[IP_ADDRESS]:8000/healthz)
|
||||
- GUI: [http://localhost:9999/ui](http://localhost:9999/ui)
|
||||
- Health check: [http://localhost:9999/healthz](http://localhost:9999/healthz)
|
||||
|
||||
Replace `localhost` with the server's hostname or IP address when connecting from another machine.
|
||||
|
||||
## How to navigate the GUI
|
||||
|
||||
@@ -76,3 +142,47 @@ Prompt files are stored in `prompts/` and loaded from `PROMPT_DIR` (default: `./
|
||||
|
||||
The canonical MVP prompt is:
|
||||
- `prompts/transcribe_document.md`
|
||||
|
||||
## Destructive test procedure (with data backup)
|
||||
|
||||
Use the cross-platform Python wrapper below whenever a test run might alter local `./data`.
|
||||
|
||||
1. Create backup of `./data`.
|
||||
2. Run your test command.
|
||||
3. On success, prompt whether to restore now.
|
||||
4. On failure, keep backup and current state for inspection.
|
||||
|
||||
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)
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
### Run with automatic restore (non-interactive)
|
||||
|
||||
```bash
|
||||
uv run python tools/run_destructive_tests.py --auto-restore -- pytest
|
||||
```
|
||||
|
||||
### Run without terminal prompt (decide restore later)
|
||||
|
||||
```bash
|
||||
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.
|
||||
|
||||
### Restore later from a saved backup
|
||||
|
||||
```bash
|
||||
uv run python tools/run_destructive_tests.py --restore-from data-backup-YYYYMMDD-HHMMSS
|
||||
```
|
||||
|
||||
Backups are stored in `.test-backups/` and ignored by git.
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
# Historical Document Transcription Design Intent
|
||||
I have several thousand pages of family history told through letters, postcards, books, and other documents that I want to transcribe to text.
|
||||
|
||||
---
|
||||
|
||||
## Goals
|
||||
1. Preserve our family history
|
||||
2. Unburden my family (and descendants) from having to store and care for the physical media. Once the documents have been transcribed and organized, they can be donated (or kept by a family member that wants to retain them).
|
||||
3. Make the text easily available and searchable by family members, as well as AI (which may have different requirements).
|
||||
4. Ability create timelines or assemble the historical record of the family or specific individuals from across the complete document archive. Perhaps use AI to create the timelines in a more narrative form.
|
||||
|
||||
---
|
||||
|
||||
## Source material
|
||||
1. **letters, cards, diaries** - handwritten; mostly stored in tubs, with little organization
|
||||
2. **books** - typed or typeset; mostly self-published books 50-100 pages in length. This may be expanded to include selected pages from other publications.
|
||||
3. **newspaper clippings, event programs, invitations, and other ephemera**
|
||||
|
||||
---
|
||||
|
||||
## Methodology
|
||||
|
||||
1. Follow current best practices per "A Guide to Documentary Editing" by Mary-Jo Kline. (See [Transcription Methodology](transcription_methodology.md))
|
||||
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
## PostgreSQL DDL Specification (Version 2)
|
||||
|
||||
```sql
|
||||
-- Enable pgcrypto for UUID generation if on PostgreSQL < 13
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
|
||||
-- 1. PERSON TABLE
|
||||
CREATE TABLE person (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
full_name TEXT NOT NULL,
|
||||
display_name TEXT,
|
||||
maiden_name TEXT,
|
||||
birth_date DATE,
|
||||
birth_date_raw TEXT,
|
||||
birth_place TEXT,
|
||||
death_date DATE,
|
||||
death_date_raw TEXT,
|
||||
death_place TEXT,
|
||||
biography TEXT,
|
||||
portrait_path TEXT,
|
||||
metadata JSONB DEFAULT '{}'::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 2. DOCUMENT TABLE
|
||||
CREATE TABLE document (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
name TEXT NOT NULL,
|
||||
document_type TEXT,
|
||||
document_date DATE,
|
||||
document_date_raw TEXT,
|
||||
location_created TEXT,
|
||||
notes TEXT,
|
||||
archive_identifier TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 3. DOCUMENT_PERSON (Junction Table for Multi-Author / Multi-Recipient)
|
||||
CREATE TABLE document_person (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
document_id UUID NOT NULL REFERENCES document(id) ON DELETE CASCADE,
|
||||
person_id UUID NOT NULL REFERENCES person(id) ON DELETE CASCADE,
|
||||
role VARCHAR(20) NOT NULL, -- 'author' or 'recipient'
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CONSTRAINT unique_document_person_role UNIQUE (document_id, person_id, role)
|
||||
);
|
||||
|
||||
-- 4. JOB TABLE (Batch-level orchestrator)
|
||||
CREATE TABLE job (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
document_id UUID NOT NULL REFERENCES document(id) ON DELETE CASCADE,
|
||||
status VARCHAR(50) NOT NULL DEFAULT 'queued', -- 'queued', 'processing', 'completed', 'partial_success', 'failed'
|
||||
retry_count INTEGER NOT NULL DEFAULT 0,
|
||||
provider TEXT NOT NULL, -- e.g., 'openai', 'anthropic'
|
||||
model TEXT NOT NULL, -- e.g., 'gpt-4o', 'claude-3-5-sonnet'
|
||||
prompt_name TEXT,
|
||||
date_created TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
date_updated TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 5. SOURCE TABLE (Physical image files & active state)
|
||||
CREATE TABLE source (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
document_id UUID NOT NULL REFERENCES document(id) ON DELETE CASCADE,
|
||||
page_number INTEGER NOT NULL DEFAULT 1,
|
||||
upload_name TEXT NOT NULL,
|
||||
filename TEXT NOT NULL,
|
||||
file_path TEXT NOT NULL,
|
||||
raw_transcription TEXT, -- Cached active AI text output
|
||||
revised_text TEXT, -- Active human edited text
|
||||
date_uploaded TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
date_revised TIMESTAMPTZ
|
||||
);
|
||||
|
||||
-- 6. JOB_SOURCE (Junction Table: Per-Image Execution Record)
|
||||
CREATE TABLE job_source (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
job_id UUID NOT NULL REFERENCES job(id) ON DELETE CASCADE,
|
||||
source_id UUID NOT NULL REFERENCES source(id) ON DELETE CASCADE,
|
||||
status VARCHAR(50) NOT NULL DEFAULT 'pending', -- 'pending', 'transcribed', 'failed'
|
||||
raw_transcription TEXT, -- Point-in-time raw AI text output
|
||||
ai_metadata JSONB, -- Page-level bounding boxes, tokens, confidence
|
||||
raw_api_response JSONB, -- Complete REST response envelope
|
||||
error_detail TEXT,
|
||||
executed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CONSTRAINT unique_job_source UNIQUE (job_id, source_id)
|
||||
);
|
||||
|
||||
-- INDEXES FOR FAST LOOKUPS & QUERY PERFORMANCE
|
||||
CREATE INDEX idx_person_full_name ON person(full_name);
|
||||
CREATE INDEX idx_document_date ON document(document_date);
|
||||
CREATE INDEX idx_document_person_doc ON document_person(document_id);
|
||||
CREATE INDEX idx_document_person_per ON document_person(person_id);
|
||||
CREATE INDEX idx_source_document ON source(document_id);
|
||||
CREATE INDEX idx_source_page_order ON source(document_id, page_number);
|
||||
CREATE INDEX idx_job_document ON job(document_id);
|
||||
CREATE INDEX idx_job_source_job ON job_source(job_id);
|
||||
CREATE INDEX idx_job_source_source ON job_source(source_id);
|
||||
CREATE INDEX idx_job_source_ai_metadata ON job_source USING GIN (ai_metadata);
|
||||
```
|
||||
@@ -1,248 +0,0 @@
|
||||
# Implementation Plan (Version 2)
|
||||
|
||||
This plan defines the path from the V1 baseline to **Version 2 complete**, aligned to the updated multi-image and multi-person relational domain model:
|
||||
|
||||
* `Document` acts as a logical parent container for physical artifacts, supporting multi-author and multi-recipient relationships via `DocumentPerson`.
|
||||
* `Source` represents an individual image page within a document, maintaining sequential order (`page_number`), cached active machine output (`raw_transcription`), and inline single user revisions (`revised_text`).
|
||||
* `Job` acts as an overarching batch orchestrator for multi-page async processing tasks.
|
||||
* `JobSource` records individual point-in-time API executions per image page, storing Pydantic-validated `ai_metadata` and raw REST envelopes (`raw_api_response`).
|
||||
* **Pydantic V2** acts as the single source of truth for runtime validation, API payload parsing, and PostgreSQL JSONB serialization.
|
||||
|
||||
The objective is to complete the V2 scope with production readiness while keeping non-V2 enhancements out of active delivery.
|
||||
|
||||
---
|
||||
|
||||
## V2 Completion Definition
|
||||
|
||||
V2 is complete when all of the following are true:
|
||||
|
||||
1. **Functional complete**
|
||||
* Multi-image and whole-folder uploads assign sequential page numbers to `Source` records under a single `Document`.
|
||||
* Batch jobs process pages concurrently using an `asyncio` worker pool with semaphore rate limiting.
|
||||
* Partial job failures resolve cleanly to `partial_success`, allowing single-page retries without re-running successful pages.
|
||||
* Multi-author and multi-recipient tagging is supported on `Document`.
|
||||
|
||||
|
||||
2. **Data-model complete**
|
||||
* SQLite is fully replaced with PostgreSQL (using `asyncpg` or `psycopg3`).
|
||||
* Pydantic V2 models validate all API payloads, database row mappings, and `JSONB` structures.
|
||||
|
||||
|
||||
3. **Operational complete**
|
||||
* Concurrency controls, worker pool metrics, and database connections operate safely under batch load.
|
||||
|
||||
|
||||
4. **Documentation complete**
|
||||
* `schema_v2.md`, `DDL_v2.sql`, Pydantic model contracts are updated and consistent.
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Data Contract Stabilization & Pydantic Baseline
|
||||
|
||||
**Goal:** Lock the PostgreSQL schema, DDL, and Pydantic V2 models before refactoring service logic.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Finalize DDL for PostgreSQL native types (`UUID`, `TIMESTAMPTZ`, `JSONB`) and junction tables (`document_person`, `job_source`).
|
||||
2. Build core Pydantic V2 schemas (`Person`, `Document`, `Source`, `Job`, `JobSource`, `PageAIMetadata`).
|
||||
3. Confirm and document data invariants:
|
||||
* `source.raw_transcription` and `job_source.raw_transcription` are immutable machine outputs.
|
||||
* `source.revised_text` holds user edits. UI renders `COALESCE(revised_text, raw_transcription)`.
|
||||
* Page sequence is strictly ordered by `source.page_number ASC`.
|
||||
|
||||
|
||||
4. Freeze V2 job status values (`queued`, `processing`, `completed`, `partial_success`, `failed`) and page execution status values (`pending`, `transcribed`, `failed`).
|
||||
|
||||
### Deliverables
|
||||
|
||||
* Canonical `docs/schema_v2.md` and `docs/DDL_v2.sql`.
|
||||
* Centralized Pydantic validation suite in `models/schemas_v2.py`.
|
||||
|
||||
### Exit Criteria
|
||||
|
||||
* All database tables, relationships, and JSONB structures have corresponding Pydantic V2 models passing unit validation tests.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Persistence Layer Transition (SQLite to PostgreSQL)
|
||||
|
||||
**Goal:** Replace the SQLite storage layer with an asynchronous PostgreSQL driver (`asyncpg` or `psycopg3`).
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Configure PostgreSQL database connection pooling and environment configuration.
|
||||
2. Refactor `services/store.py` / repository layers to execute parameterized async SQL queries (`$1`, `$2`).
|
||||
3. Implement JSONB serialization and deserialization helpers using Pydantic's `.model_dump_json()` and `.model_validate()`.
|
||||
4. Implement database bootstrap routines for PostgreSQL table creation and index initialization.
|
||||
|
||||
### Deliverables
|
||||
|
||||
* PostgreSQL-native database connection and query service modules.
|
||||
* Integration test suite confirming connection pooling and JSONB CRUD operations.
|
||||
|
||||
### Exit Criteria
|
||||
|
||||
* All database reads/writes run asynchronously against PostgreSQL with zero remaining SQLite driver dependencies.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Service Layer & `asyncio` Engine Refactor
|
||||
|
||||
**Goal:** Implement batch orchestration and parallel single-image API execution.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Refactor upload service to process folder/multi-image input:
|
||||
* Group files into a single `Document`.
|
||||
* Create ordered `Source` rows (`page_number = 1..N`).
|
||||
|
||||
|
||||
2. Refactor `services/workflows.py` with `asyncio` worker pools:
|
||||
* Use `asyncio.Semaphore` to enforce API provider rate limits.
|
||||
* Issue parallel single-image requests to Vision APIs (OpenAI/Claude).
|
||||
* Parse API responses directly into Pydantic models (`PageAIMetadata`).
|
||||
|
||||
|
||||
3. Update execution tracking:
|
||||
* Create a `JobSource` row per page call to record `raw_transcription`, `ai_metadata`, and `raw_api_response`.
|
||||
* Update active `source.raw_transcription` upon task completion.
|
||||
* Calculate aggregate batch status (`completed`, `partial_success`, `failed`) on the parent `Job`.
|
||||
|
||||
|
||||
4. Refactor `services/person.py` and `services/documents.py` to handle multi-person roles via `document_person`.
|
||||
|
||||
### Deliverables
|
||||
|
||||
* Asynchronous batch execution engine in `services/workflows.py`.
|
||||
* Service routines for multi-person tagging and page-level retries.
|
||||
|
||||
### Exit Criteria
|
||||
|
||||
* Executing a folder upload of 10+ images processes concurrently, populates page-level `JobSource` entries, and handles partial worker errors without crashing the batch.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — UI & API Contract Alignment
|
||||
|
||||
**Goal:** Update API endpoints and frontend/UI views to render multi-page documents and person roles.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Update document and job API endpoints to accept batch file arrays and multi-person ID payloads.
|
||||
2. Update UI document views:
|
||||
* Render multi-page document transcriptions sequentially by `page_number`.
|
||||
* Display author and recipient chips/cards linked from `document_person`.
|
||||
|
||||
|
||||
3. Update job detail UI to show page-level execution statuses (`transcribed` vs. `failed`) and provide a "Retry Failed Pages" action for `partial_success` jobs.
|
||||
4. Align inline page editing controls to update `source.revised_text` and `source.date_revised`.
|
||||
|
||||
### Deliverables
|
||||
|
||||
* Refactored API routes and UI components supporting multi-page rendering and person management.
|
||||
|
||||
### Exit Criteria
|
||||
|
||||
* UI successfully displays multi-page document text, allows per-page human revisions, and shows author/recipient metadata.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Test Suite Realignment & Concurrency Testing
|
||||
|
||||
**Goal:** Ensure end-to-end system stability under concurrent async execution and load.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Write unit tests for Pydantic models, custom validators, and JSONB conversions.
|
||||
2. Write integration tests for async database operations:
|
||||
* CRUD for `Document`, `Person`, `DocumentPerson`, `Source`, `Job`, and `JobSource`.
|
||||
|
||||
|
||||
3. Write mock-backed async workflow tests:
|
||||
* Verify `asyncio.Semaphore` bounds concurrent tasks properly.
|
||||
* Validate state transition logic for `completed`, `partial_success`, and `failed` jobs.
|
||||
* Confirm retry routines process only targeted `JobSource` records marked as `failed`.
|
||||
|
||||
|
||||
4. Re-enable CI quality gates (linting, type checking with Pyright/mypy, pytest).
|
||||
|
||||
### Deliverables
|
||||
|
||||
* Passing asynchronous test suite covering core workflows, edge cases, and failure recoveries.
|
||||
|
||||
### Exit Criteria
|
||||
|
||||
* CI pipeline is green with comprehensive coverage across database operations, Pydantic models, and worker queues.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 — Reliability, Operations, and Release Readiness
|
||||
|
||||
**Goal:** Prepare V2 for production deployment and operator management.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Verify structured logging includes `job_id`, `document_id`, `source_id`, and `person_id`.
|
||||
2. Tune PostgreSQL connection pool limits and `asyncio` concurrency thresholds for production infrastructure.
|
||||
3. Update operational documentation:
|
||||
* Review and update `docs/schema_v2.md` as needed.
|
||||
* Create `docs/runbook_v2.md` detailing PostgreSQL maintenance, JSONB index management, and worker queue monitoring.
|
||||
* Create `docs/release_checklist_v2.md` for launch sign-off.
|
||||
|
||||
|
||||
|
||||
### Deliverables
|
||||
|
||||
* Updated project documentation and operational runbooks.
|
||||
* V2 release sign-off checklist.
|
||||
|
||||
### Exit Criteria
|
||||
|
||||
* All documentation reflects V2 architecture; launch checklist is fully verified.
|
||||
|
||||
---
|
||||
|
||||
## Requirement Traceability Focus
|
||||
|
||||
Maintain evidence against these V2 requirement groups:
|
||||
|
||||
* **Batch & Multi-Image Pipeline:** Folder ingestion, page ordering, async worker execution.
|
||||
* **Database & Persistence:** PostgreSQL, native UUIDs, JSONB execution storage, `asyncpg` pooling.
|
||||
* **Validation & Schemas:** Pydantic V2 models for DB rows, API requests, and AI vision responses.
|
||||
* **Attribution & Metadata:** Multi-author and multi-recipient tagging, biographical entity management.
|
||||
* **Error Recovery:** Partial success states, page-level status flags, isolated retry execution.
|
||||
|
||||
---
|
||||
|
||||
## Scope Discipline Rule (V2 Focus)
|
||||
|
||||
* Only tasks required for V2 scope (PostgreSQL, Pydantic V2, folder/async processing, multi-person roles) enter this plan.
|
||||
* V3 candidate features (such as side-by-side multi-provider model output comparison) remain strictly in the future backlog.
|
||||
* Any schema adjustments during implementation require immediate updates to `DDL_v2.sql`, Pydantic models, and `schema_v2.md`.
|
||||
|
||||
---
|
||||
|
||||
## Technology References
|
||||
|
||||
- [FastAPI documentation](https://fastapi.tiangolo.com/)
|
||||
- [NiceGUI documentation](https://nicegui.io/documentation)
|
||||
- [PostgreSQL documentation](https://www.postgresql.org/docs/)
|
||||
- [Python asyncio](https://docs.python.org/3/library/asyncio.html#module-asyncio)
|
||||
- [Pydantic Validation](https://pydantic.dev/docs/validation/latest/get-started/)
|
||||
- [Pydantic AI](https://pydantic.dev/docs/ai/overview/)
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v2.md)
|
||||
- [System Design Intent](intent.md)
|
||||
- [Transcription Methodology](transcription_methodology.md)
|
||||
- [System Architecture](architecture_v2.md)
|
||||
- [System Requirements](requirements_v2.md)
|
||||
- [Data model](schema_v2.md)
|
||||
- [Error Handling Policy](error_handling_v2.md)
|
||||
- Implementation Plan (this document)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Historical Document Transcription Design Intent
|
||||
I have several thousand pages of family history told through letters, postcards, books, and other documents that I want to transcribe to text.
|
||||
|
||||
---
|
||||
|
||||
## Goals
|
||||
1. Preserve our family history
|
||||
2. Unburden my family (and descendants) from having to store and care for the physical media. Once the documents have been transcribed and organized, they can be donated (or kept by a family member that wants to retain and preserve them).
|
||||
3. Make the document text easily available and easily searchable.
|
||||
4. Ability create timelines for individuals and/or families through document dates or the data contained in them. Perhaps even use AI to generate biographies or family histories.
|
||||
|
||||
---
|
||||
|
||||
## Source material
|
||||
1. **letters, cards, diaries** - handwritten; mostly stored in boxes and tubs with little organization
|
||||
2. **books** - typed or typeset; mostly self-published books 50-100 pages in length. This may be expanded to include selected pages from other publications.
|
||||
3. **photos** - notes written on the backs of photos and the pages of photo albums
|
||||
4. **other ephemera** - newspaper clippings, event programs, invitations, military records, immigration records, etc
|
||||
|
||||
---
|
||||
|
||||
## Methodology
|
||||
|
||||
1. Follow current best practices per **A Guide to Documentary Editing** by Mary-Jo Kline. (See [Transcription Methodology](transcription_methodology.md))
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
# UI Style Guide (Invariant)
|
||||
|
||||
## 1. Purpose
|
||||
This guide defines non-negotiable UI styling rules for the transcription application.
|
||||
|
||||
The design system is token-first and class-driven:
|
||||
1. Theme tokens are defined in [src/transcription/ui/static/theme.css](src/transcription/ui/static/theme.css).
|
||||
2. Python UI code composes semantic classes instead of inline color values.
|
||||
3. Pages and components should share a single visual language across Documents, Jobs, People, and Sources flows.
|
||||
|
||||
## 2. Source of Truth
|
||||
Use these files as the style authority:
|
||||
1. [src/transcription/ui/static/theme.css](src/transcription/ui/static/theme.css) for color tokens, semantic utility classes, table styles, and viewer surfaces.
|
||||
2. [src/transcription/ui/theme.py](src/transcription/ui/theme.py) for runtime NiceGUI theme bridge and shared UI helpers.
|
||||
|
||||
If this document conflicts with implementation, update this document to match the code immediately after intentional style changes.
|
||||
|
||||
## 3. Core Design Invariants
|
||||
1. Flat, high-density surfaces over decorative depth.
|
||||
2. Strong content hierarchy with subdued backgrounds and border-based separation.
|
||||
3. Viewer area remains the highest contrast region in image/transcription workflows.
|
||||
4. Primary actions are consistent and visually recognizable.
|
||||
5. Accessible focus rings are always visible for keyboard users.
|
||||
|
||||
## 4. Token System
|
||||
|
||||
### 4.1 Palette Tokens
|
||||
Base palette variables live under :root in [src/transcription/ui/static/theme.css](src/transcription/ui/static/theme.css):
|
||||
1. --palette-carbon-black: #1c2321
|
||||
2. --palette-cool-steel: #7d98a1
|
||||
3. --palette-blue-slate: #5e6572
|
||||
4. --palette-powder-blue: #a9b4c2
|
||||
5. --palette-platinum: #eef1ef
|
||||
|
||||
### 4.2 Semantic Theme Tokens
|
||||
Do not style components directly with palette tokens when a semantic token exists.
|
||||
|
||||
Semantic tokens currently include:
|
||||
1. --theme-text and --theme-text-muted
|
||||
2. --theme-page, --theme-surface, --theme-surface-raised, --theme-surface-muted
|
||||
3. --theme-border
|
||||
4. --theme-primary and --theme-primary-hover
|
||||
5. --theme-secondary and --theme-focus
|
||||
6. --theme-inverse-text
|
||||
7. --theme-viewer, --theme-viewer-border, --theme-viewer-muted
|
||||
|
||||
## 5. Approved Semantic Classes
|
||||
|
||||
### 5.1 Text and Background
|
||||
1. ui-text-primary
|
||||
2. ui-text-muted
|
||||
3. ui-text-inverse
|
||||
4. ui-bg-page
|
||||
5. ui-bg-surface
|
||||
6. ui-bg-surface-raised
|
||||
7. ui-bg-surface-muted
|
||||
8. ui-bg-viewer
|
||||
9. ui-bg-viewer-overlay
|
||||
10. ui-bg-viewer-overlay-soft
|
||||
|
||||
### 5.2 Borders and Surfaces
|
||||
1. ui-border-subtle
|
||||
2. ui-border-viewer
|
||||
3. ui-header-divider
|
||||
4. ui-card-surface
|
||||
5. ui-row-surface
|
||||
6. ui-note-box
|
||||
|
||||
### 5.3 Interactive Elements
|
||||
1. ui-btn-primary
|
||||
2. ui-btn-secondary
|
||||
3. ui-link-primary
|
||||
4. ui-text-accent
|
||||
|
||||
### 5.4 Table Patterns
|
||||
1. ui-table
|
||||
2. ui-table-header
|
||||
3. ui-table-body
|
||||
|
||||
Use existing class combinations from [src/transcription/ui/components](src/transcription/ui/components) and [src/transcription/ui/pages](src/transcription/ui/pages) as reference implementations.
|
||||
|
||||
## 6. Legacy Class Policy
|
||||
Legacy classes with vibe- prefix still exist in a few components and are allowed only for compatibility while migrating:
|
||||
1. Existing usage may remain temporarily.
|
||||
2. New usage of vibe- classes is not allowed.
|
||||
3. When touching a file that uses vibe- classes, prefer migrating it to ui- semantic classes in the same change when safe.
|
||||
|
||||
Current legacy usage examples are in:
|
||||
1. [src/transcription/ui/components/document_panzoom.py](src/transcription/ui/components/document_panzoom.py)
|
||||
2. [src/transcription/ui/components/error_presenter.py](src/transcription/ui/components/error_presenter.py)
|
||||
3. [src/transcription/ui/components/transcript.py](src/transcription/ui/components/transcript.py)
|
||||
|
||||
## 7. Prohibited Patterns
|
||||
1. Inline hex colors in Python UI class strings or style blocks, except in isolated bridge code explicitly marked for migration.
|
||||
2. Ad-hoc one-off class names that duplicate existing semantic class intent.
|
||||
3. Page-specific palette forks that bypass theme tokens.
|
||||
4. Hidden or low-contrast focus states on interactive controls.
|
||||
|
||||
## 8. Implementation Rules For Contributors
|
||||
1. Prefer composing existing semantic classes before creating new ones.
|
||||
2. If a new class is required, add it to [src/transcription/ui/static/theme.css](src/transcription/ui/static/theme.css) with a semantic name, then reuse it.
|
||||
3. Keep behavior ownership in Python and appearance ownership in CSS.
|
||||
4. Update UI tests that assert exact text or labels when intentional copy changes are made.
|
||||
5. Avoid introducing class churn unrelated to the feature being changed.
|
||||
|
||||
## 9. Verification Checklist
|
||||
Before merging UI changes, verify:
|
||||
1. No new inline hex colors were introduced in UI pages/components.
|
||||
2. New styles are token-backed and added to [src/transcription/ui/static/theme.css](src/transcription/ui/static/theme.css).
|
||||
3. Primary buttons, links, cards, and tables still render with consistent semantics.
|
||||
4. Keyboard focus ring visibility is preserved.
|
||||
5. Relevant UI and integration tests pass.
|
||||
@@ -0,0 +1,107 @@
|
||||
from nicegui import ui
|
||||
|
||||
# 1. Mature Dark Mode Setup
|
||||
ui.dark_mode(True)
|
||||
|
||||
# Define a refined dark palette using expanded dictionary styling
|
||||
theme_colors = {
|
||||
'primary': '#6366f1',
|
||||
'secondary': '#8b5cf6',
|
||||
'accent': '#ec4899',
|
||||
'dark': '#0f172a',
|
||||
'dark_page': '#020617',
|
||||
'positive': '#10b981',
|
||||
'negative': '#ef4444',
|
||||
}
|
||||
|
||||
ui.colors(**theme_colors)
|
||||
|
||||
# Optional: Add custom CSS for subtle noise overlays or kinetic typography
|
||||
ui.add_css('''
|
||||
.glass-card {
|
||||
background: rgba(255, 255, 255, 0.03);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid rgba(255, 255, 255, 0.05);
|
||||
border-radius: 1.5rem;
|
||||
}
|
||||
''')
|
||||
|
||||
# 2. Bento Grid Layout
|
||||
with ui.element('div').classes('grid grid-cols-1 md:grid-cols-4 gap-6 w-full max-w-6xl mx-auto p-8'):
|
||||
|
||||
# Header spanning all columns
|
||||
with ui.element('div').classes('col-span-1 md:col-span-4 mb-4'):
|
||||
ui.label('Analytics Dashboard').classes('text-4xl font-extrabold tracking-tight text-white')
|
||||
ui.label('AI-driven insights for Q3').classes('text-lg text-slate-400 mt-1')
|
||||
|
||||
# Large Feature Card (Glassmorphism + Functional Motion)
|
||||
with ui.element('div').classes('glass-card col-span-1 md:col-span-2 p-6 transition-transform duration-300 hover:scale-[1.02]'):
|
||||
ui.icon('monitoring', size='2rem').classes('text-primary mb-4')
|
||||
ui.label('Revenue Prediction').classes('text-xl font-semibold text-slate-100')
|
||||
ui.label('$45,231.00').classes('text-5xl font-bold text-white mt-2')
|
||||
# Placeholder for an interactive EChart
|
||||
ui.echart({
|
||||
'xAxis': {
|
||||
'type': 'category',
|
||||
'data': [
|
||||
'Mon',
|
||||
'Tue',
|
||||
'Wed',
|
||||
'Thu',
|
||||
'Fri',
|
||||
],
|
||||
},
|
||||
'yAxis': {
|
||||
'type': 'value',
|
||||
},
|
||||
'series': [
|
||||
{
|
||||
'data': [
|
||||
120,
|
||||
200,
|
||||
150,
|
||||
80,
|
||||
70,
|
||||
],
|
||||
'type': 'bar',
|
||||
'itemStyle': {
|
||||
'color': '#6366f1',
|
||||
},
|
||||
},
|
||||
],
|
||||
}).classes('w-full h-48 mt-4')
|
||||
|
||||
# Smaller Metric Cards
|
||||
metric_cards = [
|
||||
{
|
||||
'title': 'Active Users',
|
||||
'value': '1,204',
|
||||
'icon': 'group',
|
||||
'color': 'text-secondary',
|
||||
},
|
||||
{
|
||||
'title': 'Server Load',
|
||||
'value': '34%',
|
||||
'icon': 'memory',
|
||||
'color': 'text-accent',
|
||||
},
|
||||
]
|
||||
|
||||
for card in metric_cards:
|
||||
with ui.element('div').classes('glass-card col-span-1 p-6 flex flex-col justify-between transition-transform duration-300 hover:-translate-y-1'):
|
||||
ui.icon(card['icon'], size='2rem').classes(card['color'])
|
||||
ui.element('div').classes('flex-grow')
|
||||
ui.label(card['value']).classes('text-4xl font-bold text-white mt-4')
|
||||
ui.label(card['title']).classes('text-sm font-medium text-slate-400 uppercase tracking-wider')
|
||||
|
||||
# AI Assistant Module (Adaptive Interface)
|
||||
with ui.element('div').classes('glass-card col-span-1 md:col-span-4 p-6 flex items-center gap-4'):
|
||||
ui.icon('smart_toy', size='2rem').classes('text-positive animate-pulse')
|
||||
with ui.element('div'):
|
||||
ui.label('Ambient AI Suggestion').classes('text-sm font-bold text-positive uppercase tracking-wider')
|
||||
ui.label('Based on current server load, scaling up instances in the EU-West region is recommended.').classes('text-slate-300')
|
||||
ui.space()
|
||||
ui.button('Apply Now', color='positive').classes('rounded-full px-6 py-2 shadow-lg shadow-positive/20')
|
||||
|
||||
ui.run(title='2026 UI Dashboard')
|
||||
@@ -0,0 +1,80 @@
|
||||
# UI Documentation
|
||||
|
||||
This folder contains UI-focused design and mapping documents that connect the database schema to user-facing workflows.
|
||||
|
||||
## Document Types
|
||||
|
||||
### user-journey.md
|
||||
|
||||
A product and UX contract for a user-facing entity.
|
||||
|
||||
Use this document to describe:
|
||||
- what the user is trying to do
|
||||
- which screen or action starts the workflow
|
||||
- which fields the user sees and edits
|
||||
- validation rules
|
||||
- expected success and failure outcomes
|
||||
- where the user goes next
|
||||
|
||||
### schema-mapping.md
|
||||
|
||||
A field-level mapping between schema, UI, and implementation.
|
||||
|
||||
Use this document to describe:
|
||||
- the authoritative schema fields for an entity
|
||||
- which fields are shown, hidden, editable, or system-managed
|
||||
- current implementation behavior
|
||||
- intended target behavior
|
||||
- implementation gaps between current code and intended UX
|
||||
|
||||
### acceptance-criteria.md
|
||||
|
||||
An implementation-ready checklist for CRUD behavior and quality gates.
|
||||
|
||||
Use this document to describe:
|
||||
- testable acceptance statements by flow (Create, Read, Update, Delete)
|
||||
- success and failure behaviors
|
||||
- first-release constraints
|
||||
- cross-criteria quality gates
|
||||
|
||||
### traceability-matrix.md
|
||||
|
||||
A criteria-to-code mapping that identifies implementation anchors and status.
|
||||
|
||||
Use this document to describe:
|
||||
- acceptance criteria group to implementation file mapping
|
||||
- delivery status (implemented, partial, planned)
|
||||
- ordered implementation priorities
|
||||
|
||||
## Organization Rules
|
||||
|
||||
- Store documents under `docs/ui/entities/<entity-name>/`.
|
||||
- Create both `user-journey.md` and `schema-mapping.md` for user-facing entities.
|
||||
- Create `acceptance-criteria.md` for user-facing entities.
|
||||
- Create only `schema-mapping.md` for supporting tables that do not currently have standalone UI.
|
||||
- Keep one shared `traceability-matrix.md` under `docs/ui/entities/` to map criteria to implementation anchors.
|
||||
- Keep top-level `docs/` reserved for core architecture, requirements, schema, and system-wide reference material.
|
||||
|
||||
## Current Entity Plan
|
||||
|
||||
User-facing entities:
|
||||
- `document`
|
||||
- `person`
|
||||
- `source`
|
||||
- `job`
|
||||
|
||||
Supporting entities:
|
||||
- `document-person`
|
||||
- `job-source`
|
||||
|
||||
## Relationship to Core Docs
|
||||
|
||||
These UI docs complement, but do not replace:
|
||||
- `docs/schema_v2.md`
|
||||
- `docs/requirements_v2.md`
|
||||
- `docs/architecture_v2.md`
|
||||
|
||||
When there is a conflict:
|
||||
- schema definitions come from the database model and schema docs
|
||||
- user interaction intent comes from the user-journey docs
|
||||
- implementation truth comes from code and is recorded in schema-mapping docs as current-state evidence
|
||||
@@ -0,0 +1,182 @@
|
||||
# DocumentPerson Schema-to-UI Mapping
|
||||
|
||||
Purpose: Map the DocumentPerson schema to UI-facing workflows, while separating intended target behavior from current implementation.
|
||||
|
||||
Supporting entity note: DocumentPerson does not currently have a standalone UI surface.
|
||||
|
||||
## 1. Entity Snapshot
|
||||
|
||||
- Table: document_person
|
||||
- Primary key: id (UUID)
|
||||
- Related entities: Document, Person
|
||||
- Canonical schema references:
|
||||
- src/transcription/db/models.py
|
||||
- docs/schema_v2.md
|
||||
|
||||
## 2. Mapping Rules
|
||||
|
||||
This document uses three lenses:
|
||||
1. Intended behavior: what user-facing workflows should support indirectly.
|
||||
2. Current behavior: what code supports today.
|
||||
3. Gap to target: what must change to align implementation with intended UX.
|
||||
|
||||
## 3. Field Inventory
|
||||
|
||||
| Field | DB Type | Nullable | Default/Auto Value | Intended UI Treatment | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| id | UUID | No | uuid4() | Hidden, system-managed | Primary key |
|
||||
| document_id | UUID FK | No | None | Context-managed | Selected Document context |
|
||||
| person_id | UUID FK | No | None | Context-managed | Selected Person context |
|
||||
| role | enum DocumentPersonRole | No | author | Visible in relationship context | First-release behavior may default to author |
|
||||
| created_at | datetime | No | datetime.now(UTC) | Hidden or read-only | System-managed timestamp |
|
||||
|
||||
Constraint behavior:
|
||||
1. document_id, person_id, and role are unique as a tuple.
|
||||
2. duplicate links for the same document, person, and role must be rejected.
|
||||
|
||||
## 4. CREATE Mapping
|
||||
|
||||
### 4.1 Intended Create Flow
|
||||
|
||||
Entry points are indirect through user-facing entities:
|
||||
1. Document create or update workflows may create one or more DocumentPerson links.
|
||||
2. Person relationship workflows may create DocumentPerson links.
|
||||
|
||||
| Field | Intended User Input | Required | Visible | Notes |
|
||||
|---|---|---|---|---|
|
||||
| document_id | None | Yes | No | Derived from selected Document |
|
||||
| person_id | None | Yes | No | Derived from selected Person |
|
||||
| role | Select or default | Yes | Indirectly | Defaults to author in first-release behavior |
|
||||
| created_at | None | No | No | System-generated |
|
||||
|
||||
### 4.2 Current Implementation
|
||||
|
||||
Current entry point: Document create/edit flows
|
||||
Current user action: select an existing Person from the Document author dropdown
|
||||
Current backend path: Document page submit callback -> `DocumentService.create_document_person()` or `delete_document_person()` as the author selection changes
|
||||
|
||||
| Field | Current Value at Create | Source | Visible to User | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| id | Generated UUID | System | No | src/transcription/db/models.py |
|
||||
| document_id | Caller-provided | Document UI | Indirectly | src/transcription/ui/pages/documents_page.py |
|
||||
| person_id | Caller-provided | Document UI | Indirectly | src/transcription/ui/pages/documents_page.py |
|
||||
| role | Default author in current UI | Service/model default | No | src/transcription/db/models.py, src/transcription/services/documents.py |
|
||||
| created_at | Current UTC timestamp | System | No | src/transcription/db/models.py |
|
||||
|
||||
### 4.3 Gap to Target
|
||||
|
||||
To satisfy intended supporting behavior, implementation must add:
|
||||
1. explicit UI relationship controls in Document and/or Person detail flows.
|
||||
2. duplicate-link handling with clear user feedback.
|
||||
3. role-selection UX when role expansion is enabled beyond default author.
|
||||
|
||||
## 5. READ Mapping
|
||||
|
||||
### 5.1 Intended Read Behavior
|
||||
|
||||
Users should see DocumentPerson relationships indirectly in user-facing surfaces:
|
||||
1. Document detail shows linked people.
|
||||
2. Person detail shows linked documents.
|
||||
3. Relationship role is shown where relevant.
|
||||
|
||||
### 5.2 Current Implementation
|
||||
|
||||
Current read behavior is mainly service-level.
|
||||
|
||||
| Field | Current Rendering | Visible to User | Notes | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| document_id/person_id link | Indirect relationship usage in workflows | Partial | Document/Person dedicated relationship surfaces are planned | docs/ui/entities/document/*, docs/ui/entities/person/* |
|
||||
| role | Not shown in current job-centric pages | No | Role expansion is deferred in user-facing workflows | docs/ui/entities/person/user-journey.md |
|
||||
| created_at | Not rendered | No | Operational metadata only | current UI pages |
|
||||
|
||||
Service read/query coverage:
|
||||
1. read_document_person() returns one link by id.
|
||||
2. list_document_people() supports filtering by document_id and person_id.
|
||||
|
||||
### 5.3 Gap to Target
|
||||
|
||||
To satisfy intended read behavior, implementation must add:
|
||||
1. linked-people and linked-documents UI sections backed by list_document_people().
|
||||
2. relationship role display where role context is required.
|
||||
|
||||
## 6. UPDATE Mapping
|
||||
|
||||
### 6.1 Intended Update Behavior
|
||||
|
||||
DocumentPerson updates are limited to relationship role or relationship-management actions.
|
||||
|
||||
Intended editable fields:
|
||||
- role (when role management is enabled)
|
||||
|
||||
Intended read-only fields:
|
||||
- id
|
||||
- document_id
|
||||
- person_id
|
||||
- created_at
|
||||
|
||||
### 6.2 Current Implementation
|
||||
|
||||
| Field | Updatable via UI | Updatable via Service | Notes |
|
||||
|---|---|---|---|
|
||||
| role | No | Yes | DocumentService.update_document_person() supports updates |
|
||||
| document_id/person_id | No | Technically yes via full-row update | Should generally be treated as immutable link identity |
|
||||
| created_at | No | Technically yes | Should remain system-managed |
|
||||
|
||||
### 6.3 Gap to Target
|
||||
|
||||
Implementation should add:
|
||||
1. explicit relationship-role edit controls when product scope enables them.
|
||||
2. safeguards against mutating link identity instead of recreating links.
|
||||
|
||||
## 7. DELETE Mapping
|
||||
|
||||
### 7.1 Intended Delete Behavior
|
||||
|
||||
Deletion of DocumentPerson should be exposed as unlink behavior in Document and Person flows.
|
||||
|
||||
Rules:
|
||||
1. unlink should remove only the selected relationship.
|
||||
2. unlink must not delete the underlying Document or Person records.
|
||||
|
||||
### 7.2 Current Implementation
|
||||
|
||||
| Action | UI Exposed | Backend Capability | Notes |
|
||||
|---|---|---|---|
|
||||
| Delete DocumentPerson link | No | Yes | DocumentService.delete_document_person() exists |
|
||||
|
||||
### 7.3 Gap to Target
|
||||
|
||||
Implementation must add:
|
||||
1. unlink controls in relationship sections.
|
||||
2. confirmation and success feedback for relationship removal.
|
||||
3. blocked-delete guidance if policy constraints are added later.
|
||||
|
||||
## 8. Hidden and System-Managed Fields
|
||||
|
||||
| Field | Category | Why Hidden or Protected |
|
||||
|---|---|---|
|
||||
| id | System-managed | Internal identifier |
|
||||
| document_id | Context-managed | Derived from selected Document |
|
||||
| person_id | Context-managed | Derived from selected Person |
|
||||
| created_at | System-managed | Audit timestamp |
|
||||
|
||||
## 9. Traceability Anchors
|
||||
|
||||
Schema and models:
|
||||
- docs/schema_v2.md
|
||||
- src/transcription/db/models.py
|
||||
|
||||
Current implementation:
|
||||
- src/transcription/services/documents.py
|
||||
- tests/services/test_v2_crud.py
|
||||
|
||||
Related user-facing workflows:
|
||||
- docs/ui/entities/document/user-journey.md
|
||||
- docs/ui/entities/person/user-journey.md
|
||||
|
||||
## 10. Coverage Summary
|
||||
|
||||
- Every DocumentPerson schema field appears in the field inventory.
|
||||
- Intended behavior is defined as supporting workflow behavior rather than standalone UI.
|
||||
- Current behavior reflects UI-backed CRUD through Document create/edit flows and Person detail rendering, with no standalone DocumentPerson UI.
|
||||
- Gaps between intended and current behavior are explicit.
|
||||
@@ -0,0 +1,136 @@
|
||||
# Document Acceptance Criteria
|
||||
|
||||
Purpose: Define implementation-ready acceptance criteria for Document Read, Update, and Delete workflows.
|
||||
|
||||
Companion documents:
|
||||
- docs/ui/entities/document/user-journey.md
|
||||
- docs/ui/entities/document/schema-mapping.md
|
||||
|
||||
## Scope
|
||||
|
||||
This checklist covers:
|
||||
1. Read flow
|
||||
2. Update flow
|
||||
3. Delete flow
|
||||
|
||||
This checklist does not cover:
|
||||
1. Source upload workflow details
|
||||
2. Job execution internals
|
||||
3. Revision editor behavior
|
||||
|
||||
## Read Acceptance Criteria
|
||||
|
||||
### RD-1 Document detail retrieval
|
||||
1. Given a valid Document id
|
||||
2. When the user opens the Document detail page
|
||||
3. Then the system displays Document metadata for that record only
|
||||
|
||||
### RD-2 Metadata visibility
|
||||
1. The page shows name, document_type, document_date, document_date_raw, location_created, notes, archive_identifier
|
||||
2. created_at and updated_at are displayed as system-managed, read-only values
|
||||
|
||||
### RD-3 Related people section
|
||||
1. Given zero linked people
|
||||
2. Then the page shows a no linked people yet empty state
|
||||
3. Given one linked person
|
||||
4. Then the page shows that linked person
|
||||
|
||||
### RD-4 Sources section empty state
|
||||
1. The page shows a Sources action for the current Document
|
||||
2. The page shows a primary + Add Source action that opens job-create flow for this Document
|
||||
3. The action routes to a document-scoped Sources view
|
||||
|
||||
### RD-5 Jobs section empty state
|
||||
1. The page shows a Jobs action for the current Document
|
||||
2. The page shows a primary + Add Job action for the current Document
|
||||
3. The action routes to a document-scoped Jobs view
|
||||
|
||||
### RD-6 Filtered navigation readiness
|
||||
1. The detail page provides links or actions that can route to document-scoped Sources and Jobs views
|
||||
2. Target views are filtered to the current Document id
|
||||
|
||||
### RD-7 Failure state
|
||||
1. Given a nonexistent Document id
|
||||
2. Then the UI shows a clear not found state without crashing
|
||||
|
||||
## Update Acceptance Criteria
|
||||
|
||||
### UP-1 Edit entry
|
||||
1. Given a loaded Document detail page
|
||||
2. When the user chooses Edit document
|
||||
3. Then editable controls are shown for allowed fields only, including the author relationship selector
|
||||
4. The author selector includes No author, existing Person options, and a Create new item option
|
||||
5. Selecting Create new item routes to Person create
|
||||
|
||||
### UP-2 Editable fields
|
||||
1. Editable: name, document_type, document_date, document_date_raw, location_created, notes, archive_identifier
|
||||
2. Not editable: id, created_at, updated_at
|
||||
3. The edit flow may also change the associated author Person link
|
||||
|
||||
### UP-3 Required validation
|
||||
1. name is required
|
||||
2. document_type is required
|
||||
3. Save is blocked with inline feedback when either required field is missing
|
||||
|
||||
### UP-4 Date handling rule
|
||||
1. document_date only is allowed
|
||||
2. document_date_raw only is allowed
|
||||
3. both fields together are allowed
|
||||
4. if both are present, document_date is treated as canonical exact date and document_date_raw is retained as descriptive context
|
||||
|
||||
### UP-5 Successful save
|
||||
1. Given valid input
|
||||
2. When the user saves
|
||||
3. Then changes persist
|
||||
4. Then success feedback is shown
|
||||
5. Then the user remains on Document detail with refreshed values
|
||||
6. Then updated_at reflects update policy
|
||||
|
||||
### UP-6 Save failure
|
||||
1. Given backend failure during save
|
||||
2. Then clear error feedback is shown
|
||||
3. Then the user-entered values remain available for retry where possible
|
||||
4. Then no false success feedback is shown
|
||||
|
||||
## Delete Acceptance Criteria
|
||||
|
||||
### DL-1 Delete entry and confirmation
|
||||
1. Given a Document detail page
|
||||
2. When the user chooses Delete document
|
||||
3. Then a confirmation dialog appears with permanent-action wording
|
||||
|
||||
### DL-2 Dependency guardrails
|
||||
1. Delete is allowed only when the Document has no related Source records and no related Job records
|
||||
2. Delete is blocked when at least one related Source or Job exists
|
||||
|
||||
### DL-3 Blocked delete behavior
|
||||
1. When blocked
|
||||
2. Then the UI explains why deletion is blocked
|
||||
3. Then the UI identifies dependency categories present: Sources, Jobs, or both
|
||||
4. Then the UI provides navigation to dependency cleanup paths
|
||||
|
||||
### DL-4 Successful delete
|
||||
1. Given no blocking dependencies
|
||||
2. When the user confirms delete
|
||||
3. Then the Document is removed
|
||||
4. Then success feedback is shown
|
||||
5. Then the user is returned to the Document list page
|
||||
|
||||
### DL-5 Delete failure
|
||||
1. Given backend failure during delete
|
||||
2. Then a clear error message is shown
|
||||
3. Then the user remains on Document detail with retry path
|
||||
|
||||
## Cross-Criteria Quality Gates
|
||||
|
||||
### QG-1 Separation of intent and implementation
|
||||
1. UX intent remains in user-journey.md
|
||||
2. Current versus target implementation mapping remains in schema-mapping.md
|
||||
|
||||
### QG-2 Traceability
|
||||
1. Each accepted behavior maps to at least one future UI action or service call path
|
||||
2. No acceptance criterion contradicts the current deferred-item policy
|
||||
|
||||
### QG-3 First-release constraints
|
||||
1. Linked person during create remains optional
|
||||
2. Recipient and multi-person expansion remain deferred
|
||||
@@ -0,0 +1,231 @@
|
||||
# Document Schema-to-UI Mapping
|
||||
|
||||
Purpose: Map the Document schema to the UI, while clearly separating intended target behavior from current implementation.
|
||||
|
||||
Companion document: user-journey.md
|
||||
Acceptance criteria: acceptance-criteria.md
|
||||
|
||||
## 1. Entity Snapshot
|
||||
|
||||
- Table: Document
|
||||
- Primary key: `id` (UUID)
|
||||
- Related entities: `Source`, `Job`, `DocumentPerson`, `Person`
|
||||
- Canonical schema references:
|
||||
- `src/transcription/db/models.py`
|
||||
- `docs/schema_v2.md`
|
||||
|
||||
## 2. Mapping Rules
|
||||
|
||||
This document uses three lenses:
|
||||
1. Intended behavior: what the UX should support.
|
||||
2. Current behavior: what the code supports today.
|
||||
3. Gap to target: what must change to align implementation with the intended UX.
|
||||
|
||||
## 3. Field Inventory
|
||||
|
||||
| Field | DB Type | Nullable | Default/Auto Value | Intended UI Treatment | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| id | UUID | No | `uuid4()` | Hidden, system-managed | Primary key |
|
||||
| name | str | No | None | Shown, editable on create and edit | Required |
|
||||
| document_type | str | Yes | None | Shown, editable on create and edit | Required by intended UX |
|
||||
| document_date | date | Yes | None | Shown, editable | Canonical exact date when present |
|
||||
| document_date_raw | str | Yes | None | Shown, editable | Approximate or unknown date text |
|
||||
| location_created | str | Yes | None | Shown, editable | Optional metadata |
|
||||
| notes | str | Yes | None | Shown, editable | Optional metadata |
|
||||
| archive_identifier | str | Yes | None | Shown, editable | Free text in first release |
|
||||
| created_at | datetime | No | `datetime.now(UTC)` | Hidden or read-only | System-managed |
|
||||
| updated_at | datetime | No | `datetime.now(UTC)` | Hidden or read-only | System-managed |
|
||||
|
||||
## 4. CREATE Mapping
|
||||
|
||||
### 4.1 Intended Create Flow
|
||||
|
||||
Entry point: Document page
|
||||
User action: Create new document
|
||||
Success destination: new Document detail page
|
||||
|
||||
| Field | Intended User Input | Required | Visible | Notes |
|
||||
|---|---|---|---|---|
|
||||
| name | Text input | Yes | Yes | Primary identifier used by the user |
|
||||
| document_type | Text input | Yes | Yes | Free text in first release |
|
||||
| document_date | Date input | No | Yes | Structured exact date |
|
||||
| document_date_raw | Text input | No | Yes | Approximate or uncertain date |
|
||||
| location_created | Text input | No | Yes | Optional |
|
||||
| notes | Text area | No | Yes | Optional |
|
||||
| archive_identifier | Text input | No | Yes | Free text |
|
||||
| created_at | None | No | No | System-generated |
|
||||
| updated_at | None | No | No | Not used during initial create |
|
||||
|
||||
Related records during intended create:
|
||||
- A related person may optionally be selected or created.
|
||||
- If present, the system creates a `DocumentPerson` link.
|
||||
- Jobs are not created during Document create.
|
||||
- Sources are not created during Document create.
|
||||
|
||||
### 4.2 Current Implementation
|
||||
|
||||
Current entry point: `/documents` page
|
||||
Current user action: open create form, fill metadata, optionally select an existing Person
|
||||
Current backend path: document page submit callback -> `DocumentService.create_document()` -> optional `DocumentService.create_document_person()`
|
||||
|
||||
| Field | Current Value at Create | Source | Visible to User | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| id | Generated UUID | System | No | `Document` default factory in `src/transcription/db/models.py` |
|
||||
| name | User-provided | User input | Yes | `src/transcription/ui/pages/documents_page.py` |
|
||||
| document_type | User-provided or None | User input | Yes | `src/transcription/ui/pages/documents_page.py` |
|
||||
| document_date | Parsed from date input or None | User input | Yes | `src/transcription/ui/pages/documents_page.py` |
|
||||
| document_date_raw | User-provided or None | User input | Yes | `src/transcription/ui/pages/documents_page.py` |
|
||||
| location_created | User-provided or None | User input | Yes | `src/transcription/ui/pages/documents_page.py` |
|
||||
| notes | User-provided or None | User input | Yes | `src/transcription/ui/pages/documents_page.py` |
|
||||
| archive_identifier | User-provided or None | User input | Yes | `src/transcription/ui/pages/documents_page.py` |
|
||||
| created_at | Current UTC timestamp | System | No | Default factory in `src/transcription/db/models.py` |
|
||||
| updated_at | Current UTC timestamp | System | No | Default factory in `src/transcription/db/models.py` |
|
||||
|
||||
Current related-record behavior:
|
||||
- User may optionally select an existing `Person`.
|
||||
- If selected, `DocumentPerson` is created with role `author`.
|
||||
- `Job` is not created during Document create.
|
||||
- `Source` is not created during Document create.
|
||||
|
||||
### 4.3 Gap to Target
|
||||
|
||||
To satisfy the intended Create flow, implementation now includes:
|
||||
1. a Document page and dedicated create form
|
||||
2. user-entered metadata fields for `document_type`, `document_date`, `document_date_raw`, `location_created`, `notes`, and `archive_identifier`
|
||||
3. optional Person lookup through a dropdown of existing people
|
||||
4. optional `DocumentPerson` link creation when a person is chosen
|
||||
5. post-submit routing to a Document detail page
|
||||
|
||||
## 5. READ Mapping
|
||||
|
||||
### 5.1 Intended Read Behavior
|
||||
|
||||
On the Document detail page, the user should be able to see:
|
||||
1. Document metadata
|
||||
2. linked people
|
||||
3. a Sources section with empty-state behavior when no sources exist
|
||||
4. a Jobs section with empty-state behavior when no jobs exist
|
||||
5. filtered Jobs and Sources views for the current document
|
||||
|
||||
### 5.2 Current Implementation
|
||||
|
||||
Current Document visibility in the UI is direct.
|
||||
|
||||
| Field | Current Rendering | Visible to User | Notes | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| name | Rendered as title and detail heading | Yes | Dedicated Document detail page | `src/transcription/ui/pages/documents_page.py` |
|
||||
| id | Not shown as raw id | No | Internal identifier remains hidden | `src/transcription/ui/pages/documents_page.py` |
|
||||
| document_type | Rendered | Yes | Shown on detail and editable on create/edit | `src/transcription/ui/pages/documents_page.py` |
|
||||
| document_date | Rendered | Yes | Exact date shown when present | `src/transcription/ui/pages/documents_page.py` |
|
||||
| document_date_raw | Rendered | Yes | Approximate date shown when present | `src/transcription/ui/pages/documents_page.py` |
|
||||
| location_created | Rendered | Yes | Optional metadata shown | `src/transcription/ui/pages/documents_page.py` |
|
||||
| notes | Rendered | Yes | Optional metadata shown | `src/transcription/ui/pages/documents_page.py` |
|
||||
| archive_identifier | Rendered | Yes | Optional metadata shown | `src/transcription/ui/pages/documents_page.py` |
|
||||
| created_at | Rendered read-only | Yes | System timestamp shown on detail | `src/transcription/ui/pages/documents_page.py` |
|
||||
| updated_at | Rendered read-only | Yes | System timestamp shown on detail | `src/transcription/ui/pages/documents_page.py` |
|
||||
|
||||
### 5.3 Gap to Target
|
||||
|
||||
To satisfy the intended Read flow, implementation now includes:
|
||||
1. metadata rendering for Document fields
|
||||
2. linked people rendering
|
||||
3. document-scoped Sources and Jobs navigation views
|
||||
|
||||
## 6. UPDATE Mapping
|
||||
|
||||
### 6.1 Intended Update Behavior
|
||||
|
||||
The user should eventually be able to edit Document metadata from the Document detail page or a dedicated edit flow.
|
||||
|
||||
Intended editable fields:
|
||||
- `name`
|
||||
- `document_type`
|
||||
- `document_date`
|
||||
- `document_date_raw`
|
||||
- `location_created`
|
||||
- `notes`
|
||||
- `archive_identifier`
|
||||
|
||||
Intended system-managed fields:
|
||||
- `id`
|
||||
- `created_at`
|
||||
- `updated_at`
|
||||
|
||||
### 6.2 Current Implementation
|
||||
|
||||
| Field | Updatable via UI | Updatable via Service | Notes |
|
||||
|---|---|---|---|
|
||||
| id | No | Practically no | Primary key should be treated as immutable |
|
||||
| name | Yes | Yes | Editable from dedicated document edit page via `DocumentService.update_document()` |
|
||||
| document_type | Yes | Yes | Editable from dedicated document edit page via `DocumentService.update_document()` |
|
||||
| document_date | Yes | Yes | Editable from dedicated document edit page via `DocumentService.update_document()` |
|
||||
| document_date_raw | Yes | Yes | Editable from dedicated document edit page via `DocumentService.update_document()` |
|
||||
| location_created | Yes | Yes | Editable from dedicated document edit page via `DocumentService.update_document()` |
|
||||
| notes | Yes | Yes | Editable from dedicated document edit page via `DocumentService.update_document()` |
|
||||
| archive_identifier | Yes | Yes | Editable from dedicated document edit page via `DocumentService.update_document()` |
|
||||
| created_at | No | Technically yes | Should remain system-managed |
|
||||
| updated_at | No | Technically yes | Should remain system-managed |
|
||||
|
||||
### 6.3 Gap to Target
|
||||
|
||||
Implementation now includes:
|
||||
1. Document edit controls in the UI
|
||||
2. validation and save behavior for Document metadata
|
||||
3. author relationship controls through the edit flow
|
||||
|
||||
## 7. DELETE Mapping
|
||||
|
||||
### 7.1 Intended Delete Behavior
|
||||
|
||||
The UI should eventually provide a delete action for Document with guardrails.
|
||||
|
||||
Rules:
|
||||
1. A Document can be deleted when it has no attached Jobs and no attached Sources.
|
||||
2. If dependent Jobs or Sources exist, the UI should block deletion and explain that those related records must be removed first.
|
||||
3. Delete confirmation should make it clear that the action is permanent.
|
||||
|
||||
### 7.2 Current Implementation
|
||||
|
||||
| Action | UI Exposed | Backend Capability | Notes |
|
||||
|---|---|---|---|
|
||||
| Delete Document | Yes | Yes | `DocumentService.delete_document()` exists and the UI blocks dependent deletes |
|
||||
|
||||
### 7.3 Gap to Target
|
||||
|
||||
Implementation includes:
|
||||
1. a Document delete control in the UI
|
||||
2. pre-delete dependency checks for Jobs and Sources
|
||||
3. user-facing messaging when deletion is blocked
|
||||
4. confirmation UX for successful delete attempts
|
||||
|
||||
## 8. Hidden and System-Managed Fields
|
||||
|
||||
| Field | Category | Why Hidden or Protected |
|
||||
|---|---|---|
|
||||
| id | System-managed | Internal identifier |
|
||||
| created_at | System-managed | Audit timestamp |
|
||||
| updated_at | System-managed | Audit timestamp |
|
||||
|
||||
## 9. Traceability Anchors
|
||||
|
||||
Schema and models:
|
||||
- `docs/schema_v2.md`
|
||||
- `src/transcription/db/models.py`
|
||||
|
||||
Current implementation:
|
||||
- `src/transcription/ui/pages/documents_page.py`
|
||||
- `src/transcription/services/documents.py`
|
||||
- `src/transcription/services/store.py`
|
||||
- `src/transcription/ui/pages/jobs_page.py`
|
||||
- `src/transcription/ui/components/transcript.py`
|
||||
|
||||
Companion UX spec:
|
||||
- `docs/ui/entities/document/user-journey.md`
|
||||
|
||||
## 10. Acceptance Checklist Summary
|
||||
|
||||
- Every Document schema field appears in the field inventory.
|
||||
- Intended Create behavior matches the companion user journey.
|
||||
- Current Create behavior reflects the existing upload-driven implementation.
|
||||
- Gaps between intended and current behavior are explicit.
|
||||
- Read, Update, and Delete sections distinguish target behavior from current code.
|
||||
@@ -0,0 +1,427 @@
|
||||
# Document User Journey
|
||||
|
||||
Purpose: Define how a user should interact with the UI to create and manage a Document record, including expected inputs, validation, results, and related record creation.
|
||||
|
||||
Scope: This document describes intended user interaction for the Document UI. It is the UX contract for the Document entity.
|
||||
|
||||
Companion schema mapping: schema-mapping.md
|
||||
Companion acceptance criteria: acceptance-criteria.md
|
||||
|
||||
## 1. Overview
|
||||
|
||||
A Document represents a real historical artifact the user wants to describe, organize, and eventually transcribe. The user should be able to create a Document before uploading or linking any source files.
|
||||
|
||||
Creating a Document is a metadata-first workflow:
|
||||
1. The user opens the Document page.
|
||||
2. The user selects Create new document.
|
||||
3. The user enters descriptive metadata about the document.
|
||||
4. The user optionally selects one related person from the existing Person list.
|
||||
5. The system creates the Document.
|
||||
6. If a person was selected, the system links that Person to the Document through DocumentPerson with author role.
|
||||
7. The user sees a success state and lands on the new Document detail page.
|
||||
|
||||
## 2. User Goal
|
||||
|
||||
The user wants to create a new Document record that:
|
||||
1. Has enough metadata to identify the historical artifact.
|
||||
2. Can optionally be linked to a person.
|
||||
3. Exists independently of transcription jobs and source uploads.
|
||||
4. Is ready for later steps such as adding sources, starting jobs, and reviewing transcriptions.
|
||||
|
||||
## 3. Page Model
|
||||
|
||||
### 3.1 Document Page
|
||||
|
||||
The Document page is the general UI surface where users manage documents.
|
||||
|
||||
It should support:
|
||||
1. listing or locating existing documents
|
||||
2. starting the Create new document flow
|
||||
3. navigating into a specific Document after it exists
|
||||
|
||||
### 3.2 Document Detail Page
|
||||
|
||||
The Document detail page is the page for one specific Document after it has been created.
|
||||
|
||||
It should show:
|
||||
1. the Document metadata
|
||||
2. related people linked to the Document
|
||||
3. a linked-author summary when available
|
||||
4. document-scoped navigation links for Sources and Jobs
|
||||
5. filtered views for sources and jobs linked to the current document
|
||||
6. primary actions + Add Source and + Add Job
|
||||
|
||||
## 4. Entry Point
|
||||
|
||||
Entry point: Document page
|
||||
|
||||
Primary action: Create new document
|
||||
|
||||
Expected UI affordance:
|
||||
1. A visible button, link, or primary action labeled Create new document.
|
||||
2. Activation opens a dedicated form view, modal, or detail panel for creating a Document.
|
||||
|
||||
Preferred first implementation:
|
||||
1. A dedicated Document create page or panel.
|
||||
2. A simple form with explicit labels.
|
||||
3. Existing Person records should be selectable through a dropdown.
|
||||
4. Text inputs are acceptable for the remaining fields in first release.
|
||||
|
||||
## 5. Create Document Form
|
||||
|
||||
The Create Document form should contain the following fields.
|
||||
|
||||
### 5.1 Required Fields
|
||||
|
||||
| UI Label | Schema Field | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Document name | name | Text input | Yes | Examples: Pioneer Days, Letter from Zenna to Omie |
|
||||
| Document type | document_type | Text input | Yes | Examples: book, letter, enlistment papers, military record, other |
|
||||
|
||||
### 5.2 Date Fields
|
||||
|
||||
| UI Label | Schema Field | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Exact date | document_date | Date input | No | Use when the exact date is known |
|
||||
| Approximate date | document_date_raw | Text input | No | Use when exact date is uncertain, approximate, or unknown |
|
||||
|
||||
Date handling rule:
|
||||
1. The form may allow both fields to be entered.
|
||||
2. If both fields are entered, `document_date` is the canonical structured date.
|
||||
3. `document_date_raw` may still be retained as the user-entered descriptive form.
|
||||
4. The UI should explain the distinction clearly.
|
||||
|
||||
Examples:
|
||||
1. Exact date: `07/13/1885`
|
||||
2. Approximate date: `c. 1885`
|
||||
3. Approximate date: `Fall 1925`
|
||||
4. Approximate date: `unknown`
|
||||
|
||||
### 5.3 Optional Metadata Fields
|
||||
|
||||
| UI Label | Schema Field | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Document location | location_created | Text input | No | Where the document was created |
|
||||
| Notes | notes | Multiline text area | No | Freeform notes about the document |
|
||||
| Archive identifier | archive_identifier | Text input | No | Free text for now; may represent inventory code, storage reference, or repository note |
|
||||
|
||||
Archive identifier guidance:
|
||||
1. First implementation should treat this as free text.
|
||||
2. Helper text may explain that this can store a repository code, box or folder reference, or storage note.
|
||||
|
||||
### 5.4 System Fields
|
||||
|
||||
| Schema Field | User Editable | Notes |
|
||||
|---|---|---|
|
||||
| created_at | No | System-generated at creation time |
|
||||
| updated_at | No | Not user-entered during creation |
|
||||
|
||||
### 5.5 Optional Related Person
|
||||
|
||||
The Create Document flow may optionally link one related person during first release.
|
||||
|
||||
| UI Label | Schema Area | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Related person | Person -> DocumentPerson | Dropdown select | No | Selects an existing Person and links as author when saved |
|
||||
|
||||
First release behavior:
|
||||
1. The user may save a Document without linking any person.
|
||||
2. If a person is linked during create, only one person is supported in first release.
|
||||
3. The selected person is linked as author.
|
||||
4. Additional people and recipient workflows are deferred to a future revision.
|
||||
|
||||
### 5.6 Related Records Not Created Directly Here
|
||||
|
||||
| Related Area | Included in Document Create | Notes |
|
||||
|---|---|---|
|
||||
| Jobs | No | Jobs are created later when transcription work begins |
|
||||
| Sources | No | Sources are added later as uploaded pages or files |
|
||||
|
||||
## 6. Related Person Workflow
|
||||
|
||||
### 6.1 User Intent
|
||||
|
||||
The user should be able to:
|
||||
1. select an existing Person to associate with the Document
|
||||
2. change the associated Person from the Document edit flow
|
||||
3. save the Document even if no person is linked
|
||||
|
||||
### 6.2 Data Model Interpretation
|
||||
|
||||
Person selection source:
|
||||
1. The UI should select from Person records.
|
||||
2. If a person is linked, the system should create a DocumentPerson record.
|
||||
3. Role handling for non-author document relationships is deferred.
|
||||
4. If the first release needs a persisted role immediately, the role can default to `author` until the relationship model is broadened.
|
||||
|
||||
This means:
|
||||
1. The user does not choose from DocumentPerson records.
|
||||
2. DocumentPerson is the relationship created after the Person is chosen or created.
|
||||
|
||||
### 6.3 Related Person UI Behavior
|
||||
|
||||
Minimum acceptable first implementation:
|
||||
1. Dropdown of existing Person records.
|
||||
2. Clear display of the selected related person before submit.
|
||||
3. Ability to change or clear the selected person in the Document edit flow.
|
||||
4. A Create new item option in the author selector that routes to Person create.
|
||||
5. A visible Create new person link near the selector.
|
||||
|
||||
If the person does not exist:
|
||||
1. The user can use Create new item from the author selector and continue from Person create.
|
||||
2. The Document create flow links existing Person records after selection.
|
||||
|
||||
## 7. Validation Rules
|
||||
|
||||
### 7.1 Required Field Validation
|
||||
|
||||
The form must reject submission if:
|
||||
1. `name` is empty
|
||||
2. `document_type` is empty
|
||||
|
||||
### 7.2 Date Validation
|
||||
|
||||
The form should allow:
|
||||
1. `document_date` only
|
||||
2. `document_date_raw` only
|
||||
3. both `document_date` and `document_date_raw`
|
||||
4. neither date field
|
||||
|
||||
If both are present:
|
||||
1. `document_date` is treated as the canonical exact date
|
||||
2. `document_date_raw` is retained as descriptive context
|
||||
|
||||
### 7.3 Related Person Validation
|
||||
|
||||
The form must not require a linked person in first release.
|
||||
|
||||
If a related person is selected or created:
|
||||
1. the selected value must resolve to a valid Person record before final save
|
||||
2. the DocumentPerson link must not be partially persisted on failure
|
||||
|
||||
## 8. Submission Behavior
|
||||
|
||||
When the user submits the form, the system should perform these logical steps:
|
||||
1. validate form inputs
|
||||
2. create the Document record
|
||||
3. create one DocumentPerson record only if an existing related person was selected
|
||||
4. persist intended records successfully before reporting success to the user
|
||||
|
||||
Expected write sequence:
|
||||
1. insert Document
|
||||
2. insert DocumentPerson link only if a person is linked
|
||||
|
||||
Recommended transactional behavior:
|
||||
1. Document and optional DocumentPerson writes should succeed or fail together
|
||||
2. Person creation is a separate workflow reached from the author selector and is not part of the same transaction
|
||||
|
||||
## 9. Expected Result After Success
|
||||
|
||||
After successful creation, the user should expect to see:
|
||||
1. confirmation that the Document was created successfully
|
||||
2. the Document name displayed in the resulting UI state
|
||||
3. the Document metadata displayed on the new Document detail page
|
||||
4. any linked person displayed in the resulting UI state
|
||||
5. a Sources section showing an empty state when no sources exist yet
|
||||
6. a Jobs section showing an empty state when no jobs exist yet
|
||||
7. a clear next step, such as adding source files
|
||||
|
||||
Recommended success route:
|
||||
1. navigate to the new Document detail page
|
||||
2. show Document summary metadata
|
||||
3. show linked people section
|
||||
4. show empty-state placeholders for Sources and Jobs
|
||||
|
||||
## 10. Expected Result After Failure
|
||||
|
||||
If submission fails, the user should expect:
|
||||
1. clear error messaging
|
||||
2. field-level validation feedback where applicable
|
||||
3. no false success message
|
||||
4. preservation of entered form values when possible
|
||||
|
||||
Examples:
|
||||
1. missing required name
|
||||
2. missing required document type
|
||||
3. failed person creation
|
||||
4. failed DocumentPerson link creation
|
||||
5. database or server error
|
||||
|
||||
## 11. Read Document Journey
|
||||
|
||||
### 11.1 User Intent
|
||||
|
||||
The user wants to open a specific Document and quickly understand:
|
||||
1. what the document is
|
||||
2. which people are linked to it
|
||||
3. whether sources exist
|
||||
4. whether jobs exist
|
||||
5. what the next action should be
|
||||
|
||||
### 11.2 Entry Points
|
||||
|
||||
A user can reach a Document detail page by:
|
||||
1. selecting a document from the Document page list
|
||||
2. being redirected after successfully creating a new document
|
||||
3. following a direct link to a known Document record
|
||||
|
||||
### 11.3 Document Detail Layout
|
||||
|
||||
The Document detail page should include:
|
||||
1. a header area with document name, document type, and key date values
|
||||
2. a metadata section with location_created, notes, and archive_identifier
|
||||
3. System metadata where created_at and updated_at are shown as read-only values
|
||||
4. a related people section
|
||||
5. a Sources section
|
||||
6. a Jobs section
|
||||
|
||||
The Document detail page should support:
|
||||
1. empty-state messaging when no related records exist
|
||||
2. clear next actions from each empty state
|
||||
3. filtered Sources and Jobs views scoped to the current document
|
||||
|
||||
### 11.4 Read Empty States
|
||||
|
||||
If no related records exist:
|
||||
1. People section says no linked people yet
|
||||
2. Sources section says no sources added yet
|
||||
3. Jobs section says no jobs created yet
|
||||
4. each section presents one clear next action
|
||||
|
||||
### 11.5 Read Success Criteria
|
||||
|
||||
A successful Read experience means:
|
||||
1. The user can identify the Document immediately
|
||||
2. The user can see whether work has started
|
||||
3. The user can navigate directly to document-scoped Jobs and Sources workflows
|
||||
|
||||
## 12. Update Document Journey
|
||||
|
||||
### 12.1 User Intent
|
||||
|
||||
The user wants to correct or enrich metadata after creation without touching jobs or source transcriptions directly.
|
||||
|
||||
### 12.2 Update Entry Point
|
||||
|
||||
From the Document detail page:
|
||||
1. The user selects Edit document
|
||||
2. UI opens edit mode or a dedicated edit view
|
||||
|
||||
### 12.3 Editable Fields
|
||||
|
||||
First release editable fields:
|
||||
1. name
|
||||
2. document_type
|
||||
3. document_date
|
||||
4. document_date_raw
|
||||
5. location_created
|
||||
6. notes
|
||||
7. archive_identifier
|
||||
|
||||
Read-only or system-managed fields:
|
||||
1. id
|
||||
2. created_at
|
||||
3. updated_at
|
||||
|
||||
### 12.4 Update Validation Rules
|
||||
|
||||
1. name remains required
|
||||
2. document_type remains required
|
||||
3. document_date and document_date_raw may both be present
|
||||
4. if both date fields are present, document_date remains canonical
|
||||
5. validation errors should be shown inline and block save
|
||||
|
||||
### 12.5 Update Save Behavior
|
||||
|
||||
On save:
|
||||
1. system validates form data
|
||||
2. system persists Document updates
|
||||
3. updated_at is refreshed by system policy
|
||||
4. UI shows a confirmation message
|
||||
5. user remains on Document detail page with refreshed values
|
||||
|
||||
### 12.6 Update Failure Behavior
|
||||
|
||||
If save fails:
|
||||
1. Show a clear error message
|
||||
2. keep user edits in form where possible
|
||||
3. do not show stale success messaging
|
||||
4. Allow retry without losing context
|
||||
|
||||
## 13. Delete Document Journey
|
||||
|
||||
### 13.1 User Intent
|
||||
|
||||
The user wants to remove a Document only when it is safe and unambiguous.
|
||||
|
||||
### 13.2 Delete Entry Point
|
||||
|
||||
From the Document detail page:
|
||||
1. The user selects Delete document
|
||||
2. UI opens a confirmation dialog explaining permanence
|
||||
|
||||
### 13.3 Delete Guardrails
|
||||
|
||||
Delete is allowed only when:
|
||||
1. the Document has no related Source records
|
||||
2. the Document has no related Job records
|
||||
|
||||
Delete is blocked when:
|
||||
1. any Source exists for the Document
|
||||
2. any Job exists for the Document
|
||||
|
||||
### 13.4 Blocked Delete UX
|
||||
|
||||
When blocked:
|
||||
1. Show an explicit reason that related Jobs or Sources exist
|
||||
2. Show which dependency types are present
|
||||
3. provide links to filtered Sources and Jobs for cleanup
|
||||
4. keep the Document unchanged
|
||||
|
||||
### 13.5 Allowed Delete UX
|
||||
|
||||
When allowed:
|
||||
1. Show final confirmation with document name
|
||||
2. perform delete
|
||||
3. show success confirmation
|
||||
4. return user to Document page list
|
||||
|
||||
### 13.6 Delete Failure Behavior
|
||||
|
||||
If delete fails due to system error:
|
||||
1. Show a clear error message
|
||||
2. keep user on Document detail page
|
||||
3. preserve ability to retry
|
||||
|
||||
## 14. Non-Goals for This Flow
|
||||
|
||||
The Document journey does not define:
|
||||
1. Source upload field-level UX
|
||||
2. Job execution internals
|
||||
3. revision editor behavior for transcriptions
|
||||
4. multi-person recipient workflows in first release
|
||||
|
||||
## 15. Relationship to Other Workflows
|
||||
|
||||
This Document workflow integrates with:
|
||||
1. Sources workflow for adding pages or files to the document
|
||||
2. Jobs workflow for transcription execution
|
||||
3. Person workflow for future expansion beyond one optional linked person
|
||||
|
||||
## 16. Relationship to Schema Mapping
|
||||
|
||||
This document is the intended UX contract.
|
||||
|
||||
The companion schema-mapping document should answer:
|
||||
1. which schema field appears on which screen
|
||||
2. whether the field is currently implemented
|
||||
3. whether the field is hidden, editable, or system-managed
|
||||
4. what the implementation gap is between intended UX and current code
|
||||
|
||||
## 17. Deferred Items
|
||||
|
||||
These topics are intentionally deferred to future revisions:
|
||||
1. multiple linked people during create and update
|
||||
2. recipient support during create and update
|
||||
3. a broader role model for non-author document relationships
|
||||
4. filtered Jobs and Sources list navigation details
|
||||
@@ -0,0 +1,206 @@
|
||||
# JobSource Schema-to-UI Mapping
|
||||
|
||||
Purpose: Map the JobSource schema to UI-facing workflows, while separating intended target behavior from current implementation.
|
||||
|
||||
Supporting entity note: JobSource does not currently have a standalone UI surface.
|
||||
|
||||
## 1. Entity Snapshot
|
||||
|
||||
- Table: job_source
|
||||
- Primary key: id (UUID)
|
||||
- Related entities: Job, Source
|
||||
- Canonical schema references:
|
||||
- src/transcription/db/models.py
|
||||
- docs/schema_v2.md
|
||||
|
||||
## 2. Mapping Rules
|
||||
|
||||
This document uses three lenses:
|
||||
1. Intended behavior: what user-facing workflows should support indirectly.
|
||||
2. Current behavior: what code supports today.
|
||||
3. Gap to target: what must change to align implementation with intended UX.
|
||||
|
||||
## 3. Field Inventory
|
||||
|
||||
| Field | DB Type | Nullable | Default/Auto Value | Intended UI Treatment | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| id | UUID | No | uuid4() | Hidden, system-managed | Primary key |
|
||||
| job_id | UUID FK | No | None | Context-managed | Selected Job context |
|
||||
| source_id | UUID FK | No | None | Context-managed | Selected Source context |
|
||||
| status | enum JobSourceStatus | No | pending | Shown in job detail source context | Per-source execution state |
|
||||
| raw_transcription | str | Yes | None | Shown read-only in review context | Machine output per source |
|
||||
| ai_metadata | JSONB/JSON | Yes | None | Hidden or advanced diagnostics | Provider metadata |
|
||||
| raw_api_response | JSONB/JSON | Yes | None | Hidden or advanced diagnostics | Low-level provider payload |
|
||||
| error_detail | str | Yes | None | Shown when status is failed | Execution failure details |
|
||||
| executed_at | datetime | No | datetime.now(UTC) | Shown read-only | Execution timestamp |
|
||||
|
||||
## 4. CREATE Mapping
|
||||
|
||||
### 4.1 Intended Create Flow
|
||||
|
||||
JobSource creation is indirect through Job and transcription workflows:
|
||||
1. Job create flow should create a JobSource row for each uploaded source page.
|
||||
2. Processing workflow may create missing JobSource rows when persisting transcription output.
|
||||
|
||||
| Field | Intended User Input | Required | Visible | Notes |
|
||||
|---|---|---|---|---|
|
||||
| job_id | None | Yes | No | Derived from active Job |
|
||||
| source_id | None | Yes | No | Derived from created/selected Source |
|
||||
| status | None | No | Indirectly | Defaults to pending at create |
|
||||
| raw_transcription | None | No | No at create | Filled after processing |
|
||||
| ai_metadata | None | No | No | Operational metadata |
|
||||
| raw_api_response | None | No | No | Operational payload |
|
||||
| error_detail | None | No | No at create | Filled on failure |
|
||||
| executed_at | None | No | No | System-generated |
|
||||
|
||||
### 4.2 Current Implementation
|
||||
|
||||
Current entry points:
|
||||
1. upload create path adds pending JobSource link in _create_upload_records().
|
||||
2. transcription update path creates or updates JobSource row during output persistence.
|
||||
|
||||
Current backend paths:
|
||||
1. src/transcription/services/store.py -> _create_upload_records()
|
||||
2. src/transcription/services/transcription.py -> update_job_transcription()
|
||||
|
||||
| Field | Current Value at Create/Update | Source | Visible to User | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| id | Generated UUID | System | No | src/transcription/db/models.py |
|
||||
| job_id | Caller or workflow derived | Service/workflow | Indirectly | store.py, transcription.py |
|
||||
| source_id | Caller or workflow derived | Service/workflow | Indirectly | store.py, transcription.py |
|
||||
| status | pending at create, transcribed or failed on update | Workflow logic | Partial | transcription.py |
|
||||
| raw_transcription | Set on successful transcription update | Workflow/provider result | Yes in review context | transcription.py, jobs UI |
|
||||
| ai_metadata | Available in model; not currently filled in update path | Workflow potential | No | models.py, transcription.py |
|
||||
| raw_api_response | Available in model; not currently filled in update path | Workflow potential | No | models.py, transcription.py |
|
||||
| error_detail | Set on failed transcription update | Workflow/provider error | Partial | transcription.py |
|
||||
| executed_at | Set at row creation and refreshed on updates | System/workflow | Partial | models.py, transcription.py |
|
||||
|
||||
### 4.3 Gap to Target
|
||||
|
||||
To satisfy intended supporting behavior, implementation must add:
|
||||
1. explicit per-source status display for all linked sources in Job detail.
|
||||
2. clear surfaced error_detail for failed source executions.
|
||||
3. optional diagnostics surface for ai_metadata/raw_api_response when needed.
|
||||
4. first-class multi-source create path from Job create flow.
|
||||
|
||||
## 5. READ Mapping
|
||||
|
||||
### 5.1 Intended Read Behavior
|
||||
|
||||
Users should see JobSource data indirectly in job detail and review workflows:
|
||||
1. per-source execution status.
|
||||
2. per-source raw transcription output.
|
||||
3. per-source failure details where applicable.
|
||||
4. execution timestamp context.
|
||||
|
||||
### 5.2 Current Implementation
|
||||
|
||||
Current read behavior is partial and job-detail-centric.
|
||||
|
||||
| Field | Current Rendering | Visible to User | Notes | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| status | Job-level status is visible; source-level status is limited | Partial | Source-level status not fully surfaced as a dedicated list | src/transcription/ui/pages/jobs_page.py |
|
||||
| raw_transcription | Original transcription card is visible | Yes | Primary source is shown in current detail flow | src/transcription/ui/components/transcript.py |
|
||||
| error_detail | Not prominently surfaced in current detail UI | Partial | Stored in JobSource rows during failures | src/transcription/services/transcription.py |
|
||||
| executed_at | Not first-class rendered | Partial | Available in model for future display | src/transcription/db/models.py |
|
||||
|
||||
Service read/query coverage:
|
||||
1. read_job_source() reads one row with source relation.
|
||||
2. list_job_sources() lists rows and supports job_id filtering.
|
||||
|
||||
### 5.3 Gap to Target
|
||||
|
||||
To satisfy intended read behavior, implementation must add:
|
||||
1. source-level execution table in Job detail.
|
||||
2. explicit failed-source messaging from error_detail.
|
||||
3. multi-source navigation in job review UI.
|
||||
|
||||
## 6. UPDATE Mapping
|
||||
|
||||
### 6.1 Intended Update Behavior
|
||||
|
||||
JobSource updates are workflow-managed, not directly user-edited.
|
||||
|
||||
Intended user-editable fields:
|
||||
- none in first-release behavior
|
||||
|
||||
Workflow-managed fields:
|
||||
- status
|
||||
- raw_transcription
|
||||
- error_detail
|
||||
- executed_at
|
||||
- optional diagnostics payload fields
|
||||
|
||||
### 6.2 Current Implementation
|
||||
|
||||
| Field | Updatable via UI | Updatable via Service/Workflow | Notes |
|
||||
|---|---|---|---|
|
||||
| status | No | Yes | Set by transcription update and job lifecycle handling |
|
||||
| raw_transcription | No | Yes | Persisted in update_job_transcription() |
|
||||
| error_detail | No | Yes | Persisted on transcription failure |
|
||||
| executed_at | No | Yes | Updated when existing JobSource rows are changed |
|
||||
| ai_metadata/raw_api_response | No | Potentially yes | Model supports them; active population is limited |
|
||||
|
||||
### 6.3 Gap to Target
|
||||
|
||||
Implementation should add:
|
||||
1. clearer job-detail visualization of per-source execution updates.
|
||||
2. optional operator diagnostics views for advanced troubleshooting.
|
||||
|
||||
## 7. DELETE Mapping
|
||||
|
||||
### 7.1 Intended Delete Behavior
|
||||
|
||||
JobSource deletion should be policy-driven and usually tied to Job/Source lifecycle operations.
|
||||
|
||||
Rules:
|
||||
1. direct user deletion is not required in first-release behavior.
|
||||
2. cleanup should occur through Job or Source deletion policies.
|
||||
|
||||
### 7.2 Current Implementation
|
||||
|
||||
| Action | UI Exposed | Backend Capability | Notes |
|
||||
|---|---|---|---|
|
||||
| Delete JobSource row | No | Yes | TranscriptionService.delete_job_source() exists |
|
||||
|
||||
### 7.3 Gap to Target
|
||||
|
||||
Implementation may add:
|
||||
1. maintenance tooling for cleanup operations.
|
||||
2. policy-aware cascade guidance in Job and Source delete flows.
|
||||
|
||||
## 8. Hidden and System-Managed Fields
|
||||
|
||||
| Field | Category | Why Hidden or Protected |
|
||||
|---|---|---|
|
||||
| id | System-managed | Internal identifier |
|
||||
| job_id | Context-managed | Derived from Job context |
|
||||
| source_id | Context-managed | Derived from Source context |
|
||||
| ai_metadata | Operational metadata | Advanced diagnostics payload |
|
||||
| raw_api_response | Operational metadata | Raw provider response payload |
|
||||
| executed_at | System-managed | Execution timestamp |
|
||||
|
||||
## 9. Traceability Anchors
|
||||
|
||||
Schema and models:
|
||||
- docs/schema_v2.md
|
||||
- src/transcription/db/models.py
|
||||
|
||||
Current implementation:
|
||||
- src/transcription/services/store.py
|
||||
- src/transcription/services/transcription.py
|
||||
- src/transcription/services/workflows.py
|
||||
- src/transcription/ui/pages/jobs_page.py
|
||||
- src/transcription/ui/components/transcript.py
|
||||
- tests/services/test_v2_crud.py
|
||||
|
||||
Related user-facing workflows:
|
||||
- docs/ui/entities/job/user-journey.md
|
||||
- docs/ui/entities/source/user-journey.md
|
||||
|
||||
## 10. Coverage Summary
|
||||
|
||||
- Every JobSource schema field appears in the field inventory.
|
||||
- Intended behavior is defined as supporting workflow behavior rather than standalone UI.
|
||||
- Current behavior reflects workflow/service-driven CRUD with partial job-detail visibility.
|
||||
- Gaps between intended and current behavior are explicit.
|
||||
@@ -0,0 +1,154 @@
|
||||
# Job Acceptance Criteria
|
||||
|
||||
Purpose: Define implementation-ready acceptance criteria for Job Create, Read, Update, and Delete workflows.
|
||||
|
||||
Companion documents:
|
||||
- docs/ui/entities/job/user-journey.md
|
||||
- docs/ui/entities/job/schema-mapping.md
|
||||
|
||||
## Scope
|
||||
|
||||
This checklist covers:
|
||||
1. Create flow
|
||||
2. Read flow
|
||||
3. Update flow
|
||||
4. Delete flow
|
||||
|
||||
This checklist does not cover:
|
||||
1. provider-specific transcription internals
|
||||
2. advanced workflow scheduling and queue orchestration controls
|
||||
3. multi-job bulk operations
|
||||
|
||||
## Create Acceptance Criteria
|
||||
|
||||
### CR-1 Job creation entry
|
||||
1. Given the user is on the Jobs page
|
||||
2. When the user selects Create job
|
||||
3. Then the user is taken to Job detail/create mode
|
||||
|
||||
### CR-2 Required create values
|
||||
1. document_id must be selected before submit
|
||||
2. at least one source file must be uploaded before submit
|
||||
3. each uploaded file creates a Source linked to the selected Document
|
||||
4. each created Source is linked to the new Job through JobSource
|
||||
|
||||
### CR-3 Source ordering behavior
|
||||
1. Given multi-file or folder upload
|
||||
2. When source records are created
|
||||
3. Then page ordering follows alphabetical order of original filenames
|
||||
4. Then helper text explains how filename conventions control ordering
|
||||
|
||||
### CR-4 Provider/model/prompt visibility
|
||||
1. provider, model, and prompt_name are visible in create flow when known
|
||||
2. provider, model, and prompt_name are visible in detail flow when known
|
||||
3. if values are unknown at create time, UI shows clear unknown or pending state without blocking submit
|
||||
|
||||
### CR-5 Successful create outcome
|
||||
1. Given valid inputs
|
||||
2. When the user submits create
|
||||
3. Then the Job record is created and linked to selected Document
|
||||
4. Then source and JobSource records are created for uploads
|
||||
5. Then job status is queued or processing based on execution timing
|
||||
6. Then the user is routed to Job detail mode
|
||||
|
||||
### CR-6 Create failure outcome
|
||||
1. Given create validation or persistence failure
|
||||
2. Then clear error feedback is shown
|
||||
3. Then no false success feedback is shown
|
||||
4. Then entered selections are preserved where possible
|
||||
5. Then retry path remains available
|
||||
|
||||
## Read Acceptance Criteria
|
||||
|
||||
### RD-1 Jobs list retrieval
|
||||
1. Given one or more jobs exist
|
||||
2. When the user opens the Jobs page
|
||||
3. Then all jobs are listed in a table or equivalent list surface
|
||||
|
||||
### RD-2 Jobs list fields
|
||||
1. Jobs list shows job id
|
||||
2. Jobs list shows status
|
||||
3. Jobs list shows created or updated timestamps
|
||||
4. Jobs list shows retry_count when available
|
||||
5. Jobs list provides navigation to Job detail for each row
|
||||
|
||||
### RD-3 Job detail retrieval
|
||||
1. Given a valid job id
|
||||
2. When the user opens Job detail
|
||||
3. Then job metadata for that record only is shown
|
||||
4. Then document-scoped navigation links for Sources and Jobs are shown
|
||||
|
||||
### RD-4 Detail execution context visibility
|
||||
1. provider, model, and prompt_name are displayed when known
|
||||
2. status lifecycle value is visible
|
||||
3. source-level transcription and revision context is available through Source detail navigation from Job detail
|
||||
|
||||
### RD-5 Missing and invalid id states
|
||||
1. Given an invalid job id format
|
||||
2. Then UI shows invalid job id state without crashing
|
||||
3. Given a valid but nonexistent job id
|
||||
4. Then UI shows job not found state without crashing
|
||||
|
||||
## Update Acceptance Criteria
|
||||
|
||||
### UP-1 Revision edit entry
|
||||
1. Given a job detail page
|
||||
2. When the user opens the page
|
||||
3. Then navigation links to job-scoped Sources are available
|
||||
4. Then source rows can open Source detail revision workflow
|
||||
|
||||
### UP-2 Revision validation
|
||||
1. revision save blocks empty trimmed text and shows warning feedback
|
||||
|
||||
### UP-3 Successful revision save
|
||||
1. Source detail save persists revised text and shows success feedback
|
||||
|
||||
### UP-4 Revision save failure
|
||||
1. Source detail save failure shows clear error feedback with retry path
|
||||
|
||||
### UP-5 Job lifecycle state update visibility
|
||||
1. status changes from queued to processing to terminal states are reflected in UI
|
||||
2. retry_count updates are reflected when retry logic runs
|
||||
3. users cannot directly edit lifecycle state fields in first release
|
||||
|
||||
## Delete Acceptance Criteria
|
||||
|
||||
### DL-1 Delete entry and confirmation
|
||||
1. Given a job detail context
|
||||
2. When the user opens job delete page
|
||||
3. Then a permanent-action confirmation is shown for non-processing jobs
|
||||
|
||||
### DL-2 Dependency guardrails
|
||||
1. Delete is blocked while job status is processing
|
||||
2. Related JobSource links are removed as part of allowed delete flow
|
||||
|
||||
### DL-3 Blocked delete behavior
|
||||
1. When blocked, the UI shows clear processing-state guidance
|
||||
2. The user is offered navigation back to job or jobs list
|
||||
|
||||
### DL-4 Successful delete
|
||||
1. Given an allowed delete
|
||||
2. When the user confirms delete
|
||||
3. Then the job is removed and success feedback is shown
|
||||
4. Then the user is returned to Jobs list
|
||||
|
||||
### DL-5 Delete failure
|
||||
1. Given backend failure during delete
|
||||
2. Then clear error feedback is shown
|
||||
3. Then the user remains in delete context with retry path
|
||||
|
||||
## Cross-Criteria Quality Gates
|
||||
|
||||
### QG-1 Separation of intent and implementation
|
||||
1. UX intent remains in user-journey.md
|
||||
2. Current versus target implementation mapping remains in schema-mapping.md
|
||||
|
||||
### QG-2 Traceability
|
||||
1. Each accepted behavior maps to at least one UI action or service path
|
||||
2. No acceptance criterion contradicts first-release deferred items
|
||||
|
||||
### QG-3 First-release constraints
|
||||
1. Jobs page remains list-all with explicit Create job action
|
||||
2. Job create requires Document selection and source upload
|
||||
3. provider/model/prompt_name are visible to users when known
|
||||
4. manual retry controls may remain deferred while status visibility is required
|
||||
@@ -0,0 +1,233 @@
|
||||
# Job Schema-to-UI Mapping
|
||||
|
||||
Purpose: Map the Job schema to the UI, while clearly separating intended target behavior from current implementation.
|
||||
|
||||
Companion document: user-journey.md
|
||||
Acceptance criteria: acceptance-criteria.md
|
||||
|
||||
## 1. Entity Snapshot
|
||||
|
||||
- Table: Job
|
||||
- Primary key: id (UUID)
|
||||
- Related entities: Document, JobSource, Source
|
||||
- Canonical schema references:
|
||||
- src/transcription/db/models.py
|
||||
- docs/schema_v2.md
|
||||
|
||||
## 2. Mapping Rules
|
||||
|
||||
This document uses three lenses:
|
||||
1. Intended behavior: what the UX should support.
|
||||
2. Current behavior: what the code supports today.
|
||||
3. Gap to target: what must change to align implementation with the intended UX.
|
||||
|
||||
## 3. Field Inventory
|
||||
|
||||
| Field | DB Type | Nullable | Default/Auto Value | Intended UI Treatment | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| id | UUID | No | uuid4() | Shown read-only in list and detail | Primary key |
|
||||
| document_id | UUID FK | No | None | Required create input via Document selection | Job belongs to one Document |
|
||||
| status | enum JobStatus | No | queued | Shown read-only as lifecycle state | System-managed transitions |
|
||||
| retry_count | int | No | 0 | Shown read-only | Operational counter |
|
||||
| date_created | datetime | No | datetime.now(UTC) | Shown read-only | System-managed timestamp |
|
||||
| date_updated | datetime | No | datetime.now(UTC) | Shown read-only | System-managed timestamp |
|
||||
| provider | str | Yes | None | Visible when known; editable if create-time options are available | Processing metadata |
|
||||
| model | str | Yes | None | Visible when known; editable if create-time options are available | Processing metadata |
|
||||
| prompt_name | str | Yes | None | Visible when known; editable if create-time options are available | Prompt metadata |
|
||||
|
||||
Related execution fields rendered in Job detail via relationships:
|
||||
- Job detail renders metadata and document links; source-level review/editing is reached through job-scoped Sources routes.
|
||||
|
||||
## 4. CREATE Mapping
|
||||
|
||||
### 4.1 Intended Create Flow
|
||||
|
||||
Entry point: Jobs page Create job action
|
||||
User action: open create mode, select Document, upload one or more source files or a folder, submit for transcription
|
||||
Success destination: Job detail page in detail mode
|
||||
|
||||
| Field | Intended User Input | Required | Visible | Notes |
|
||||
|---|---|---|---|---|
|
||||
| document_id | Select/search | Yes | Yes | Required create selection |
|
||||
| status | None | No | Yes (read-only) | Starts at queued and changes by workflow |
|
||||
| retry_count | None | No | Yes (read-only) | Starts at 0 |
|
||||
| date_created | None | No | Yes (read-only) | System-generated |
|
||||
| date_updated | None | No | Yes (read-only) | System-generated |
|
||||
| provider | Display or select | No | Yes | Visible when known during create and detail |
|
||||
| model | Display or select | No | Yes | Visible when known during create and detail |
|
||||
| prompt_name | Display or select | No | Yes | Visible when known during create and detail |
|
||||
|
||||
Create-related relationship rules:
|
||||
1. source file upload is required for create.
|
||||
2. each uploaded file creates a Source linked to the selected Document.
|
||||
3. each created Source must be linked to the new Job through JobSource.
|
||||
4. processing order for multi-file and folder uploads is alphabetical by original filename.
|
||||
|
||||
### 4.2 Current Implementation
|
||||
|
||||
Current entry point: Jobs page create flow
|
||||
Current user action: select Document and upload one or more files or a folder through a single upload widget
|
||||
Current backend path: job create submit -> create_job_for_document()
|
||||
|
||||
| Field | Current Value at Create | Source | Visible to User | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| id | Generated UUID | System | Yes on jobs list/detail | src/transcription/ui/pages/jobs_page.py |
|
||||
| document_id | Selected existing Document id | User selection + service write | Indirectly | src/transcription/ui/pages/jobs_page.py, src/transcription/services/store.py |
|
||||
| status | queued | Service/model default | Yes | src/transcription/services/store.py, src/transcription/db/models.py |
|
||||
| retry_count | 0 | Model default | Yes | src/transcription/db/models.py, src/transcription/ui/pages/jobs_page.py |
|
||||
| date_created | current UTC timestamp | System | Yes | src/transcription/db/models.py, src/transcription/ui/pages/jobs_page.py |
|
||||
| date_updated | current UTC timestamp | System | Yes | src/transcription/db/models.py, src/transcription/ui/pages/jobs_page.py |
|
||||
| provider | None at create, set after transcription update | Workflow/service | Yes | src/transcription/services/workflows.py |
|
||||
| model | None at create, set after transcription update | Workflow/service | Yes | src/transcription/services/workflows.py |
|
||||
| prompt_name | None at create, set by workflow updates | Workflow/service | Yes | src/transcription/services/workflows.py |
|
||||
|
||||
Current create constraints:
|
||||
1. dedicated Create job action exists in the Jobs page.
|
||||
2. job create flow requires a Document selection.
|
||||
3. current upload path accepts one widget for files or folder selection.
|
||||
|
||||
### 4.3 Gap to Target
|
||||
|
||||
To satisfy intended Create flow, implementation must add:
|
||||
1. Jobs list Create job action that opens Job detail/create mode.
|
||||
2. explicit Document selection and source upload controls in create mode.
|
||||
3. multi-file and folder upload support in create mode.
|
||||
4. deterministic alphabetical page ordering and user guidance.
|
||||
5. explicit visibility of provider, model, and prompt_name in create/detail when known.
|
||||
|
||||
## 5. READ Mapping
|
||||
|
||||
### 5.1 Intended Read Behavior
|
||||
|
||||
On Job list/detail surfaces, users should be able to see:
|
||||
1. all jobs in one list.
|
||||
2. status and timeline context.
|
||||
3. selected Document context.
|
||||
4. source-level processing and transcription results.
|
||||
5. provider/model/prompt_name when known.
|
||||
|
||||
### 5.2 Current Implementation
|
||||
|
||||
Current read behavior exists in jobs list and jobs detail routes.
|
||||
|
||||
| Field | Current Rendering | Visible to User | Notes | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| id | Jobs list row and detail header | Yes | Primary visible identifier | src/transcription/ui/pages/jobs_page.py |
|
||||
| status | Jobs list and detail | Yes | Chip styling for transcribed; text for others | src/transcription/ui/pages/jobs_page.py |
|
||||
| retry_count | Jobs list table | Yes | Included in row model | src/transcription/ui/components/table/jobs.py |
|
||||
| date_created | Jobs list table | Yes | Included in row model | src/transcription/ui/components/table/jobs.py |
|
||||
| date_updated | Jobs list table | Yes | Included in row model | src/transcription/ui/components/table/jobs.py |
|
||||
| document_id | Not rendered directly as labeled field | Partial | Document context exists by relationship but limited direct display | src/transcription/ui/pages/jobs_page.py |
|
||||
| provider/model/prompt_name | Rendered as labeled fields in Job detail | Yes | Shows pending fallback when unset | src/transcription/ui/pages/jobs_page.py |
|
||||
|
||||
Source-related read behavior:
|
||||
1. Job detail exposes Sources navigation for current job context.
|
||||
2. Source preview, transcription context, and revision editor are rendered in Source detail.
|
||||
3. invalid or missing job ids show explicit UI states.
|
||||
|
||||
### 5.3 Gap to Target
|
||||
|
||||
To satisfy intended Read flow, implementation must add:
|
||||
1. optional in-page source summaries in Job detail if future UX requires fewer navigation steps.
|
||||
2. richer filtering/search UX if needed.
|
||||
|
||||
## 6. UPDATE Mapping
|
||||
|
||||
### 6.1 Intended Update Behavior
|
||||
|
||||
Primary user updates in first release are source revision edits in Source detail reached from Job detail.
|
||||
|
||||
Intended editable scope (first release):
|
||||
- Source.revised_text through Source detail review
|
||||
|
||||
Intended read-only Job fields in first release:
|
||||
- id
|
||||
- document_id after create
|
||||
- status
|
||||
- retry_count
|
||||
- date_created
|
||||
- date_updated
|
||||
|
||||
Job metadata visibility policy:
|
||||
- provider, model, and prompt_name should be visible when known.
|
||||
- create-time editing of provider/model/prompt_name is optional and depends on available options.
|
||||
|
||||
### 6.2 Current Implementation
|
||||
|
||||
| Field/Area | Updatable via UI | Updatable via Service | Notes |
|
||||
|---|---|---|---|
|
||||
| Source.revised_text from Source detail | Yes | Yes | Saved via transcription service revision path from Sources page detail route |
|
||||
| status | No | Yes | Updated by workflow lifecycle services |
|
||||
| retry_count | No | Yes | Incremented by workflow retry logic |
|
||||
| provider/model/prompt_name | No | Yes | Set during transcription result finalization |
|
||||
| document_id | No | Technically via model/service update | Treated as fixed post-create in intended UX |
|
||||
|
||||
### 6.3 Gap to Target
|
||||
|
||||
Implementation now includes:
|
||||
1. create-mode handling for provider/model/prompt visibility and optional selection.
|
||||
2. detail display for provider/model/prompt and document-scoped navigation links.
|
||||
3. source revision workflow through job-scoped Sources and Source detail pages.
|
||||
4. manual controls for retry and state transitions remain deferred.
|
||||
|
||||
## 7. DELETE Mapping
|
||||
|
||||
### 7.1 Intended Delete Behavior
|
||||
|
||||
Job deletion is implemented as a dedicated delete route with processing-state guardrails.
|
||||
|
||||
Rules:
|
||||
1. deletion is allowed only when policy allows cleanup or retention handling for related JobSource records.
|
||||
2. blocked deletion must explain constraints and required cleanup path.
|
||||
3. successful deletion requires confirmation and returns user to Jobs list.
|
||||
|
||||
### 7.2 Current Implementation
|
||||
|
||||
| Action | UI Exposed | Backend Capability | Notes |
|
||||
|---|---|---|---|
|
||||
| Delete Job | Yes | Yes | Job delete page confirms permanent action and blocks when processing |
|
||||
|
||||
### 7.3 Gap to Target
|
||||
|
||||
Implementation may add in a future revision:
|
||||
1. inline delete entry in Job detail header.
|
||||
2. richer dependency messaging beyond processing-state guardrail.
|
||||
|
||||
## 8. Hidden and System-Managed Fields
|
||||
|
||||
| Field | Category | Why Hidden or Protected |
|
||||
|---|---|---|
|
||||
| status | System-managed lifecycle | Managed by worker lifecycle transitions |
|
||||
| retry_count | System-managed operational state | Reflects retry behavior, not direct user input |
|
||||
| date_created | System-managed | Audit timestamp |
|
||||
| date_updated | System-managed | Audit timestamp |
|
||||
|
||||
## 9. Traceability Anchors
|
||||
|
||||
Schema and models:
|
||||
- docs/schema_v2.md
|
||||
- src/transcription/db/models.py
|
||||
|
||||
Current implementation:
|
||||
- src/transcription/ui/pages/jobs_page.py
|
||||
- src/transcription/ui/components/table/jobs.py
|
||||
- src/transcription/ui/pages/sources_page.py
|
||||
- src/transcription/services/jobs.py
|
||||
- src/transcription/services/workflows.py
|
||||
- src/transcription/services/store.py
|
||||
- src/transcription/services/transcription.py
|
||||
|
||||
Companion UX spec:
|
||||
- docs/ui/entities/job/user-journey.md
|
||||
|
||||
Acceptance checklist:
|
||||
- docs/ui/entities/job/acceptance-criteria.md
|
||||
|
||||
## 10. Acceptance Checklist Summary
|
||||
|
||||
- Every Job schema field appears in the field inventory.
|
||||
- Intended Create behavior matches the companion user journey.
|
||||
- Current behavior reflects explicit jobs creation plus source review/editing through dedicated Sources routes.
|
||||
- Provider/model/prompt visibility intent is explicit for create and detail views.
|
||||
- Gaps between intended and current behavior are explicit.
|
||||
- Read, Update, and Delete sections distinguish target behavior from current code.
|
||||
@@ -0,0 +1,291 @@
|
||||
# Job User Journey
|
||||
|
||||
Purpose: Define how a user should interact with the UI to create and manage a Job record, including document linking, source uploads, processing status, and page-level review.
|
||||
|
||||
Scope: This document describes intended user interaction for the Job UI. It is the UX contract for the Job entity.
|
||||
|
||||
Companion schema mapping: schema-mapping.md
|
||||
Companion acceptance criteria: acceptance-criteria.md
|
||||
|
||||
## 1. Overview
|
||||
|
||||
A Job represents one transcription run for a selected Document and one or more uploaded source files.
|
||||
|
||||
Managing a Job is run-first:
|
||||
1. The user opens the Jobs page.
|
||||
2. The user selects Create job.
|
||||
3. The user lands on a Job detail/create surface.
|
||||
4. The user links a Document and uploads one or more source files.
|
||||
5. The user submits for transcription.
|
||||
6. The system creates and processes the Job.
|
||||
7. The user reviews job metadata and follows document-scoped links for Sources and Jobs.
|
||||
|
||||
## 2. User Goal
|
||||
|
||||
The user wants to:
|
||||
1. see all jobs in one place
|
||||
2. create a new transcription run intentionally
|
||||
3. attach the run to the correct Document
|
||||
4. upload source file(s) for that run
|
||||
5. submit and monitor processing state
|
||||
6. review and revise page-level outputs
|
||||
|
||||
## 3. Page Model
|
||||
|
||||
### 3.1 Jobs List Page
|
||||
|
||||
The Jobs page is the primary UI surface where users manage jobs.
|
||||
|
||||
It should support:
|
||||
1. listing all jobs
|
||||
2. searching or filtering jobs
|
||||
3. opening job detail for any row
|
||||
4. starting Create job
|
||||
5. clear empty state when no jobs exist
|
||||
|
||||
### 3.2 Job Detail/Create Page
|
||||
|
||||
The Job detail/create page is used for both creating a new Job and viewing an existing Job.
|
||||
|
||||
Create mode should include:
|
||||
1. document selection
|
||||
2. source upload controls
|
||||
3. submit for transcription action
|
||||
|
||||
Detail mode should include:
|
||||
1. job metadata and status
|
||||
2. document-scoped navigation links for the current Document
|
||||
3. provider/model/prompt visibility when known
|
||||
4. no delete action in first release
|
||||
|
||||
## 4. Entry Points
|
||||
|
||||
Primary entry points:
|
||||
1. from Jobs page, Create job
|
||||
2. from Jobs page row selection, open existing Job detail
|
||||
|
||||
Current implementation note:
|
||||
1. current code path uses explicit /jobs/new creation
|
||||
2. intended UX is explicit Create job from the Jobs page
|
||||
3. current detail view is link-oriented and routes source review/editing through dedicated Source detail
|
||||
|
||||
## 5. Create Job Flow
|
||||
|
||||
### 5.1 User Intent
|
||||
|
||||
The user wants to start a transcription run by selecting the right Document and providing source files in one guided flow.
|
||||
|
||||
### 5.2 Create Entry
|
||||
|
||||
1. The user opens the Jobs page
|
||||
2. The user selects Create job
|
||||
3. The system opens Job detail/create page in create mode
|
||||
|
||||
### 5.3 Create Inputs
|
||||
|
||||
| UI Label | Schema Area | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Document | Job.document_id | Select/search | Yes | Links the run to one Document |
|
||||
| Source files | Source upload fields | Multi-file upload or folder upload | Yes | User may select one file, many files, or a folder |
|
||||
| Processing order | Source.page_number assignment rule | System rule | Yes | If multiple files are uploaded, order is alphabetical by original filename |
|
||||
| Provider | Job.provider | Display or select | No | Visible to user when known; selectable when options are available |
|
||||
| Model | Job.model | Display or select | No | Visible to user when known; selectable when options are available |
|
||||
| Prompt | Job.prompt_name | Display or select | No | Visible to user when known; selectable when options are available |
|
||||
|
||||
### 5.4 Source Handling Rules
|
||||
|
||||
1. Each uploaded file becomes a Source linked to the selected Document
|
||||
2. Each created Source is linked to the Job through JobSource
|
||||
3. Multi-file or folder uploads are processed alphabetically by original filename
|
||||
4. upload_name stores the original filename
|
||||
5. stored filename uses UUID plus original extension in the form UUID.extension
|
||||
|
||||
Suggested helper text:
|
||||
1. Files are processed alphabetically by original filename. Use leading numbers such as 001, 002, 003 to control page order.
|
||||
|
||||
### 5.5 Validation Rules
|
||||
|
||||
Create submission must be blocked when:
|
||||
1. no Document is selected
|
||||
2. no source file is uploaded
|
||||
|
||||
Create submission should provide clear feedback when:
|
||||
1. uploaded files are invalid or unreadable
|
||||
2. persistence fails for Job, Source, or JobSource linkage
|
||||
|
||||
### 5.6 Submission Behavior
|
||||
|
||||
On submit:
|
||||
1. validate create inputs
|
||||
2. create Job record linked to selected Document
|
||||
3. create Source records for uploaded files
|
||||
4. create JobSource links for each Source in the Job
|
||||
5. queue processing for transcription
|
||||
6. route user to Job detail mode
|
||||
|
||||
Recommended transactional behavior:
|
||||
1. intended create writes should succeed or fail together
|
||||
2. The user should not receive false success when required records fail
|
||||
|
||||
### 5.7 Create Success Result
|
||||
|
||||
After successful create:
|
||||
1. job appears in Jobs list
|
||||
2. job detail shows selected Document and created source set
|
||||
3. status appears as queued or processing based on execution timing
|
||||
4. The user can monitor progress and open page-level review
|
||||
|
||||
### 5.8 Create Failure Result
|
||||
|
||||
If create fails:
|
||||
1. Show clear error message
|
||||
2. preserve entered selections where possible
|
||||
3. keep retry path available
|
||||
4. do not show false success feedback
|
||||
|
||||
## 6. Read Job Journey
|
||||
|
||||
### 6.1 User Intent
|
||||
|
||||
The user wants to quickly understand what the job is, its current status, and which source pages need review.
|
||||
|
||||
### 6.2 Jobs List Expectations
|
||||
|
||||
The Jobs list should show, at minimum:
|
||||
1. job identifier
|
||||
2. document context
|
||||
3. current status
|
||||
4. creation or update timestamp
|
||||
5. quick action to open detail
|
||||
|
||||
Optional first-release columns if available:
|
||||
1. retry count
|
||||
2. provider/model summary
|
||||
|
||||
### 6.3 Job Detail Expectations
|
||||
|
||||
The Job detail should show:
|
||||
1. job status and summary metadata
|
||||
2. selected Document context
|
||||
3. document-scoped and job-scoped navigation links
|
||||
4. source review entry through job-scoped Sources list
|
||||
|
||||
Source detail should show:
|
||||
1. source metadata and preview
|
||||
2. original transcription output per source
|
||||
3. revision editor and latest revised content
|
||||
|
||||
### 6.4 Read Empty and Missing States
|
||||
|
||||
If no jobs exist:
|
||||
1. list shows no jobs yet empty state
|
||||
2. list shows Create job action
|
||||
|
||||
If a job id is invalid or missing:
|
||||
1. Show clear not found state
|
||||
2. do not crash the page
|
||||
|
||||
If a job has no source items due to failure:
|
||||
1. Show clear warning state
|
||||
2. keep recovery guidance visible
|
||||
|
||||
## 7. Job Status Lifecycle UX
|
||||
|
||||
### 7.1 Status Values
|
||||
|
||||
The UI should map to model-backed job states:
|
||||
1. queued
|
||||
2. processing
|
||||
3. transcribed
|
||||
4. completed
|
||||
5. partial_success
|
||||
6. failed
|
||||
|
||||
### 7.2 In-Progress States
|
||||
|
||||
When status is queued or processing:
|
||||
1. Show active progress state
|
||||
2. keep detail page refresh-safe
|
||||
3. indicate that source-level results may still be arriving
|
||||
|
||||
### 7.3 Terminal States
|
||||
|
||||
When status is completed:
|
||||
1. Show completion success state
|
||||
2. direct user to revision workflow
|
||||
|
||||
When status is partial_success:
|
||||
1. Show mixed outcome state
|
||||
2. identify failed pages
|
||||
3. guide user to review available successful pages and retry strategy
|
||||
|
||||
When status is failed:
|
||||
1. Show failure state with actionable message
|
||||
2. keep navigation and retry guidance available
|
||||
|
||||
## 8. Update Job Journey
|
||||
|
||||
### 8.1 User Intent
|
||||
|
||||
The user primarily updates job-related review outcomes by editing revised transcription text per source page.
|
||||
|
||||
### 8.2 First-Release Editable Scope
|
||||
|
||||
Editable in first release:
|
||||
1. source-level revised_text through Source detail reached from job-scoped Sources navigation
|
||||
|
||||
Read-only in first release:
|
||||
1. Job.document_id after create
|
||||
2. job status values managed by processing workflow
|
||||
3. provider/model/prompt values may be system-managed, but should remain visible in UI when known
|
||||
|
||||
### 8.3 Update Save Behavior
|
||||
|
||||
On revision save:
|
||||
1. validate revised text
|
||||
2. persist revised text for selected source
|
||||
3. update revised timestamp fields by system policy
|
||||
4. show success feedback
|
||||
|
||||
On save failure:
|
||||
1. Show clear error feedback
|
||||
2. preserve entered text where possible
|
||||
3. Allow retry
|
||||
|
||||
## 9. Delete and Retention Policy
|
||||
|
||||
### 9.1 User Intent
|
||||
|
||||
The user may need to remove invalid or duplicate jobs safely.
|
||||
|
||||
### 9.2 First-Release Policy
|
||||
|
||||
Delete behavior uses explicit guardrails:
|
||||
1. deletion is blocked while status is processing
|
||||
2. blocked delete explains constraints and offers back navigation
|
||||
3. allowed delete requires explicit confirmation and then returns to Jobs list with success feedback
|
||||
|
||||
## 10. Relationship to Other Workflows
|
||||
|
||||
Job workflow integrates with:
|
||||
1. Document workflow for ownership context
|
||||
2. Source workflow for uploaded page records and ordering
|
||||
3. Revision workflow for human correction lifecycle
|
||||
4. Worker processing workflow for queued execution and status transitions
|
||||
|
||||
## 11. Relationship to Schema Mapping
|
||||
|
||||
The companion schema-mapping document should specify:
|
||||
1. field visibility per CRUD action
|
||||
2. current implementation status
|
||||
3. intended behavior
|
||||
4. gap-to-target items
|
||||
|
||||
## 12. Deferred Items
|
||||
|
||||
Deferred to future revisions:
|
||||
1. manual retry controls from job detail
|
||||
2. advanced provider/model/prompt policy controls beyond basic create-time visibility
|
||||
3. advanced bulk actions across multiple jobs
|
||||
4. live streaming progress updates beyond refresh-based updates
|
||||
5. job templates or preset configurations
|
||||
@@ -0,0 +1,154 @@
|
||||
# Job Acceptance Criteria
|
||||
|
||||
Purpose: Define implementation-ready acceptance criteria for Job Create, Read, Update, and Delete workflows.
|
||||
|
||||
Companion documents:
|
||||
- docs/ui/entities/job/user-journey.md
|
||||
- docs/ui/entities/job/schema-mapping.md
|
||||
|
||||
## Scope
|
||||
|
||||
This checklist covers:
|
||||
1. Create flow
|
||||
2. Read flow
|
||||
3. Update flow
|
||||
4. Delete flow
|
||||
|
||||
This checklist does not cover:
|
||||
1. provider-specific transcription internals
|
||||
2. advanced workflow scheduling and queue orchestration controls
|
||||
3. multi-job bulk operations
|
||||
|
||||
## Create Acceptance Criteria
|
||||
|
||||
### CR-1 Job creation entry
|
||||
1. Given the user is on the Jobs page
|
||||
2. When the user selects Create job
|
||||
3. Then the user is taken to Job detail/create mode
|
||||
|
||||
### CR-2 Required create values
|
||||
1. document_id must be selected before submit
|
||||
2. at least one source file must be uploaded before submit
|
||||
3. each uploaded file creates a Source linked to the selected Document
|
||||
4. each created Source is linked to the new Job through JobSource
|
||||
|
||||
### CR-3 Source ordering behavior
|
||||
1. Given multi-file or folder upload
|
||||
2. When source records are created
|
||||
3. Then page ordering follows alphabetical order of original filenames
|
||||
4. Then helper text explains how filename conventions control ordering
|
||||
|
||||
### CR-4 Provider/model/prompt visibility
|
||||
1. provider, model, and prompt_name are visible in create flow when known
|
||||
2. provider, model, and prompt_name are visible in detail flow when known
|
||||
3. if values are unknown at create time, UI shows clear unknown or pending state without blocking submit
|
||||
|
||||
### CR-5 Successful create outcome
|
||||
1. Given valid inputs
|
||||
2. When the user submits create
|
||||
3. Then the Job record is created and linked to selected Document
|
||||
4. Then source and JobSource records are created for uploads
|
||||
5. Then job status is queued or processing based on execution timing
|
||||
6. Then the user is routed to Job detail mode
|
||||
|
||||
### CR-6 Create failure outcome
|
||||
1. Given create validation or persistence failure
|
||||
2. Then clear error feedback is shown
|
||||
3. Then no false success feedback is shown
|
||||
4. Then entered selections are preserved where possible
|
||||
5. Then retry path remains available
|
||||
|
||||
## Read Acceptance Criteria
|
||||
|
||||
### RD-1 Jobs list retrieval
|
||||
1. Given one or more jobs exist
|
||||
2. When the user opens the Jobs page
|
||||
3. Then all jobs are listed in a table or equivalent list surface
|
||||
|
||||
### RD-2 Jobs list fields
|
||||
1. Jobs list shows job id
|
||||
2. Jobs list shows status
|
||||
3. Jobs list shows created or updated timestamps
|
||||
4. Jobs list shows retry_count when available
|
||||
5. Jobs list provides navigation to Job detail for each row
|
||||
|
||||
### RD-3 Job detail retrieval
|
||||
1. Given a valid job id
|
||||
2. When the user opens Job detail
|
||||
3. Then job metadata for that record only is shown
|
||||
4. Then document-scoped navigation links for Sources and Jobs are shown
|
||||
|
||||
### RD-4 Detail execution context visibility
|
||||
1. provider, model, and prompt_name are displayed when known
|
||||
2. status lifecycle value is visible
|
||||
3. source-level transcription and revision context is available through Source detail navigation from Job detail
|
||||
|
||||
### RD-5 Missing and invalid id states
|
||||
1. Given an invalid job id format
|
||||
2. Then UI shows invalid job id state without crashing
|
||||
3. Given a valid but nonexistent job id
|
||||
4. Then UI shows job not found state without crashing
|
||||
|
||||
## Update Acceptance Criteria
|
||||
|
||||
### UP-1 Revision edit entry
|
||||
1. Given a job detail page
|
||||
2. When the user opens the page
|
||||
3. Then navigation links to job-scoped Sources are available
|
||||
4. Then source rows can open Source detail revision workflow
|
||||
|
||||
### UP-2 Revision validation
|
||||
1. revision save blocks empty trimmed text and shows warning feedback
|
||||
|
||||
### UP-3 Successful revision save
|
||||
1. Source detail save persists revised text and shows success feedback
|
||||
|
||||
### UP-4 Revision save failure
|
||||
1. Source detail save failure shows clear error feedback with retry path
|
||||
|
||||
### UP-5 Job lifecycle state update visibility
|
||||
1. status changes from queued to processing to terminal states are reflected in UI
|
||||
2. retry_count updates are reflected when retry logic runs
|
||||
3. users cannot directly edit lifecycle state fields in first release
|
||||
|
||||
## Delete Acceptance Criteria
|
||||
|
||||
### DL-1 Delete entry and confirmation
|
||||
1. Given a job detail context
|
||||
2. When the user opens job delete page
|
||||
3. Then a permanent-action confirmation is shown for non-processing jobs
|
||||
|
||||
### DL-2 Dependency guardrails
|
||||
1. Delete is blocked while job status is processing
|
||||
2. Related JobSource links are removed as part of allowed delete flow
|
||||
|
||||
### DL-3 Blocked delete behavior
|
||||
1. When blocked, the UI shows clear processing-state guidance
|
||||
2. The user is offered navigation back to job or jobs list
|
||||
|
||||
### DL-4 Successful delete
|
||||
1. Given an allowed delete
|
||||
2. When the user confirms delete
|
||||
3. Then the job is removed and success feedback is shown
|
||||
4. Then the user is returned to Jobs list
|
||||
|
||||
### DL-5 Delete failure
|
||||
1. Given backend failure during delete
|
||||
2. Then clear error feedback is shown
|
||||
3. Then the user remains in delete context with retry path
|
||||
|
||||
## Cross-Criteria Quality Gates
|
||||
|
||||
### QG-1 Separation of intent and implementation
|
||||
1. UX intent remains in user-journey.md
|
||||
2. Current versus target implementation mapping remains in schema-mapping.md
|
||||
|
||||
### QG-2 Traceability
|
||||
1. Each accepted behavior maps to at least one UI action or service path
|
||||
2. No acceptance criterion contradicts first-release deferred items
|
||||
|
||||
### QG-3 First-release constraints
|
||||
1. Jobs page remains list-all with explicit Create job action
|
||||
2. Job create requires Document selection and source upload
|
||||
3. provider/model/prompt_name are visible to users when known
|
||||
4. manual retry controls may remain deferred while status visibility is required
|
||||
@@ -0,0 +1,147 @@
|
||||
# Person Acceptance Criteria
|
||||
|
||||
Purpose: Define implementation-ready acceptance criteria for Person Create, Read, Update, and Delete workflows.
|
||||
|
||||
Companion documents:
|
||||
- docs/ui/entities/person/user-journey.md
|
||||
- docs/ui/entities/person/schema-mapping.md
|
||||
|
||||
## Scope
|
||||
|
||||
This checklist covers:
|
||||
1. Create flow
|
||||
2. Read flow
|
||||
3. Update flow
|
||||
4. Delete flow
|
||||
|
||||
This checklist does not cover:
|
||||
1. advanced metadata_ editing UX
|
||||
2. structured-name schema migration implementation
|
||||
3. bulk merge or dedup workflow design
|
||||
|
||||
## Create Acceptance Criteria
|
||||
|
||||
### CR-1 Person creation entry
|
||||
1. Given a Person page
|
||||
2. When the user selects Create new person
|
||||
3. Then the user can open a Person create form
|
||||
|
||||
### CR-2 Required field validation
|
||||
1. full_name is required
|
||||
2. Save is blocked when full_name is empty
|
||||
3. Inline feedback is shown for required-field errors
|
||||
|
||||
### CR-3 Optional field handling
|
||||
1. Optional fields may be blank without blocking create
|
||||
2. Date raw and exact fields can coexist
|
||||
3. Exact date remains canonical when both exact and raw are provided
|
||||
4. Portrait uploads persist under uploads/portraits/person and store a relative portrait_path
|
||||
|
||||
### CR-4 Successful create outcome
|
||||
1. Given valid input
|
||||
2. When the user saves
|
||||
3. Then the Person record is created
|
||||
4. Then success feedback is shown
|
||||
5. Then the user is routed to Person detail page
|
||||
|
||||
### CR-5 Create failure outcome
|
||||
1. Given backend failure during create
|
||||
2. Then clear error feedback is shown
|
||||
3. Then entered values are retained where possible
|
||||
4. Then no false success feedback is shown
|
||||
|
||||
## Read Acceptance Criteria
|
||||
|
||||
### RD-1 Person detail retrieval
|
||||
1. Given a valid Person id
|
||||
2. When the user opens the Person detail page
|
||||
3. Then the system displays Person metadata for that record only
|
||||
|
||||
### RD-2 Metadata visibility
|
||||
1. The page shows full_name and available optional person fields
|
||||
2. created_at and updated_at are shown as system-managed, read-only values
|
||||
3. portrait_path is rendered when available, including an image preview when possible
|
||||
4. relative portrait_path values resolve through /uploads for image rendering
|
||||
|
||||
### RD-3 Linked documents section
|
||||
1. Given no linked DocumentPerson rows
|
||||
2. Then the page shows a no linked documents yet empty state
|
||||
3. Given linked documents exist
|
||||
4. Then the page shows linked document entries
|
||||
|
||||
### RD-4 Read failure state
|
||||
1. Given a nonexistent Person id
|
||||
2. Then the UI shows a clear not found state without crashing
|
||||
|
||||
## Update Acceptance Criteria
|
||||
|
||||
### UP-1 Edit entry
|
||||
1. Given a loaded Person detail page
|
||||
2. When the user selects Edit person
|
||||
3. Then editable controls are shown for allowed fields only
|
||||
|
||||
### UP-2 Editable fields
|
||||
1. Editable: full_name, display_name, maiden_name, birth/death fields, places, biography, portrait_path
|
||||
2. Not editable: id, created_at, updated_at
|
||||
3. metadata_ remains hidden in first release
|
||||
|
||||
### UP-3 Required validation
|
||||
1. full_name remains required
|
||||
2. Save is blocked with inline feedback when full_name is empty
|
||||
|
||||
### UP-4 Successful save
|
||||
1. Given valid input
|
||||
2. When the user saves
|
||||
3. Then changes persist
|
||||
4. Then success feedback is shown
|
||||
5. Then the user remains on Person detail with refreshed values
|
||||
|
||||
### UP-5 Save failure
|
||||
1. Given backend failure during save
|
||||
2. Then clear error feedback is shown
|
||||
3. Then the user-entered values remain available for retry where possible
|
||||
4. Then no false success feedback is shown
|
||||
|
||||
## Delete Acceptance Criteria
|
||||
|
||||
### DL-1 Delete entry and confirmation
|
||||
1. Given a Person detail page
|
||||
2. When the user selects Delete person
|
||||
3. Then a confirmation dialog appears with permanent-action wording
|
||||
|
||||
### DL-2 Relationship guardrails
|
||||
1. Delete is allowed only when relationship policy allows it
|
||||
2. If linked DocumentPerson rows must be removed first, delete is blocked
|
||||
|
||||
### DL-3 Blocked delete behavior
|
||||
1. When blocked
|
||||
2. Then the UI explains why deletion is blocked
|
||||
3. Then the UI identifies linked-document dependency presence
|
||||
4. Then the UI provides navigation to cleanup paths
|
||||
|
||||
### DL-4 Successful delete
|
||||
1. Given no blocking dependencies
|
||||
2. When the user confirms delete
|
||||
3. Then the Person record is removed
|
||||
4. Then success feedback is shown
|
||||
5. Then the user returns to the Person list page
|
||||
|
||||
### DL-5 Delete failure
|
||||
1. Given backend failure during delete
|
||||
2. Then clear error feedback is shown
|
||||
3. Then the user remains on Person detail with retry path
|
||||
|
||||
## Cross-Criteria Quality Gates
|
||||
|
||||
### QG-1 Separation of intent and implementation
|
||||
1. UX intent remains in user-journey.md
|
||||
2. Current versus target implementation mapping remains in schema-mapping.md
|
||||
|
||||
### QG-2 Traceability
|
||||
1. Each accepted behavior maps to at least one future UI action or service call path
|
||||
2. No acceptance criterion contradicts the deferred-item policy
|
||||
|
||||
### QG-3 First-release constraints
|
||||
1. metadata_ remains hidden in first release
|
||||
2. structured name field split remains deferred
|
||||
3. recipient and multi-person role management stays in later revisions
|
||||
@@ -0,0 +1,265 @@
|
||||
# Person Schema-to-UI Mapping
|
||||
|
||||
Purpose: Map the Person schema to the UI, while clearly separating intended target behavior from current implementation.
|
||||
|
||||
Companion document: user-journey.md
|
||||
Acceptance criteria: acceptance-criteria.md
|
||||
|
||||
## 1. Entity Snapshot
|
||||
|
||||
- Table: Person
|
||||
- Primary key: id (UUID)
|
||||
- Related entities: DocumentPerson, Document
|
||||
- Canonical schema references:
|
||||
- src/transcription/db/models.py
|
||||
- docs/schema_v2.md
|
||||
|
||||
## 2. Mapping Rules
|
||||
|
||||
This document uses three lenses:
|
||||
1. Intended behavior: what the UX should support.
|
||||
2. Current behavior: what the code supports today.
|
||||
3. Gap to target: what must change to align implementation with the intended UX.
|
||||
|
||||
## 3. Field Inventory
|
||||
|
||||
| Field | DB Type | Nullable | Default/Auto Value | Intended UI Treatment | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| id | UUID | No | uuid4() | Hidden, system-managed | Primary key |
|
||||
| full_name | str | No | None | Shown, editable on create and update | Required canonical name |
|
||||
| display_name | str | Yes | None | Shown, editable | Optional |
|
||||
| maiden_name | str | Yes | None | Shown, editable | Optional |
|
||||
| birth_date | date | Yes | None | Shown, editable | Canonical exact date when present |
|
||||
| birth_date_raw | str | Yes | None | Shown, editable | Approximate or unknown date text |
|
||||
| birth_place | str | Yes | None | Shown, editable | Optional |
|
||||
| death_date | date | Yes | None | Shown, editable | Canonical exact date when present |
|
||||
| death_date_raw | str | Yes | None | Shown, editable | Approximate or unknown date text |
|
||||
| death_place | str | Yes | None | Shown, editable | Optional |
|
||||
| biography | str | Yes | None | Shown, editable | Optional narrative |
|
||||
| portrait_path | str | Yes | None | Shown, editable | Optional path |
|
||||
| metadata_ | JSONB/JSON | Yes | None | Hidden in first release | Advanced metadata |
|
||||
| created_at | datetime | No | datetime.now(UTC) | Hidden or read-only | System-managed |
|
||||
| updated_at | datetime | No | datetime.now(UTC) | Hidden or read-only | System-managed |
|
||||
|
||||
## 4. CREATE Mapping
|
||||
|
||||
### 4.1 Intended Create Flow
|
||||
|
||||
Entry point: Person page
|
||||
User action: Create new person
|
||||
Success destination: new Person detail page
|
||||
|
||||
| Field | Intended User Input | Required | Visible | Notes |
|
||||
|---|---|---|---|---|
|
||||
| full_name | Text input | Yes | Yes | Canonical identity field |
|
||||
| display_name | Text input | No | Yes | Optional |
|
||||
| maiden_name | Text input | No | Yes | Optional |
|
||||
| birth_date | Date input | No | Yes | Structured exact date |
|
||||
| birth_date_raw | Text input | No | Yes | Approximate/uncertain date |
|
||||
| birth_place | Text input | No | Yes | Optional |
|
||||
| death_date | Date input | No | Yes | Structured exact date |
|
||||
| death_date_raw | Text input | No | Yes | Approximate/uncertain date |
|
||||
| death_place | Text input | No | Yes | Optional |
|
||||
| biography | Text area | No | Yes | Optional |
|
||||
| portrait_path | Text input | No | Yes | Optional |
|
||||
| metadata_ | None | No | No | Hidden in first release |
|
||||
| created_at | None | No | No | System-generated |
|
||||
| updated_at | None | No | No | Not user-entered |
|
||||
|
||||
Related records during intended create:
|
||||
- No DocumentPerson link is required during Person creation.
|
||||
- Document linking can be done later from Document or Person workflows.
|
||||
|
||||
### 4.2 Current Implementation
|
||||
|
||||
Current entry point: dedicated People page and Person create/edit flows
|
||||
Current user action: open Person create page, fill form fields, optionally upload portrait
|
||||
Current backend path: People page submit callbacks -> DocumentService.create_person() / update_person()
|
||||
|
||||
| Field | Current Value at Create | Source | Visible to User | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| id | Generated UUID | System | No | Person model default factory in src/transcription/db/models.py |
|
||||
| full_name | Form input | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| display_name | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| maiden_name | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| birth_date | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| birth_date_raw | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| birth_place | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| death_date | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| death_date_raw | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| death_place | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| biography | Form input or None | User input | Yes | src/transcription/ui/pages/people_page.py |
|
||||
| portrait_path | Relative upload path or manual path | Upload helper + user input | Yes | src/transcription/ui/pages/people_page.py, src/transcription/services/store.py |
|
||||
| metadata_ | Caller-provided or None | Service/API caller | No | Person model in src/transcription/db/models.py |
|
||||
| created_at | Current UTC timestamp | System | No | Person model default in src/transcription/db/models.py |
|
||||
| updated_at | Current UTC timestamp | System | No | Person model default in src/transcription/db/models.py |
|
||||
|
||||
### 4.3 Gap to Target
|
||||
|
||||
To satisfy the intended Create flow, implementation now includes:
|
||||
1. a Person page and dedicated create form
|
||||
2. user-entered controls for Person fields
|
||||
3. create validation and success/failure UX states
|
||||
4. post-submit routing to a Person detail page
|
||||
|
||||
## 5. READ Mapping
|
||||
|
||||
### 5.1 Intended Read Behavior
|
||||
|
||||
On the Person detail page, the user should be able to see:
|
||||
1. Person identity and biographical metadata
|
||||
2. linked Documents (through DocumentPerson)
|
||||
3. empty-state behavior when no linked documents exist
|
||||
|
||||
### 5.2 Current Implementation
|
||||
|
||||
Current Person visibility is implemented in dedicated list/detail/edit/delete pages.
|
||||
|
||||
| Field | Current Rendering | Visible to User | Notes | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| full_name | Rendered in header and summary | Yes | Dedicated Person page exists | `src/transcription/ui/pages/people_page.py` |
|
||||
| display_name | Rendered | Yes | Visible in detail and list contexts | src/transcription/ui/pages/people_page.py |
|
||||
| maiden_name | Rendered | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| birth_date | Rendered | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| birth_date_raw | Rendered | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| birth_place | Rendered | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| death_date | Rendered | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| death_date_raw | Rendered | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| death_place | Rendered | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| biography | Rendered | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| portrait_path | Rendered as text and image when available | Yes | Dedicated Person page exists | `src/transcription/ui/pages/people_page.py` |
|
||||
| metadata_ | Not rendered | No | Hidden advanced field | no current UI field |
|
||||
| created_at | Rendered read-only | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
| updated_at | Rendered read-only | Yes | Visible in detail context | src/transcription/ui/pages/people_page.py |
|
||||
|
||||
### 5.3 Gap to Target
|
||||
|
||||
To satisfy the intended Read flow, implementation now includes:
|
||||
1. metadata rendering for Person fields
|
||||
2. linked Documents section with empty states
|
||||
3. document-link navigation paths
|
||||
|
||||
## 6. UPDATE Mapping
|
||||
|
||||
### 6.1 Intended Update Behavior
|
||||
|
||||
The user should be able to edit Person metadata from the Person detail page or a dedicated edit flow.
|
||||
|
||||
Intended editable fields:
|
||||
- full_name
|
||||
- display_name
|
||||
- maiden_name
|
||||
- birth_date
|
||||
- birth_date_raw
|
||||
- birth_place
|
||||
- death_date
|
||||
- death_date_raw
|
||||
- death_place
|
||||
- biography
|
||||
- portrait_path
|
||||
|
||||
Intended system-managed fields:
|
||||
- id
|
||||
- created_at
|
||||
- updated_at
|
||||
|
||||
Hidden in first release:
|
||||
- metadata_
|
||||
|
||||
### 6.2 Current Implementation
|
||||
|
||||
| Field | Updatable via UI | Updatable via Service | Notes |
|
||||
|---|---|---|---|
|
||||
| id | No | Practically no | Primary key should be treated as immutable |
|
||||
| full_name | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| display_name | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| maiden_name | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| birth_date | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| birth_date_raw | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| birth_place | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| death_date | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| death_date_raw | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| death_place | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| biography | Yes | Yes | Editable from Person edit page via DocumentService.update_person() |
|
||||
| portrait_path | Yes | Yes | Editable manually and via portrait upload helper |
|
||||
| metadata_ | No | Yes | Technically updatable, hidden in first release |
|
||||
| created_at | No | Technically yes | Should remain system-managed |
|
||||
| updated_at | No | Technically yes | Should remain system-managed |
|
||||
|
||||
### 6.3 Gap to Target
|
||||
|
||||
Implementation now includes:
|
||||
1. Person edit controls in the UI
|
||||
2. validation and save behavior for Person metadata
|
||||
3. a consistent updated_at update policy for Person edits
|
||||
|
||||
## 7. DELETE Mapping
|
||||
|
||||
### 7.1 Intended Delete Behavior
|
||||
|
||||
The UI should provide a delete action for Person with guardrails.
|
||||
|
||||
Rules:
|
||||
1. Deletion can proceed when relationship policy allows no retained document links.
|
||||
2. If linked DocumentPerson records exist and policy requires cleanup first, deletion is blocked.
|
||||
3. Delete confirmation must make clear that deletion is permanent.
|
||||
|
||||
### 7.2 Current Implementation
|
||||
|
||||
| Action | UI Exposed | Backend Capability | Notes |
|
||||
|---|---|---|---|
|
||||
| Delete Person | Yes | Yes | Dedicated delete page enforces linked-document guardrails before service delete |
|
||||
|
||||
### 7.3 Gap to Target
|
||||
|
||||
Implementation includes:
|
||||
1. a Person delete control in the UI
|
||||
2. relationship-aware pre-delete checks
|
||||
3. user-facing blocked-delete messaging
|
||||
4. confirmation UX for successful delete attempts
|
||||
|
||||
## 8. Hidden and System-Managed Fields
|
||||
|
||||
| Field | Category | Why Hidden or Protected |
|
||||
|---|---|---|
|
||||
| id | System-managed | Internal identifier |
|
||||
| created_at | System-managed | Audit timestamp |
|
||||
| updated_at | System-managed | Audit timestamp |
|
||||
| metadata_ | Hidden in first release | Advanced JSON metadata not needed in initial UI |
|
||||
|
||||
## 9. Structured Name Deferred Note
|
||||
|
||||
Structured name fields are deferred to a future schema revision.
|
||||
|
||||
Current policy:
|
||||
1. full_name remains canonical and required.
|
||||
|
||||
Future revision intent:
|
||||
1. introduce first_name, middle_name, last_name, and optional suffix fields.
|
||||
2. maintain compatibility with existing full_name records during migration.
|
||||
3. define normalization and reconciliation rules when structured and canonical forms differ.
|
||||
|
||||
## 10. Traceability Anchors
|
||||
|
||||
Schema and models:
|
||||
- docs/schema_v2.md
|
||||
- src/transcription/db/models.py
|
||||
|
||||
Current implementation:
|
||||
- src/transcription/services/documents.py
|
||||
- src/transcription/ui/pages/people_page.py
|
||||
- src/transcription/services/store.py
|
||||
|
||||
Companion UX spec:
|
||||
- docs/ui/entities/person/user-journey.md
|
||||
|
||||
Acceptance checklist:
|
||||
- docs/ui/entities/person/acceptance-criteria.md
|
||||
|
||||
## 11. Acceptance Checklist Summary
|
||||
|
||||
- Every Person schema field appears in the field inventory.
|
||||
- Intended Create behavior matches the companion user journey.
|
||||
- Current Create behavior reflects dedicated UI form implementation with optional portrait upload handling.
|
||||
- Gaps between intended and current behavior are explicit.
|
||||
- Read, Update, and Delete sections distinguish target behavior from current code.
|
||||
@@ -0,0 +1,292 @@
|
||||
# Person User Journey
|
||||
|
||||
Purpose: Define how a user should interact with the UI to create and manage a Person record, including expected inputs, validation, outcomes, and links to Document relationships.
|
||||
|
||||
Scope: This document describes intended user interaction for the Person UI. It is the UX contract for the Person entity.
|
||||
|
||||
Companion schema mapping: schema-mapping.md
|
||||
Companion acceptance criteria: acceptance-criteria.md
|
||||
|
||||
## 1. Overview
|
||||
|
||||
A Person represents a historical individual who may be associated with one or more Documents.
|
||||
|
||||
Managing a Person is a profile-first workflow:
|
||||
1. The user opens the Person page.
|
||||
2. The user selects Create new person.
|
||||
3. The user enters known biographical fields.
|
||||
4. The system creates the Person record.
|
||||
5. The user can later associate the Person with one or more Documents through DocumentPerson links.
|
||||
|
||||
## 2. User Goal
|
||||
|
||||
The user wants to:
|
||||
1. create and maintain historical person records
|
||||
2. reuse the same Person across multiple Documents
|
||||
3. record both precise and approximate date values where certainty is limited
|
||||
4. link people to documents as author or recipient in future flows
|
||||
|
||||
## 3. Page Model
|
||||
|
||||
### 3.1 Person Page
|
||||
|
||||
The Person page is the general UI surface where users manage people.
|
||||
|
||||
It should support:
|
||||
1. listing or locating existing people
|
||||
2. starting the Create new person flow
|
||||
3. navigating into a specific Person after it exists
|
||||
|
||||
### 3.2 Person Detail Page
|
||||
|
||||
The Person detail page is the page for one specific Person after creation.
|
||||
|
||||
It should show:
|
||||
1. core identity fields
|
||||
2. biographical metadata
|
||||
3. portrait image when available
|
||||
4. related Documents section
|
||||
5. empty state when no linked documents exist yet
|
||||
|
||||
## 4. Entry Point
|
||||
|
||||
Entry point: Person page
|
||||
|
||||
Primary action: Create new person
|
||||
|
||||
Expected UI affordance:
|
||||
1. a visible action labeled Create new person
|
||||
2. activation opens a dedicated form view, modal, or detail panel
|
||||
|
||||
Preferred first implementation:
|
||||
1. dedicated Person create page or panel
|
||||
2. simple labeled form controls
|
||||
3. text inputs are acceptable for first release
|
||||
|
||||
## 5. Create Person Form
|
||||
|
||||
### 5.1 Required Fields
|
||||
|
||||
| UI Label | Schema Field | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Full name | full_name | Text input | Yes | Canonical identity field |
|
||||
|
||||
### 5.2 Optional Name Fields
|
||||
|
||||
| UI Label | Schema Field | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Display name | display_name | Text input | No | Friendly or abbreviated display |
|
||||
| Maiden name | maiden_name | Text input | No | Historical alternate surname |
|
||||
|
||||
### 5.3 Birth and Death Date Fields
|
||||
|
||||
| UI Label | Schema Field | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Birth date | birth_date | Date input | No | Exact known date |
|
||||
| Birth date (approximate/raw) | birth_date_raw | Text input | No | Approximate or uncertain value |
|
||||
| Death date | death_date | Date input | No | Exact known date |
|
||||
| Death date (approximate/raw) | death_date_raw | Text input | No | Approximate or uncertain value |
|
||||
|
||||
Date handling rule:
|
||||
1. exact and raw values may both be entered
|
||||
2. exact date is canonical when present
|
||||
3. raw date is retained as historical context
|
||||
|
||||
### 5.4 Optional Biographical Fields
|
||||
|
||||
| UI Label | Schema Field | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Birth place | birth_place | Text input | No | Free text |
|
||||
| Death place | death_place | Text input | No | Free text |
|
||||
| Biography | biography | Text area | No | Narrative context |
|
||||
| Portrait path | portrait_path | Text input | No | File or resource path |
|
||||
| Metadata | metadata_ | Hidden or advanced JSON editor | No | Prefer hidden in first release |
|
||||
|
||||
### 5.5 System Fields
|
||||
|
||||
| Schema Field | User Editable | Notes |
|
||||
|---|---|---|
|
||||
| id | No | System-generated |
|
||||
| created_at | No | System-generated |
|
||||
| updated_at | No | System-managed |
|
||||
|
||||
## 6. Validation Rules
|
||||
|
||||
### 6.1 Required Validation
|
||||
|
||||
1. full_name is required
|
||||
2. save is blocked when full_name is empty
|
||||
|
||||
### 6.2 Date Validation
|
||||
|
||||
1. birth_date and birth_date_raw may coexist
|
||||
2. death_date and death_date_raw may coexist
|
||||
3. exact date fields are canonical when present
|
||||
4. raw fields remain descriptive context
|
||||
|
||||
### 6.3 Integrity Validation
|
||||
|
||||
1. form accepts unknown values for optional fields
|
||||
2. missing birth or death data does not block creation
|
||||
|
||||
## 7. Submission Behavior
|
||||
|
||||
On submit:
|
||||
1. The system validates required fields
|
||||
2. The system creates the Person record
|
||||
3. The system returns the user to the Person detail page
|
||||
4. The system shows a success message
|
||||
5. If portrait upload is used, the file is stored under uploads/portraits/person and portrait_path is set to that relative file path
|
||||
|
||||
Recommended transactional behavior:
|
||||
1. Person writes are atomic
|
||||
2. no partial save state should be persisted
|
||||
|
||||
## 8. Expected Result After Success
|
||||
|
||||
After successful creation:
|
||||
1. The user sees the Person detail page for the new record
|
||||
2. full_name is visible in the header or summary
|
||||
3. empty Related Documents section is shown if no links exist
|
||||
4. The user can proceed to link this person from Document workflows
|
||||
|
||||
## 9. Expected Result After Failure
|
||||
|
||||
If creation fails:
|
||||
1. Show a clear error message
|
||||
2. Show field-level feedback for validation failures
|
||||
3. preserve entered data where possible
|
||||
4. do not show false success messaging
|
||||
|
||||
## 10. Read Person Journey
|
||||
|
||||
### 10.1 User Intent
|
||||
|
||||
The user wants to open a Person and quickly understand:
|
||||
1. identity and key biography fields
|
||||
2. whether this person is linked to any documents
|
||||
3. what next action to take
|
||||
|
||||
### 10.2 Read Surfaces
|
||||
|
||||
The Person detail page should show:
|
||||
1. full_name and display fields
|
||||
2. birth and death fields
|
||||
3. biography summary
|
||||
4. related documents list or empty state
|
||||
5. portrait preview resolved from /uploads when portrait_path is a relative path
|
||||
|
||||
### 10.3 Read Empty State
|
||||
|
||||
If no linked documents exist:
|
||||
1. Show No linked documents yet
|
||||
2. provide guidance to link from Document workflow
|
||||
|
||||
## 11. Update Person Journey
|
||||
|
||||
### 11.1 User Intent
|
||||
|
||||
The user wants to correct or enrich person metadata over time.
|
||||
|
||||
### 11.2 Editable Fields
|
||||
|
||||
Editable:
|
||||
1. full_name
|
||||
2. display_name
|
||||
3. maiden_name
|
||||
4. birth_date
|
||||
5. birth_date_raw
|
||||
6. birth_place
|
||||
7. death_date
|
||||
8. death_date_raw
|
||||
9. death_place
|
||||
10. biography
|
||||
11. portrait_path
|
||||
|
||||
System-managed:
|
||||
1. id
|
||||
2. created_at
|
||||
3. updated_at
|
||||
4. metadata_ can remain hidden in first release
|
||||
|
||||
### 11.3 Update Save Behavior
|
||||
|
||||
On save:
|
||||
1. validate required fields
|
||||
2. persist updates
|
||||
3. refresh updated_at by system policy
|
||||
4. show confirmation
|
||||
5. keep user on Person detail page
|
||||
|
||||
### 11.4 Update Failure Behavior
|
||||
|
||||
1. Show clear error feedback
|
||||
2. preserve form state where possible
|
||||
3. Allow retry
|
||||
|
||||
## 12. Delete Person Journey
|
||||
|
||||
### 12.1 User Intent
|
||||
|
||||
The user wants to remove incorrect or duplicate person records safely.
|
||||
|
||||
### 12.2 Delete Guardrails
|
||||
|
||||
Delete is allowed when:
|
||||
1. Person has no required retained relationships
|
||||
|
||||
Delete is blocked when:
|
||||
1. Person is linked to one or more Documents via DocumentPerson and unlink policy requires cleanup first
|
||||
|
||||
### 12.3 Blocked Delete UX
|
||||
|
||||
1. explain that linked Document relationships exist
|
||||
2. Show link count or list
|
||||
3. provide cleanup path
|
||||
|
||||
### 12.4 Allowed Delete UX
|
||||
|
||||
1. Show a confirmation dialog
|
||||
2. confirm permanent action
|
||||
3. delete Person
|
||||
4. return to Person list with success message
|
||||
|
||||
## 13. Relationship to Other Workflows
|
||||
|
||||
This Person workflow integrates with:
|
||||
1. Document create and update workflows through person lookup and linking
|
||||
2. DocumentPerson mapping for role assignments
|
||||
3. future recipient and multi-person enhancements
|
||||
|
||||
## 14. Relationship to Schema Mapping
|
||||
|
||||
The companion schema-mapping document should specify:
|
||||
1. field visibility per CRUD action
|
||||
2. current implementation status
|
||||
3. intended behavior
|
||||
4. gap-to-target items
|
||||
|
||||
## 15. Deferred Items
|
||||
|
||||
Deferred to future revisions:
|
||||
1. advanced metadata_ editing UI
|
||||
2. multi-person role editing in the Person UI itself
|
||||
3. richer relationship timeline views
|
||||
4. bulk merge or dedup workflows
|
||||
5. structured name fields migration (first_name, middle_name, last_name, optional suffix)
|
||||
|
||||
### 15.1 Structured Name Fields Migration Note
|
||||
|
||||
For now, `full_name` remains the canonical required name field.
|
||||
|
||||
Future revision intent:
|
||||
1. introduce structured fields such as first_name, middle_name, last_name, and optional suffix
|
||||
2. keep full_name during transition for backward compatibility and historical formatting
|
||||
3. define normalization and formatting rules for display and sorting
|
||||
4. update search and dedup workflows to use both structured and canonical forms during migration
|
||||
|
||||
Migration considerations:
|
||||
1. schema migration and backfill strategy for existing Person records
|
||||
2. validation updates for create and update forms
|
||||
3. compatibility for existing APIs and UI components that currently rely on full_name
|
||||
4. clear precedence and reconciliation rules when structured fields and full_name differ
|
||||
@@ -0,0 +1,141 @@
|
||||
# Source Acceptance Criteria
|
||||
|
||||
Purpose: Define implementation-ready acceptance criteria for Source Create, Read, Update, and Delete workflows.
|
||||
|
||||
Companion documents:
|
||||
- docs/ui/entities/source/user-journey.md
|
||||
- docs/ui/entities/source/schema-mapping.md
|
||||
|
||||
## Scope
|
||||
|
||||
This checklist covers:
|
||||
1. Create flow
|
||||
2. Read flow
|
||||
3. Update flow
|
||||
4. Delete flow
|
||||
|
||||
This checklist does not cover:
|
||||
1. advanced multi-version revision history design
|
||||
2. job orchestration state-machine behavior
|
||||
3. provider-level transcription internals
|
||||
|
||||
## Create Acceptance Criteria
|
||||
|
||||
### CR-1 Source creation entry
|
||||
1. Given the user is in job creation or job configuration flow
|
||||
2. When the user selects Add sources
|
||||
3. Then the user can upload one or more source files or a folder
|
||||
4. Then source creation is not offered as a standalone first-release document-only flow
|
||||
|
||||
### CR-2 Required create values
|
||||
1. document_id is derived from selected Document context
|
||||
2. JobSource.job_id is derived from the active Job context
|
||||
3. Each created Source is linked to the active Job through JobSource at create time
|
||||
4. page_number is assigned to preserve ordering
|
||||
5. upload_name, filename, and file_path are persisted for each created source
|
||||
|
||||
### CR-3 Ordering and filename strategy
|
||||
1. Given a multi-file or folder upload
|
||||
2. When source records are created
|
||||
3. Then page ordering follows alphabetical order of original filenames
|
||||
4. Then upload_name stores the original filename
|
||||
5. Then filename is stored using UUID plus original extension in the form UUID.extension
|
||||
|
||||
### CR-4 Successful create outcome
|
||||
1. Given valid uploads
|
||||
2. When source creation completes
|
||||
3. Then Source records are created and linked to the Document
|
||||
4. Then Source records are linked to the active Job through JobSource
|
||||
5. Then source list reflects new pages in sequence
|
||||
6. Then the user can open preview or revision workflow
|
||||
|
||||
### CR-5 Create failure outcome
|
||||
1. Given upload or persistence failure
|
||||
2. Then clear error feedback is shown
|
||||
3. Then no false success feedback is shown
|
||||
4. Then retry path remains available
|
||||
5. Then creation fails when required Document or Job linkage cannot be established
|
||||
|
||||
## Read Acceptance Criteria
|
||||
|
||||
### RD-1 Source detail retrieval
|
||||
1. Given a valid Source id in source context
|
||||
2. When the user opens source detail
|
||||
3. Then source metadata and preview are displayed for that source only
|
||||
|
||||
### RD-2 Transcription and revision visibility
|
||||
1. Original transcription context is visible read-only in Source detail
|
||||
2. Revision state is visible in Source detail
|
||||
3. If revised_text is absent, revision input opens as empty and can be edited
|
||||
|
||||
### RD-3 Missing source state
|
||||
1. Given a missing source
|
||||
2. Then UI shows clear no source available or not found messaging without crashing
|
||||
|
||||
## Update Acceptance Criteria
|
||||
|
||||
### UP-1 Revision editing entry
|
||||
1. Given a source context
|
||||
2. When the user enters revision edit flow
|
||||
3. Then revised_text input is available in Source detail
|
||||
|
||||
### UP-2 Revision validation
|
||||
1. revised_text cannot be saved as empty after trimming
|
||||
2. Warning feedback is shown for invalid empty input
|
||||
|
||||
### UP-3 Successful revision save
|
||||
1. Given valid revision text
|
||||
2. When the user saves
|
||||
3. Then revised_text persists
|
||||
4. Then date_revised is updated
|
||||
5. Then success feedback is shown
|
||||
6. Then refreshed revision content is visible
|
||||
|
||||
### UP-4 Revision save failure
|
||||
1. Given backend failure during save
|
||||
2. Then clear error feedback is shown
|
||||
3. Then the user-entered text remains available for retry where possible
|
||||
|
||||
## Delete Acceptance Criteria
|
||||
|
||||
### DL-1 Delete entry and confirmation
|
||||
1. Given a source in source context
|
||||
2. When the user selects delete source
|
||||
3. Then a permanent-action confirmation dialog appears
|
||||
|
||||
### DL-2 Dependency guardrails
|
||||
1. If policy requires cleanup of related JobSource records first, delete is blocked
|
||||
2. If policy allows dependent cleanup path, delete can proceed
|
||||
|
||||
### DL-3 Blocked delete behavior
|
||||
1. When blocked
|
||||
2. Then UI explains dependency constraints
|
||||
3. Then UI provides guidance for dependency cleanup
|
||||
|
||||
### DL-4 Successful delete
|
||||
1. Given no blocking dependencies
|
||||
2. When the user confirms deletion
|
||||
3. Then source is removed
|
||||
4. Then success feedback is shown
|
||||
5. Then the user returns to source list context
|
||||
|
||||
### DL-5 Delete failure
|
||||
1. Given backend failure during delete
|
||||
2. Then clear error feedback is shown
|
||||
3. Then the user remains in source context with retry path
|
||||
|
||||
## Cross-Criteria Quality Gates
|
||||
|
||||
### QG-1 Separation of intent and implementation
|
||||
1. UX intent remains in user-journey.md
|
||||
2. Current versus target implementation mapping remains in schema-mapping.md
|
||||
|
||||
### QG-2 Traceability
|
||||
1. Each accepted behavior maps to at least one future UI action or service path
|
||||
2. No acceptance criterion contradicts first-release deferred items
|
||||
|
||||
### QG-3 First-release constraints
|
||||
1. Source creation remains job-create-centric
|
||||
2. revised_text is the primary editable source field in first release
|
||||
3. source creation requires both Document linkage and Job linkage at create time
|
||||
4. source delete management surfaces are phased in later
|
||||
@@ -0,0 +1,212 @@
|
||||
# Source Schema-to-UI Mapping
|
||||
|
||||
Purpose: Map the Source schema to the UI, while clearly separating intended target behavior from current implementation.
|
||||
|
||||
Companion document: user-journey.md
|
||||
Acceptance criteria: acceptance-criteria.md
|
||||
|
||||
## 1. Entity Snapshot
|
||||
|
||||
- Table: Source
|
||||
- Primary key: id (UUID)
|
||||
- Related entities: Document, JobSource, Job
|
||||
- Canonical schema references:
|
||||
- src/transcription/db/models.py
|
||||
- docs/schema_v2.md
|
||||
|
||||
## 2. Mapping Rules
|
||||
|
||||
This document uses three lenses:
|
||||
1. Intended behavior: what the UX should support.
|
||||
2. Current behavior: what the code supports today.
|
||||
3. Gap to target: what must change to align implementation with the intended UX.
|
||||
|
||||
## 3. Field Inventory
|
||||
|
||||
| Field | DB Type | Nullable | Default/Auto Value | Intended UI Treatment | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| id | UUID | No | uuid4() | Hidden, system-managed | Primary key |
|
||||
| document_id | UUID FK | No | None | Hidden/context-managed | Selected Document context |
|
||||
| page_number | int | No | 1 | Shown read-only or ordered list | Sequential ordering |
|
||||
| upload_name | str | No | None | Shown read-only after upload | Original user-provided name |
|
||||
| filename | str | No | None | Shown read-only | Stored filename |
|
||||
| file_path | str | No | None | Usually hidden; preview uses path internally | Filesystem path |
|
||||
| raw_transcription | str | Yes | None | Shown indirectly or hidden | Immutable machine output context |
|
||||
| revised_text | str | Yes | None | Editable in Source detail | Human-authored correction |
|
||||
| date_uploaded | datetime | No | datetime.now(UTC) | Shown read-only | System-managed timestamp |
|
||||
| date_revised | datetime | Yes | None | Shown read-only | Set when revision is saved |
|
||||
|
||||
## 4. CREATE Mapping
|
||||
|
||||
### 4.1 Intended Create Flow
|
||||
|
||||
Entry point: Job creation or job configuration Add sources action
|
||||
User action: upload one or more source files, or a whole folder
|
||||
Success destination: source preview or revision flow in job detail context
|
||||
|
||||
| Field | Intended User Input | Required | Visible | Notes |
|
||||
|---|---|---|---|---|
|
||||
| document_id | Hidden/context | Yes | No | Comes from selected Document |
|
||||
| JobSource.job_id | Hidden/context | Yes | No | Comes from active Job; required for first release |
|
||||
| page_number | Auto or user-assisted ordering | Yes | Indirectly | Should preserve sequence |
|
||||
| upload_name | File picker name | Yes | Yes | Original display name |
|
||||
| filename | None | Yes | No or read-only | System-stored as UUID.extension |
|
||||
| file_path | None | Yes | No | Storage path |
|
||||
| raw_transcription | None | No | No | Filled by processing |
|
||||
| revised_text | None | No | No | Initially empty |
|
||||
| date_uploaded | None | No | No | System-generated |
|
||||
| date_revised | None | No | No | Null until revision |
|
||||
|
||||
### 4.2 Current Implementation
|
||||
|
||||
Current entry point: Jobs page create flow
|
||||
Current user action: upload one or more files or a folder through a single upload widget
|
||||
Current backend path: job create submit -> create_job_for_document()
|
||||
|
||||
| Field | Current Value at Create | Source | Visible to User | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| id | Generated UUID | System | No | Source model default in src/transcription/db/models.py |
|
||||
| document_id | Selected existing Document id | Job create selection + service write | Indirectly | src/transcription/ui/pages/jobs_page.py, src/transcription/services/store.py |
|
||||
| page_number | Sequential assignment based on existing max and alphabetical upload order | Service | No | src/transcription/services/store.py |
|
||||
| upload_name | original filename basename | User file name transformed by service | Indirectly | src/transcription/services/store.py |
|
||||
| filename | stored generated filename | Service | Indirectly | src/transcription/services/store.py |
|
||||
| file_path | stored path | Service | Indirectly | src/transcription/services/store.py |
|
||||
| raw_transcription | None initially | System | No at create | Source model defaults |
|
||||
| revised_text | None initially | System | No at create | Source model defaults |
|
||||
| date_uploaded | current UTC timestamp | System | No | Source model default |
|
||||
| date_revised | None | System | No | Source model default |
|
||||
|
||||
### 4.3 Gap to Target
|
||||
|
||||
To satisfy intended Create flow, implementation now includes:
|
||||
1. multi-source and folder upload support in job create/configure flows
|
||||
2. deterministic page_number assignment from alphabetical original filename ordering
|
||||
3. enforced create-time Source-to-Document and Source-to-Job linkage invariants
|
||||
4. filename storage policy using UUID.extension
|
||||
|
||||
## 5. READ Mapping
|
||||
|
||||
### 5.1 Intended Read Behavior
|
||||
|
||||
On Source detail/list surfaces, users should be able to see:
|
||||
1. source page preview
|
||||
2. source metadata and ordering
|
||||
3. revision state
|
||||
4. original transcription context
|
||||
|
||||
### 5.2 Current Implementation
|
||||
|
||||
Current Source reading is centered on dedicated Sources list/detail routes with optional document/job filtering.
|
||||
|
||||
| Field | Current Rendering | Visible to User | Notes | Evidence |
|
||||
|---|---|---|---|---|
|
||||
| upload_name | Shown in Sources list and Source detail | Yes | Displayed in source context | src/transcription/ui/pages/sources_page.py |
|
||||
| filename | Shown in Sources list and Source detail | Yes | Source metadata shown in list/detail | src/transcription/ui/pages/sources_page.py |
|
||||
| file_path | Hidden from direct text rendering | No | Used internally for preview rendering | src/transcription/ui/components/document_panzoom.py |
|
||||
| page_number | Shown in Sources list and Source detail | Yes | Ordering visible in filtered/global list | src/transcription/ui/pages/sources_page.py |
|
||||
| raw_transcription | Shown read-only in Source detail | Yes | Read from latest linked JobSource context | src/transcription/ui/pages/sources_page.py |
|
||||
| revised_text | Shown and editable in Source detail | Yes | Saved through revision action | src/transcription/ui/pages/sources_page.py |
|
||||
| date_uploaded | Shown in Source detail | Yes | Read-only metadata | src/transcription/ui/pages/sources_page.py |
|
||||
| date_revised | Shown in Source detail | Yes | Read-only metadata after revision save | src/transcription/ui/pages/sources_page.py |
|
||||
|
||||
### 5.3 Gap to Target
|
||||
|
||||
To satisfy intended Read flow, implementation must add:
|
||||
1. optional list filtering controls in-page (current filtering is URL/context based)
|
||||
2. optional page-specific navigation enhancements beyond current list/detail pattern
|
||||
|
||||
## 6. UPDATE Mapping
|
||||
|
||||
### 6.1 Intended Update Behavior
|
||||
|
||||
Primary user update for Source is revised_text maintenance in Source detail.
|
||||
|
||||
Intended editable fields (first release):
|
||||
- revised_text
|
||||
|
||||
Intended read-only fields (first release):
|
||||
- document_id
|
||||
- page_number
|
||||
- upload_name
|
||||
- filename
|
||||
- file_path
|
||||
- raw_transcription
|
||||
- date_uploaded
|
||||
- date_revised
|
||||
|
||||
### 6.2 Current Implementation
|
||||
|
||||
| Field | Updatable via UI | Updatable via Service | Notes |
|
||||
|---|---|---|---|
|
||||
| revised_text | Yes | Yes | Saved via TranscriptionService.upsert_revision_for_source() from Source detail |
|
||||
| date_revised | No | Yes | Set automatically on revision save |
|
||||
| other fields | No | Technically yes in service layer | No first-class UI editing flow |
|
||||
|
||||
### 6.3 Gap to Target
|
||||
|
||||
Implementation should add in a later revision:
|
||||
1. optional future controls for page ordering and metadata corrections
|
||||
2. revision history and conflict-resolution UX beyond single revised_text updates
|
||||
|
||||
## 7. DELETE Mapping
|
||||
|
||||
### 7.1 Intended Delete Behavior
|
||||
|
||||
Source deletion is deferred in the current UI.
|
||||
|
||||
Rules:
|
||||
1. Deletion can proceed when policy allows cleanup of related JobSource records.
|
||||
2. If related execution history must be preserved first, deletion is blocked with guidance.
|
||||
|
||||
### 7.2 Current Implementation
|
||||
|
||||
| Action | UI Exposed | Backend Capability | Notes |
|
||||
|---|---|---|---|
|
||||
| Delete Source | No | Yes | TranscriptionService.delete_source() exists, no dedicated UI delete flow |
|
||||
|
||||
### 7.3 Gap to Target
|
||||
|
||||
Implementation should add in a future revision:
|
||||
1. source delete controls in source/document context UI
|
||||
2. dependency checks for JobSource links
|
||||
3. blocked-delete messaging and cleanup path guidance
|
||||
4. confirmation UX for successful delete attempts
|
||||
|
||||
## 8. Hidden and System-Managed Fields
|
||||
|
||||
| Field | Category | Why Hidden or Protected |
|
||||
|---|---|---|
|
||||
| id | System-managed | Internal identifier |
|
||||
| document_id | Context-managed | Derived from selected document context |
|
||||
| file_path | Operational/internal | Used for file storage and preview plumbing |
|
||||
| date_uploaded | System-managed | Audit timestamp |
|
||||
| date_revised | System-managed | Revision timestamp set by system |
|
||||
|
||||
## 9. Traceability Anchors
|
||||
|
||||
Schema and models:
|
||||
- docs/schema_v2.md
|
||||
- src/transcription/db/models.py
|
||||
|
||||
Current implementation:
|
||||
- src/transcription/services/store.py
|
||||
- src/transcription/services/transcription.py
|
||||
- src/transcription/ui/pages/sources_page.py
|
||||
- src/transcription/ui/pages/jobs_page.py
|
||||
- src/transcription/ui/pages/documents_page.py
|
||||
- src/transcription/ui/components/document_panzoom.py
|
||||
|
||||
Companion UX spec:
|
||||
- docs/ui/entities/source/user-journey.md
|
||||
|
||||
Acceptance checklist:
|
||||
- docs/ui/entities/source/acceptance-criteria.md
|
||||
|
||||
## 10. Acceptance Checklist Summary
|
||||
|
||||
- Every Source schema field appears in the field inventory.
|
||||
- Intended Create behavior matches the companion user journey.
|
||||
- Source create invariant requires both Document linkage and Job linkage at create time.
|
||||
- Current behavior reflects upload-centric create flow and dedicated Sources list/detail review flow.
|
||||
- Gaps between intended and current behavior are explicit.
|
||||
- Read, Update, and Delete sections distinguish target behavior from current code.
|
||||
@@ -0,0 +1,229 @@
|
||||
# Source User Journey
|
||||
|
||||
Purpose: Define how a user should interact with the UI to create and manage Source records, including page-level transcription context and revision behavior.
|
||||
|
||||
Scope: This document describes intended user interaction for the Source UI. It is the UX contract for the Source entity.
|
||||
|
||||
Companion schema mapping: schema-mapping.md
|
||||
Companion acceptance criteria: acceptance-criteria.md
|
||||
|
||||
## 1. Overview
|
||||
|
||||
A Source represents one page or file unit associated with a Document.
|
||||
|
||||
Managing Source records is page-first:
|
||||
1. The user starts from a transcription job flow.
|
||||
2. The user adds one or more source files.
|
||||
3. The system creates Source records linked to the Document and linked to the Job through JobSource.
|
||||
4. The user reviews source lists from a dedicated Sources page.
|
||||
5. The user opens Source detail to review preview, metadata, transcription text, and revision text.
|
||||
|
||||
## 2. User Goal
|
||||
|
||||
The user wants to:
|
||||
1. add page files to a Document
|
||||
2. ensure every source is attached to the transcription job context
|
||||
3. keep page order reliable
|
||||
4. review original machine output
|
||||
5. save human revisions per page
|
||||
6. navigate source pages efficiently
|
||||
|
||||
## 3. Page Model
|
||||
|
||||
### 3.1 Source List Surface
|
||||
|
||||
A Source list surface should support:
|
||||
1. listing source pages globally or filtered by selected Document or Job
|
||||
2. sorting by page_number
|
||||
3. opening the owning Document or Job context
|
||||
4. opening Source detail for a selected source
|
||||
|
||||
### 3.2 Source Detail Surface
|
||||
|
||||
Source detail supports:
|
||||
1. pan/zoom image or PDF preview
|
||||
2. read-only source metadata (page number, names, timestamps)
|
||||
3. read-only original transcription text
|
||||
4. editable revision text with save action
|
||||
|
||||
## 4. Entry Points
|
||||
|
||||
Primary entry points:
|
||||
1. from Job workflow, Add sources while creating or configuring a job
|
||||
2. from Job detail, open filtered Sources for the current Job
|
||||
3. from Document detail, open filtered Sources for the current Document
|
||||
4. from global navigation, open all Sources
|
||||
|
||||
Current implementation note:
|
||||
1. source interaction occurs in job-create flow and dedicated Sources list/detail flows
|
||||
|
||||
## 5. Create Source Flow
|
||||
|
||||
### 5.1 User Intent
|
||||
|
||||
The user wants to attach one or more files to a Document so each page can be processed and reviewed.
|
||||
|
||||
### 5.2 Create from Job Context
|
||||
|
||||
1. The user starts from a job-creation or job-configuration flow
|
||||
2. The user can upload one or more files, or upload a whole folder
|
||||
3. The system creates Source rows linked to the selected Document
|
||||
4. The system creates JobSource links for the active Job as part of this flow
|
||||
5. Source creation fails if required Document or Job linkage cannot be established
|
||||
|
||||
### 5.3 Source Create Inputs
|
||||
|
||||
| UI Label | Schema Field | Input Type | Required | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Source files | upload_name/filename/file_path | Multi-file upload or folder upload | Yes | User may select one file, many files, or a folder |
|
||||
| Processing order | page_number assignment rule | System rule | Yes | If multiple files are uploaded, processing order is alphabetical by original filename |
|
||||
| Document reference | document_id | Hidden/context | Yes | Comes from selected Document |
|
||||
| Job reference | JobSource.job_id | Hidden/context | Yes | Required for first-release source creation |
|
||||
|
||||
### 5.4 Filename Strategy
|
||||
|
||||
1. store original user filename in upload_name
|
||||
2. store persisted filename using UUID plus original extension only, in the form UUID.extension
|
||||
3. this replaces the previous UUID-upload_name.extension pattern
|
||||
|
||||
### 5.5 Ordering Guidance
|
||||
|
||||
1. multi-file or folder uploads are processed alphabetically by original filename
|
||||
2. UI should show a warning or helper note so users understand that filename conventions control order
|
||||
|
||||
Suggested helper text:
|
||||
1. Files are processed alphabetically by original filename. Use leading numbers such as 001, 002, 003 to control page order.
|
||||
|
||||
### 5.6 System-Managed Values at Create
|
||||
|
||||
| Schema Field | User Editable | Notes |
|
||||
|---|---|---|
|
||||
| id | No | System-generated |
|
||||
| date_uploaded | No | System-generated |
|
||||
| raw_transcription | No | Filled later by processing |
|
||||
| revised_text | No | Initially empty |
|
||||
| date_revised | No | Initially null |
|
||||
|
||||
### 5.7 Expected Create Result
|
||||
|
||||
After successful source create:
|
||||
1. Source is linked to the Document
|
||||
2. Source appears in page order derived from alphabetical upload filename ordering
|
||||
3. Source is linked to the Job through JobSource at create time
|
||||
4. The user can open the owning Document or Job context
|
||||
|
||||
### 5.8 Source Creation Invariant
|
||||
|
||||
For first release:
|
||||
1. every new Source must have a Document link (Source.document_id)
|
||||
2. every new Source must have a Job link through JobSource (JobSource.job_id -> JobSource.source_id)
|
||||
3. source creation is treated as part of transcription workflow, not a standalone document-only upload path
|
||||
|
||||
## 6. Read Source Journey
|
||||
|
||||
### 6.1 User Intent
|
||||
|
||||
The user wants to view each page file and understand file identity and processing context.
|
||||
|
||||
### 6.2 Read Surface Expectations
|
||||
|
||||
The UI should show:
|
||||
1. source lists for current context (all, document-filtered, or job-filtered)
|
||||
2. upload_name as the original user-provided filename
|
||||
3. filename as the stored system filename
|
||||
4. page_number and ordering context
|
||||
5. the owning Document and Job navigation context
|
||||
6. direct action to open Source detail
|
||||
|
||||
### 6.3 Read Empty and Missing States
|
||||
|
||||
If source is missing:
|
||||
1. Show clear not found or no source available messaging
|
||||
|
||||
If source metadata is partially unavailable:
|
||||
1. Show fallback labels and keep navigation available where possible
|
||||
|
||||
## 7. Update Source Journey
|
||||
|
||||
### 7.1 User Intent
|
||||
|
||||
The user primarily tracks page-level source records while preserving raw machine output in the service layer.
|
||||
|
||||
### 7.2 Intended Editable Fields
|
||||
|
||||
Editable in first release:
|
||||
1. revised_text in Source detail
|
||||
|
||||
Read-only in first release:
|
||||
1. upload_name
|
||||
2. filename
|
||||
3. file_path
|
||||
4. raw_transcription
|
||||
5. page_number
|
||||
6. date_uploaded
|
||||
7. date_revised set by system on revision save
|
||||
|
||||
### 7.3 Revision Save Behavior
|
||||
|
||||
On save:
|
||||
1. validate revision text is non-empty after trimming
|
||||
2. persist revised_text
|
||||
3. set date_revised
|
||||
4. show success feedback
|
||||
5. keep user in current source context
|
||||
|
||||
### 7.4 Revision Failure Behavior
|
||||
|
||||
If save fails:
|
||||
1. Show clear error feedback
|
||||
2. keep user input where possible
|
||||
3. Allow retry
|
||||
|
||||
## 8. Delete Source Journey
|
||||
|
||||
### 8.1 User Intent
|
||||
|
||||
The user may need to remove incorrect or duplicate source files from a Document.
|
||||
|
||||
### 8.2 Guardrails
|
||||
|
||||
Delete is allowed when:
|
||||
1. policy allows removal of related processing history
|
||||
|
||||
Delete is blocked when:
|
||||
1. policy requires preserving dependent job-source execution records until explicit cleanup
|
||||
|
||||
### 8.3 Delete UX
|
||||
|
||||
When blocked:
|
||||
1. explain dependency constraints in a future delete flow
|
||||
2. show cleanup guidance in a future delete flow
|
||||
|
||||
When allowed:
|
||||
1. confirm permanent removal in a future delete flow
|
||||
2. remove source in a future delete flow
|
||||
3. return to source list with success state in a future delete flow
|
||||
|
||||
## 9. Relationship to Other Workflows
|
||||
|
||||
Source workflow integrates with:
|
||||
1. Document workflow for ownership and page organization
|
||||
2. Job workflow for processing status and outputs
|
||||
3. revision workflow for human correction lifecycle
|
||||
|
||||
## 10. Relationship to Schema Mapping
|
||||
|
||||
The companion schema-mapping document should specify:
|
||||
1. field visibility per CRUD action
|
||||
2. current implementation status
|
||||
3. intended behavior
|
||||
4. gap-to-target items
|
||||
|
||||
## 11. Deferred Items
|
||||
|
||||
Deferred to future revisions:
|
||||
1. bulk page reordering UX
|
||||
2. multi-file upload progress and resumable upload UX
|
||||
3. revision history versions beyond a single revised_text field
|
||||
4. richer per-page status dashboards
|
||||
5. source delete UI with dependency-aware confirmation
|
||||
@@ -0,0 +1,78 @@
|
||||
# UI Entity Traceability Matrix
|
||||
|
||||
Purpose: Map acceptance criteria to concrete implementation anchors and current delivery status.
|
||||
|
||||
Updated: 2026-08-02
|
||||
|
||||
Status legend:
|
||||
- Implemented: behavior exists in current UI and service flow
|
||||
- Partial: parts exist, but user-facing behavior or guardrails are incomplete
|
||||
- Planned: documented intent with no dedicated UI implementation yet
|
||||
|
||||
## Document
|
||||
|
||||
| Criteria Group | Acceptance IDs | Status | Primary Implementation Anchors | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Read detail and metadata | RD-1, RD-2, RD-7 | Implemented | src/transcription/ui/pages/documents_page.py; src/transcription/services/documents.py; tests/ui/test_documents_page.py | Dedicated Document detail route renders metadata, read-only system timestamps, and invalid/missing-id states. |
|
||||
| Related sections and navigation | RD-3, RD-4, RD-5, RD-6 | Implemented | src/transcription/ui/pages/documents_page.py; src/transcription/services/documents.py; tests/ui/test_documents_page.py | Document detail now shows linked people plus document-scoped Sources and Jobs navigation for the current document. |
|
||||
| Update entry, validation, and author linkage | UP-1, UP-2, UP-3, UP-4, UP-5, UP-6 | Implemented | src/transcription/ui/pages/documents_page.py; src/transcription/services/documents.py; tests/ui/test_documents_page.py; tests/services/test_document_service.py | Dedicated edit page includes required-field validation messaging, date parsing rules, and author relationship selection with save path routed back to document detail. |
|
||||
| Delete controls and guardrails | DL-1, DL-2, DL-3, DL-4, DL-5 | Implemented | src/transcription/ui/pages/documents_page.py; src/transcription/services/documents.py; tests/ui/test_documents_page.py; tests/services/test_document_service.py | Dedicated delete page provides permanent-action confirmation, dependency-category blocking, and guarded backend delete behavior. |
|
||||
|
||||
## Person
|
||||
|
||||
| Criteria Group | Acceptance IDs | Status | Primary Implementation Anchors | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Create flow and validation | CR-1, CR-2, CR-3, CR-4, CR-5 | Implemented | src/transcription/ui/pages/people_page.py; src/transcription/services/documents.py; tests/ui/test_people_page.py | Dedicated Person create page with required full_name validation, optional field handling, and success routing to detail. |
|
||||
| Read detail and linked documents | RD-1, RD-2, RD-3, RD-4 | Implemented | src/transcription/ui/pages/people_page.py; src/transcription/services/documents.py; tests/ui/test_people_page.py; tests/services/test_document_service.py | Person detail route renders metadata, full-name summary, portrait preview when available, linked-document section, and invalid/missing-id states. |
|
||||
| Update behavior | UP-1, UP-2, UP-3, UP-4, UP-5 | Implemented | src/transcription/ui/pages/people_page.py; src/transcription/services/documents.py; tests/ui/test_people_page.py; tests/services/test_document_service.py | Dedicated Person edit page supports allowed fields, required full_name validation, and save path back to detail. |
|
||||
| Delete behavior and guardrails | DL-1, DL-2, DL-3, DL-4, DL-5 | Implemented | src/transcription/ui/pages/people_page.py; src/transcription/services/documents.py; tests/ui/test_people_page.py; tests/services/test_document_service.py | Dedicated delete page provides permanent-action confirmation, linked-document blocking message, and guarded backend delete behavior. |
|
||||
|
||||
## Source
|
||||
|
||||
| Criteria Group | Acceptance IDs | Status | Primary Implementation Anchors | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Create entry and required links | CR-1, CR-2, CR-4, CR-5 | Implemented | src/transcription/services/store.py; src/transcription/ui/pages/jobs_page.py; src/transcription/ui/pages/upload_page.py; tests/services/test_store.py; tests/ui/test_jobs_page.py | Source upload/create is job-create-context only (legacy upload route redirects), with required Document and JobSource linkage enforced. |
|
||||
| Ordering and filename policy | CR-3 | Implemented | src/transcription/services/store.py; tests/services/test_store.py; tests/ui/test_jobs_page.py | Multi-file/folder uploads are ordered alphabetically by original filename, helper text is visible, and stored filenames use generated unique-id plus extension. |
|
||||
| Read and navigation visibility | RD-1, RD-2, RD-3 | Implemented | src/transcription/ui/pages/sources_page.py; src/transcription/ui/pages/documents_page.py; src/transcription/ui/pages/jobs_page.py; tests/ui/test_sources_page.py; tests/ui/test_documents_page.py; tests/ui/test_jobs_page.py | Dedicated Sources list/detail routes support global, document-filtered, and job-filtered navigation plus source metadata and preview rendering. |
|
||||
| Revision update behavior | UP-1, UP-2, UP-3, UP-4 | Implemented | src/transcription/ui/pages/sources_page.py; src/transcription/services/transcription.py; tests/ui/test_sources_page.py; tests/services/test_transcription_service.py | Source detail exposes revision edit/save UX with non-empty validation, success feedback, and refreshed state after save. |
|
||||
| Delete and dependency guardrails | DL-1, DL-2, DL-3, DL-4, DL-5 | Planned | src/transcription/services/transcription.py; tests/services/test_transcription_service.py | Job-detail source delete UI was removed from the current simplified flow; backend guardrails remain for future reinstatement. |
|
||||
|
||||
## Job
|
||||
|
||||
| Criteria Group | Acceptance IDs | Status | Primary Implementation Anchors | Notes |
|
||||
|---|---|---|---|---|
|
||||
| Create entry and required links | CR-1, CR-2, CR-5, CR-6 | Implemented | src/transcription/services/store.py; src/transcription/ui/pages/jobs_page.py; tests/ui/test_jobs_page.py; tests/services/test_store.py | Jobs list now has explicit Create entry and `/jobs/new` create flow with Document selection, combined file/folder upload widget, and submit routing to job detail. |
|
||||
| Source ordering and upload behavior | CR-3 | Implemented | src/transcription/services/store.py; src/transcription/ui/pages/jobs_page.py; tests/services/test_store.py; tests/ui/test_jobs_page.py | Multi-file and folder upload are supported through one widget, uploads are sorted alphabetically by original filename, and helper guidance is shown in create UI. |
|
||||
| Provider/model/prompt visibility | CR-4, RD-4 | Implemented | src/transcription/services/workflows.py; src/transcription/ui/pages/jobs_page.py; tests/ui/test_jobs_page.py | Provider/model/prompt fields are visible in create and detail flows when known (with pending fallback labels). |
|
||||
| Jobs list and detail read states | RD-1, RD-2, RD-3, RD-5 | Implemented | src/transcription/ui/pages/jobs_page.py; src/transcription/ui/components/table/jobs.py; tests/ui/test_jobs_page.py | Jobs list, detail route, document-scoped navigation, and invalid/missing id states are present. |
|
||||
| Revision update behavior | UP-1, UP-2, UP-3, UP-4 | Implemented | src/transcription/ui/pages/jobs_page.py; src/transcription/ui/pages/sources_page.py; src/transcription/services/transcription.py; tests/ui/test_jobs_page.py; tests/ui/test_sources_page.py; tests/services/test_transcription_service.py | Job detail routes users to job-scoped Sources where Source detail provides revision edit/save workflow. |
|
||||
| Lifecycle visibility and retry indicators | UP-5 | Implemented | src/transcription/services/jobs.py; src/transcription/services/workflows.py; src/transcription/ui/pages/jobs_page.py; tests/ui/test_jobs_page.py | Job detail now surfaces lifecycle status plus retry/update metadata while lifecycle fields remain system-managed (no direct user edit controls). |
|
||||
| Delete and dependency guardrails | DL-1, DL-2, DL-3, DL-4, DL-5 | Implemented | src/transcription/ui/pages/jobs_page.py; src/transcription/services/jobs.py; tests/ui/test_jobs_page.py; tests/services/test_job_service.py | Job delete page enforces processing-state block, confirms allowed deletes, and routes back to jobs list on success. |
|
||||
|
||||
## Quality Gate Coverage
|
||||
|
||||
| Quality Gate | Acceptance IDs | Status | Notes |
|
||||
|---|---|---|---|
|
||||
| Separation of intent vs implementation | QG-1 across entities | Implemented | user-journey.md, schema-mapping.md, and acceptance-criteria.md are maintained per entity. |
|
||||
| Traceability from criteria to implementation | QG-2 across entities | Implemented | This matrix provides criterion-to-code anchors and current status tags. |
|
||||
| First-release constraints | QG-3 across entities | Implemented | Constraints are documented and aligned with current flows: jobs-first source upload, visible provider/model/prompt context, and system-managed lifecycle fields. |
|
||||
|
||||
## Supporting Entity Coverage
|
||||
|
||||
| Supporting Entity | Documentation | Status | Notes |
|
||||
|---|---|---|---|
|
||||
| document-person | docs/ui/entities/document-person/schema-mapping.md | Completed | Supporting-entity schema mapping created; no standalone UI contract file by design. |
|
||||
| job-source | docs/ui/entities/job-source/schema-mapping.md | Completed | Supporting-entity schema mapping created; no standalone UI contract file by design. |
|
||||
|
||||
## Suggested Implementation Order
|
||||
|
||||
1. Aggregate final acceptance review across Document, Person, Source, and Job criteria.
|
||||
|
||||
## Aggregate Final Review Snapshot (2026-08-02)
|
||||
|
||||
| Entity | Acceptance IDs still not fully met | Evidence | Notes |
|
||||
|---|---|---|---|
|
||||
| Document | None | src/transcription/ui/pages/documents_page.py; tests/ui/test_documents_page.py | Document criteria are covered by dedicated detail/edit/delete pages and document-scoped related views. |
|
||||
| Person | None | src/transcription/ui/pages/people_page.py; tests/ui/test_people_page.py | Person criteria are covered by dedicated create/detail/edit/delete pages with relationship-aware delete guardrails. |
|
||||
| Source | None | src/transcription/services/store.py; src/transcription/ui/pages/sources_page.py; src/transcription/ui/pages/jobs_page.py; tests/services/test_store.py; tests/ui/test_sources_page.py; tests/services/test_transcription_service.py | Source criteria are covered by job-context create behavior, ordering/filename policy, dedicated list/detail read flow, revision flow, and delete guardrails. |
|
||||
| Job | None | src/transcription/ui/pages/jobs_page.py; src/transcription/services/jobs.py; tests/ui/test_jobs_page.py; tests/services/test_job_service.py | Job criteria are covered by create/read/revision/lifecycle visibility and delete guardrails in dedicated routes. |
|
||||
@@ -0,0 +1,35 @@
|
||||
# AI Coding Assistant Project Briefing & Context
|
||||
|
||||
## Project Mission
|
||||
This application is a family history archival and transcription platform. Its primary goal is to accept scanned document images (letters, postcards, logbooks, diaries), execute OCR and structured transcription via AI vision models (OpenAI GPT-4o, Anthropic Claude 3.5 Sonnet), and manage historical metadata (authors, recipients, dates, and locations).
|
||||
|
||||
---
|
||||
|
||||
## Technical Stack & Architecture
|
||||
* **Database:** PostgreSQL 13+ with native `UUID` (`gen_random_uuid()`) and `JSONB` columns.
|
||||
* **Backend Runtime / Concurrency:** Python utilizing `asyncio` for concurrent HTTP API calls to AI providers, with strict rate-limiting via `asyncio.Semaphore`.
|
||||
* **Validation & Types:** Python with **Pydantic** model definitions. Incoming AI responses must be parsed and validated with Pydantic models *before* database insertion.
|
||||
* **ORM / Database Access:** SQLModel and SQLAlchemy, using parameterized statements and PostgreSQL-native types.
|
||||
|
||||
---
|
||||
|
||||
## Core System Directives for AI Code Generation
|
||||
|
||||
### 1. Data Immutability vs. Human Corrections
|
||||
* `job_source.raw_transcription` and `source.raw_transcription` represent original, point-in-time machine outputs and are **immutable**.
|
||||
* Human corrections occur on `source.revised_text`.
|
||||
* When fetching text for the UI, always display `COALESCE(source.revised_text, source.raw_transcription)`.
|
||||
|
||||
### 2. Async Execution & Batching Rules
|
||||
* A `job` represents an overarching execution run for a folder/group of images belonging to a single `document`.
|
||||
* Images are submitted to AI APIs **one at a time in rapid succession** using `asyncio` worker pools.
|
||||
* Each single-image API call populates a row in `job_source` with its own `status`, `raw_transcription`, `ai_metadata`, and `raw_api_response`.
|
||||
* If 9 of 10 pages succeed and 1 fails, `job_source.status` for the failed image becomes `'failed'`, while `job.status` becomes `'partial_success'`. Do not mark the entire batch as failed if partial results exist.
|
||||
|
||||
### 3. Entity Relationships
|
||||
* **Authors/Recipients:** A `document` can have multiple authors and recipients. Do NOT put direct `author_id` foreign keys on `document`. Query authors/recipients via `document_person` where `role = 'author'` or `role = 'recipient'`.
|
||||
* **Page Ordering:** Multi-page documents must always be queried using `ORDER BY page_number ASC`.
|
||||
|
||||
### 4. Database Mutations
|
||||
* Always use parameterized SQL queries (`$1`, `$2`) to prevent SQL injection.
|
||||
* Store datetimes using UTC ISO 8601 strings or native PostgreSQL `TIMESTAMPTZ`.
|
||||
@@ -0,0 +1,416 @@
|
||||
# SQLModel Table Models
|
||||
|
||||
These models implement the canonical [Version 2 database schema](../schema_v2.md). Each schema entity is represented by exactly one `SQLModel` table class. Because `SQLModel` is built on Pydantic and SQLAlchemy, these classes provide application validation and PostgreSQL mappings without parallel row and create models.
|
||||
|
||||
Database-generated UUIDs and timestamps are `None` until PostgreSQL supplies their values during insert. The database columns remain non-nullable. `Person.metadata_` maps to the `metadata` column because `metadata` is reserved by SQLAlchemy's declarative API.
|
||||
|
||||
```python
|
||||
from datetime import date
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import JsonValue
|
||||
from sqlalchemy import Column
|
||||
from sqlalchemy import Date
|
||||
from sqlalchemy import DateTime
|
||||
from sqlalchemy import ForeignKey
|
||||
from sqlalchemy import Index
|
||||
from sqlalchemy import Integer
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy import Text
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.dialects.postgresql import UUID as PostgreSQLUUID
|
||||
from sqlmodel import Field
|
||||
from sqlmodel import Relationship
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
|
||||
class PersonRole(StrEnum):
|
||||
AUTHOR = "author"
|
||||
RECIPIENT = "recipient"
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
QUEUED = "queued"
|
||||
PROCESSING = "processing"
|
||||
COMPLETED = "completed"
|
||||
PARTIAL_SUCCESS = "partial_success"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
class JobSourceStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
TRANSCRIBED = "transcribed"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
class Person(SQLModel, table=True):
|
||||
__tablename__ = "person"
|
||||
__table_args__ = (Index("idx_person_full_name", "full_name"),)
|
||||
|
||||
id: UUID | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
primary_key=True,
|
||||
server_default=text("gen_random_uuid()"),
|
||||
),
|
||||
)
|
||||
full_name: str = Field(sa_column=Column(Text, nullable=False))
|
||||
display_name: str | None = Field(default=None, sa_column=Column(Text))
|
||||
maiden_name: str | None = Field(default=None, sa_column=Column(Text))
|
||||
birth_date: date | None = Field(default=None, sa_column=Column(Date))
|
||||
birth_date_raw: str | None = Field(default=None, sa_column=Column(Text))
|
||||
birth_place: str | None = Field(default=None, sa_column=Column(Text))
|
||||
death_date: date | None = Field(default=None, sa_column=Column(Date))
|
||||
death_date_raw: str | None = Field(default=None, sa_column=Column(Text))
|
||||
death_place: str | None = Field(default=None, sa_column=Column(Text))
|
||||
biography: str | None = Field(default=None, sa_column=Column(Text))
|
||||
portrait_path: str | None = Field(default=None, sa_column=Column(Text))
|
||||
metadata_: JsonValue | None = Field(
|
||||
default_factory=dict,
|
||||
sa_column=Column(
|
||||
"metadata",
|
||||
JSONB,
|
||||
server_default=text("'{}'::jsonb"),
|
||||
),
|
||||
)
|
||||
created_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
updated_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
|
||||
document_people: list["DocumentPerson"] = Relationship(
|
||||
back_populates="person",
|
||||
sa_relationship_kwargs={"lazy": "raise", "passive_deletes": True},
|
||||
)
|
||||
|
||||
|
||||
class Document(SQLModel, table=True):
|
||||
__tablename__ = "document"
|
||||
__table_args__ = (Index("idx_document_date", "document_date"),)
|
||||
|
||||
id: UUID | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
primary_key=True,
|
||||
server_default=text("gen_random_uuid()"),
|
||||
),
|
||||
)
|
||||
name: str = Field(sa_column=Column(Text, nullable=False))
|
||||
document_type: str | None = Field(default=None, sa_column=Column(Text))
|
||||
document_date: date | None = Field(default=None, sa_column=Column(Date))
|
||||
document_date_raw: str | None = Field(default=None, sa_column=Column(Text))
|
||||
location_created: str | None = Field(default=None, sa_column=Column(Text))
|
||||
notes: str | None = Field(default=None, sa_column=Column(Text))
|
||||
archive_identifier: str | None = Field(default=None, sa_column=Column(Text))
|
||||
created_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
updated_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
|
||||
document_people: list["DocumentPerson"] = Relationship(
|
||||
back_populates="document",
|
||||
sa_relationship_kwargs={"lazy": "raise", "passive_deletes": True},
|
||||
)
|
||||
jobs: list["Job"] = Relationship(
|
||||
back_populates="document",
|
||||
sa_relationship_kwargs={"lazy": "raise", "passive_deletes": True},
|
||||
)
|
||||
sources: list["Source"] = Relationship(
|
||||
back_populates="document",
|
||||
sa_relationship_kwargs={"lazy": "raise", "passive_deletes": True},
|
||||
)
|
||||
|
||||
|
||||
class DocumentPerson(SQLModel, table=True):
|
||||
__tablename__ = "document_person"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"document_id",
|
||||
"person_id",
|
||||
"role",
|
||||
name="unique_document_person_role",
|
||||
),
|
||||
Index("idx_document_person_doc", "document_id"),
|
||||
Index("idx_document_person_per", "person_id"),
|
||||
)
|
||||
|
||||
id: UUID | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
primary_key=True,
|
||||
server_default=text("gen_random_uuid()"),
|
||||
),
|
||||
)
|
||||
document_id: UUID = Field(
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
ForeignKey("document.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
)
|
||||
person_id: UUID = Field(
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
ForeignKey("person.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
)
|
||||
role: PersonRole = Field(sa_column=Column(String(20), nullable=False))
|
||||
created_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
|
||||
document: Document | None = Relationship(
|
||||
back_populates="document_people",
|
||||
sa_relationship_kwargs={"lazy": "raise"},
|
||||
)
|
||||
person: Person | None = Relationship(
|
||||
back_populates="document_people",
|
||||
sa_relationship_kwargs={"lazy": "raise"},
|
||||
)
|
||||
|
||||
|
||||
class Job(SQLModel, table=True):
|
||||
__tablename__ = "job"
|
||||
__table_args__ = (Index("idx_job_document", "document_id"),)
|
||||
|
||||
id: UUID | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
primary_key=True,
|
||||
server_default=text("gen_random_uuid()"),
|
||||
),
|
||||
)
|
||||
document_id: UUID = Field(
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
ForeignKey("document.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
)
|
||||
status: JobStatus = Field(
|
||||
default=JobStatus.QUEUED,
|
||||
sa_column=Column(
|
||||
String(50),
|
||||
nullable=False,
|
||||
server_default=text("'queued'"),
|
||||
),
|
||||
)
|
||||
retry_count: int = Field(
|
||||
default=0,
|
||||
sa_column=Column(
|
||||
Integer,
|
||||
nullable=False,
|
||||
server_default=text("0"),
|
||||
),
|
||||
)
|
||||
provider: str = Field(sa_column=Column(Text, nullable=False))
|
||||
model: str = Field(sa_column=Column(Text, nullable=False))
|
||||
prompt_name: str | None = Field(default=None, sa_column=Column(Text))
|
||||
date_created: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
date_updated: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
|
||||
document: Document | None = Relationship(
|
||||
back_populates="jobs",
|
||||
sa_relationship_kwargs={"lazy": "raise"},
|
||||
)
|
||||
job_sources: list["JobSource"] = Relationship(
|
||||
back_populates="job",
|
||||
sa_relationship_kwargs={"lazy": "raise", "passive_deletes": True},
|
||||
)
|
||||
|
||||
|
||||
class Source(SQLModel, table=True):
|
||||
__tablename__ = "source"
|
||||
__table_args__ = (
|
||||
Index("idx_source_document", "document_id"),
|
||||
Index("idx_source_page_order", "document_id", "page_number"),
|
||||
)
|
||||
|
||||
id: UUID | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
primary_key=True,
|
||||
server_default=text("gen_random_uuid()"),
|
||||
),
|
||||
)
|
||||
document_id: UUID = Field(
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
ForeignKey("document.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
)
|
||||
page_number: int = Field(
|
||||
default=1,
|
||||
sa_column=Column(
|
||||
Integer,
|
||||
nullable=False,
|
||||
server_default=text("1"),
|
||||
),
|
||||
)
|
||||
upload_name: str = Field(sa_column=Column(Text, nullable=False))
|
||||
filename: str = Field(sa_column=Column(Text, nullable=False))
|
||||
file_path: str = Field(sa_column=Column(Text, nullable=False))
|
||||
raw_transcription: str | None = Field(default=None, sa_column=Column(Text))
|
||||
revised_text: str | None = Field(default=None, sa_column=Column(Text))
|
||||
date_uploaded: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
date_revised: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(DateTime(timezone=True)),
|
||||
)
|
||||
|
||||
document: Document | None = Relationship(
|
||||
back_populates="sources",
|
||||
sa_relationship_kwargs={"lazy": "raise"},
|
||||
)
|
||||
job_sources: list["JobSource"] = Relationship(
|
||||
back_populates="source",
|
||||
sa_relationship_kwargs={"lazy": "raise", "passive_deletes": True},
|
||||
)
|
||||
|
||||
|
||||
class JobSource(SQLModel, table=True):
|
||||
__tablename__ = "job_source"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("job_id", "source_id", name="unique_job_source"),
|
||||
Index("idx_job_source_job", "job_id"),
|
||||
Index("idx_job_source_source", "source_id"),
|
||||
Index(
|
||||
"idx_job_source_ai_metadata",
|
||||
"ai_metadata",
|
||||
postgresql_using="gin",
|
||||
),
|
||||
)
|
||||
|
||||
id: UUID | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
primary_key=True,
|
||||
server_default=text("gen_random_uuid()"),
|
||||
),
|
||||
)
|
||||
job_id: UUID = Field(
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
ForeignKey("job.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
)
|
||||
source_id: UUID = Field(
|
||||
sa_column=Column(
|
||||
PostgreSQLUUID(as_uuid=True),
|
||||
ForeignKey("source.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
)
|
||||
status: JobSourceStatus = Field(
|
||||
default=JobSourceStatus.PENDING,
|
||||
sa_column=Column(
|
||||
String(50),
|
||||
nullable=False,
|
||||
server_default=text("'pending'"),
|
||||
),
|
||||
)
|
||||
raw_transcription: str | None = Field(default=None, sa_column=Column(Text))
|
||||
ai_metadata: JsonValue | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(JSONB),
|
||||
)
|
||||
raw_api_response: JsonValue | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(JSONB),
|
||||
)
|
||||
error_detail: str | None = Field(default=None, sa_column=Column(Text))
|
||||
executed_at: datetime | None = Field(
|
||||
default=None,
|
||||
sa_column=Column(
|
||||
DateTime(timezone=True),
|
||||
nullable=False,
|
||||
server_default=text("now()"),
|
||||
),
|
||||
)
|
||||
|
||||
job: Job | None = Relationship(
|
||||
back_populates="job_sources",
|
||||
sa_relationship_kwargs={"lazy": "raise"},
|
||||
)
|
||||
source: Source | None = Relationship(
|
||||
back_populates="job_sources",
|
||||
sa_relationship_kwargs={"lazy": "raise"},
|
||||
)
|
||||
```
|
||||
|
||||
The enum annotations validate application values while the mapped columns retain the `VARCHAR` types specified by the DDL. PostgreSQL owns generated UUIDs and timestamps through `server_default`; call `session.refresh(instance)` after a flush or commit when those generated values are needed immediately.
|
||||
|
||||
`ai_metadata`, `raw_api_response`, and `metadata_` accept any JSON value supported by `JSONB`. Validate provider-specific payload structure before assigning it to these fields, while preserving the complete raw response in `raw_api_response`.
|
||||
|
||||
Relationships use `lazy="raise"` to prevent implicit database I/O in async code. Queries must explicitly load relationships they need, for example with `selectinload()`.
|
||||
|
||||
The schema's behavioral invariants are enforced outside the table shape where appropriate:
|
||||
|
||||
- `PersonRole`, `JobStatus`, and `JobSourceStatus` define the exact values listed by the schema.
|
||||
- `unique_document_person_role` enforces role uniqueness for `(document_id, person_id, role)`.
|
||||
- Services order document sources by `Source.document_id` and `Source.page_number`.
|
||||
- Services derive aggregate `Job.status` from related `JobSource.status` values.
|
||||
- Services preserve `JobSource.raw_transcription` and `JobSource.raw_api_response` as point-in-time outputs while updating the active text on `Source`.
|
||||
@@ -59,7 +59,7 @@ Responsibilities:
|
||||
|
||||
### Domain & Service Layer
|
||||
|
||||
* `src/transcription/models/*.py` (Pydantic V2 schemas and entity definitions)
|
||||
* `src/transcription/db/models.py` (SQLModel/Pydantic V2 schema definitions for the current implementation)
|
||||
* `src/transcription/services/*.py` (Transactional operations for `Document`, `Person`, `Source`, `Job`, and `JobSource`)
|
||||
|
||||
### Infrastructure Layer
|
||||
@@ -121,14 +121,14 @@ Responsibilities:
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v1.md)
|
||||
- [System Design Intent](intent.md)
|
||||
- [Transcription Methodology](transcription_methodology.md)
|
||||
- [System Overview](index_v2.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- System Architecture (this document)
|
||||
- [System Requirements](requirements_v1.md)
|
||||
- [Data model](schema_v1.md)
|
||||
- [Error Handling Policy](error_handling_v1.md)
|
||||
- [Implementation Plan](implementation_plan_v1.md)
|
||||
- [System Requirements](requirements_v2.md)
|
||||
- [Data model](schema_v2.md)
|
||||
- [Error Handling Policy](error_handling_v2.md)
|
||||
- [Implementation Plan](implementation_plan_v2.md)
|
||||
|
||||
|
||||
|
||||
@@ -79,8 +79,8 @@ HTTP Status Mappings:
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v2.md)
|
||||
- [System Design Intent](intent.md)
|
||||
- [Transcription Methodology](transcription_methodology.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- [System Architecture](architecture_v2.md)
|
||||
- [System Requirements](requirements_v2.md)
|
||||
- [Data model](schema_v2.md)
|
||||
@@ -0,0 +1,64 @@
|
||||
# implementation_plan_v2
|
||||
|
||||
## Goal
|
||||
|
||||
Replace the current V1 SQLModel schema with the approved V2 schema and make sure every database operation works through the existing async SQLAlchemy/SQLModel session layer.
|
||||
|
||||
Use a fresh database. There will be no migrations, data conversion, legacy compatibility shims, or parallel V1/V2 code paths.
|
||||
|
||||
## Current Project Impact
|
||||
|
||||
- `src/transcription/db/models.py` still defines the V1 `Document`, `Source`, `Job`, and `Revision` tables.
|
||||
- The V2 target adds `Person`, `DocumentPerson`, and `JobSource`, moves revisions onto `Source`, and removes the direct `Source.job_id` relationship.
|
||||
- The engine, session factory, transaction handling, and PostgreSQL async support already exist and do not need to be rewritten.
|
||||
- Async CRUD currently lives in `DocumentService`, `JobService`, `TranscriptionService`, and the upload record helper. Their queries and eager-loading options depend on V1 relationships.
|
||||
- Existing tests cover only part of the schema and CRUD surface.
|
||||
|
||||
## Implementation
|
||||
|
||||
### 1. Update the schema
|
||||
|
||||
- Replace the models in `src/transcription/db/models.py` with the approved V2 tables, enums, relationships, foreign keys, constraints, and indexes.
|
||||
- Remove `Revision`, `Source.job_id`, and the transcription fields that no longer belong on `Job`.
|
||||
- Keep `create_all()` as the schema bootstrap for a fresh database.
|
||||
- Delete `_ensure_sqlite_compat_columns()` and all schema patching from `src/transcription/db/operations.py`.
|
||||
- Keep the Python models and `docs/schema_v2.md` consistent.
|
||||
|
||||
### 2. Align the async CRUD methods
|
||||
|
||||
- Keep the existing `ServiceBase` session and transaction pattern.
|
||||
- Update document CRUD to load and manage its ordered `Source` rows and `DocumentPerson` links.
|
||||
- Update job CRUD and queue queries to use `JobSource` instead of `Source.job_id`.
|
||||
- Add the missing async CRUD operations for `Person`, `Source`, `DocumentPerson`, and `JobSource` using the existing service style. Do not add another repository abstraction.
|
||||
- Replace revision CRUD with direct updates to `Source.revised_text` and `Source.date_revised`.
|
||||
- Remove the temporary transcript compatibility aliases instead of redirecting them.
|
||||
- Update only direct database call sites that construct or query these records; UI and worker feature changes are not part of this work.
|
||||
|
||||
### 3. Verify the schema and CRUD
|
||||
|
||||
- Update the schema bootstrap test to expect `person`, `document`, `document_person`, `source`, `job`, and `job_source`, with no `revision` table.
|
||||
- Add async create, read, update, delete, list, and filtered-query tests for each entity that exposes those operations.
|
||||
- Test relationship loading, page ordering, uniqueness constraints, delete behavior, status values, and `JobSource` JSON fields.
|
||||
- Test both service-owned sessions and caller-provided sessions so flush/commit behavior remains correct.
|
||||
- Run the focused database and service tests, then the full suite with `uv run pytest`.
|
||||
|
||||
### 4. Update the UI for the V2 schema
|
||||
|
||||
- Review the UI components and views that display document, job, person, and source data so they reference the V2 schema instead of V1 relationships.
|
||||
- Update upload, detail, and listing screens to show the new person and source associations, revised-source fields, and the revised status values.
|
||||
- Keep the UI behavior aligned with the updated service layer and ensure the existing UI tests continue to pass with the V2 data model.
|
||||
- Consider the guidance in `docs/ui_style_guide.md` when making UI changes so the updated views remain consistent with the project’s visual and interaction conventions.
|
||||
|
||||
## Done When
|
||||
|
||||
- A fresh database is created directly from the V2 SQLModel metadata.
|
||||
- All async CRUD methods pass against the V2 relationships and fields.
|
||||
- No code references `Revision`, `Source.job_id`, removed `Job` transcription fields, or compatibility aliases.
|
||||
- The focused tests and full test suite pass.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Database migrations or preservation of V1 data
|
||||
- Legacy compatibility code
|
||||
- Database engine or session-layer rewrites
|
||||
- UI redesign, batch orchestration, worker concurrency, deployment, and operational runbooks
|
||||
@@ -19,7 +19,7 @@ Read [architecture_v2.md](architecture_v2.md) first for technical overview and s
|
||||
## Technical Stack
|
||||
|
||||
* **Application Web Framework:** FastAPI + NiceGUI
|
||||
* **Persistence Engine:** PostgreSQL 13+
|
||||
* **Persistence Engine:** PostgreSQL 18+
|
||||
* **Data Validation & Schemas:** Pydantic V2
|
||||
* **Concurrency & Workers:** Python `asyncio` worker pool with `asyncio.Semaphore`
|
||||
* **Vision Providers:** OpenAI (GPT-4o) and Anthropic (Claude 3.5 Sonnet) via native SDKs
|
||||
@@ -38,8 +38,8 @@ Read [architecture_v2.md](architecture_v2.md) first for technical overview and s
|
||||
## Documentation Index
|
||||
|
||||
- System Overview (this document)
|
||||
- [System Design Intent](intent.md)
|
||||
- [Transcription Methodology](transcription_methodology.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- [System Architecture](architecture_v2.md)
|
||||
- [System Requirements](requirements_v2.md)
|
||||
- [Data model](schema_v2.md)
|
||||
@@ -31,8 +31,8 @@ This document captures the **Version 2 baseline requirements** for the productio
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v2.md)
|
||||
- [System Design Intent](intent.md)
|
||||
- [Transcription Methodology](transcription_methodology.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- [System Architecture](architecture_v2.md)
|
||||
- System Requirements (this document)
|
||||
- [Data model](schema_v2.md)
|
||||
@@ -50,7 +50,7 @@ erDiagram
|
||||
JOB {
|
||||
UUID id PK
|
||||
UUID document_id FK
|
||||
VARCHAR status "queued | processing | completed | partial_success | failed"
|
||||
VARCHAR status "queued | processing | transcribed | completed | partial_success | failed"
|
||||
INTEGER retry_count
|
||||
TEXT provider
|
||||
TEXT model
|
||||
@@ -97,6 +97,7 @@ erDiagram
|
||||
### Page-Level Execution & AI Outputs
|
||||
|
||||
* Execution Granularity: Every single image execution by an AI model produces a dedicated record in job_source.
|
||||
* Source vs Execution Status: `source` does not carry a `status` column. Per-source execution state is tracked in `job_source.status` (`pending`, `transcribed`, `failed`).
|
||||
* Point-in-Time Auditability: job_source.raw_api_response stores the unparsed REST response envelope for that specific image page call. job_source.ai_metadata stores spatial bounding boxes, token usage, and layout details for that specific image page call.
|
||||
* Active Output Caching: Upon successful completion of an image call, source.raw_transcription is updated with the latest output string from job_source.raw_transcription for fast UI rendering.
|
||||
|
||||
@@ -126,8 +127,8 @@ erDiagram
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v2.md)
|
||||
- [System Design Intent](intent.md)
|
||||
- [Transcription Methodology](transcription_methodology.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- [System Architecture](architecture_v2.md)
|
||||
- [System Requirements](requirements_v2.md)
|
||||
- Data model (this document)
|
||||
@@ -0,0 +1,142 @@
|
||||
# System Architecture (Version 3)
|
||||
|
||||
This document describes the V3 production architecture of the personal historical-document transcription system.
|
||||
|
||||
## Architecture Objectives
|
||||
|
||||
* Preserve source material as immutable transcribed text alongside page-level spatial AI metadata and complete provider API envelopes.
|
||||
* Support batching multi-image and folder uploads cleanly into sequential pages (`page_number`).
|
||||
* Capture complete input prompt provenance (`system_prompt`, `user_prompt`, `prompt_hash`) and execution parameters (`temperature`, `top_p`) at submission time on `Job`.
|
||||
* Leverage asynchronous worker pools (`asyncio`) for parallel single-image API execution bounded by rate limiters (`asyncio.Semaphore`).
|
||||
* Maintain relational data-model portability across the supported backends by using SQLModel/SQLAlchemy and compatibility types so the same domain schema works in SQLite for local development/testing and PostgreSQL in production.
|
||||
* Keep operator tooling and local maintenance workflows OS-independent by using Python or other cross-platform interfaces for canonical project automation.
|
||||
* Verify image asset integrity via SHA-256 file hashing (`file_hash`) while storing binary assets on the local filesystem.
|
||||
* Standardize all data validation, API parsing, and database models on **Pydantic V2** and **SQLModel**.
|
||||
* Support rich historical attribution (multi-author and multi-recipient relationships via `DocumentPerson`).
|
||||
|
||||
## Runtime Topology
|
||||
|
||||
The V3 runtime operates as an asynchronous Python application:
|
||||
|
||||
* FastAPI + NiceGUI web application process.
|
||||
* In-process `asyncio` background task orchestrator for parallel API execution.
|
||||
* Relational persistence via SQLModel / SQLAlchemy, using SQLite for local development/testing and PostgreSQL as the production persistence target.
|
||||
* Pydantic V2 validation layer wrapping API payloads, prompt configurations, and JSON metadata schemas.
|
||||
* Cross-platform operator workflows implemented in Python so core local operations run consistently on Windows, Linux, and macOS.
|
||||
|
||||
^^^mermaid
|
||||
flowchart LR
|
||||
U[Browser User] --> A[FastAPI + NiceGUI App]
|
||||
A --> W[Asyncio Worker Engine]
|
||||
A --> DB[(Relational DB\nSQLite / PostgreSQL)]
|
||||
W --> P[Vision Provider APIs\nOpenAI / Claude / OpenRouter]
|
||||
W --> DB
|
||||
^^^
|
||||
|
||||
## Lifecycle Ownership
|
||||
|
||||
Application lifespan owns runtime setup/teardown:
|
||||
|
||||
* Initialize environment logging, directory paths, and Pydantic configuration.
|
||||
* Manage asynchronous database engine connection pools (`aiosqlite` or `asyncpg`).
|
||||
* Execute database bootstrap (`SQLModel.metadata.create_all()`) or migrations.
|
||||
* Recover stale or interrupted processing jobs on startup.
|
||||
* Manage graceful shutdown of active `asyncio` worker 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.py`
|
||||
* `src/transcription/worker.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
* Batch orchestration and status transitions (`queued` -> `processing` -> `transcribed` | `partial_success` | `failed`).
|
||||
* Parallel single-image API execution using `asyncio.gather` bounded by `asyncio.Semaphore`.
|
||||
* Resolve prompt configuration at submission time and persist frozen snapshot fields on `Job`.
|
||||
* Pydantic schema parsing and validation prior to database storage.
|
||||
|
||||
### Domain & Service Layer
|
||||
|
||||
* `src/transcription/db/models.py` (SQLModel schema definitions for Document, Source, Job, JobSource, Person, DocumentPerson)
|
||||
* `src/transcription/services/*.py` (Transactional operations for `Document`, `Person`, `Source`, `Job`, and `JobSource`)
|
||||
|
||||
### Infrastructure Layer
|
||||
|
||||
* `src/transcription/db/**` (Async database session factory, engine creation, and JSON dialect abstractions)
|
||||
* `src/transcription/providers/**` (OpenAI, Anthropic, and OpenRouter Vision SDK adapters)
|
||||
|
||||
## Processing Workflow
|
||||
|
||||
1. User uploads a folder or batch of images for a `Document`.
|
||||
2. System hashes each image file (SHA-256), writes image files to filesystem storage, and creates `Document`, `Job(status='queued')`, and ordered `Source` pages (`page_number = 1..N`).
|
||||
3. Worker claims job, sets `Job.status = 'processing'`, and spawns parallel `asyncio` tasks bounded by semaphore.
|
||||
4. Each task reads the frozen prompt snapshot from `Job` and calls Vision API for a **single** `Source` image.
|
||||
5. On task completion:
|
||||
* Writes a `JobSource` record containing `status='transcribed'`, `raw_transcription`, operational `ai_metadata`, and complete unedited `raw_api_response`.
|
||||
* Caches active output text to `Source.raw_transcription`.
|
||||
|
||||
|
||||
6. On page failure:
|
||||
* Writes `JobSource` record with `status='failed'` and `error_detail`.
|
||||
|
||||
|
||||
7. Once all page tasks resolve:
|
||||
* Marks `Job.status` as `transcribed` (100% success), `partial_success` (at least 1 success, 1 failure), or `failed` (all failed).
|
||||
|
||||
|
||||
|
||||
## Domain Ownership & Invariants
|
||||
|
||||
* **Immutable AI Outputs:** `source.raw_transcription` and `job_source.raw_transcription` store original, point-in-time machine output and are immutable.
|
||||
* **Complete Input & Output Provenance:** Every `job` stores the exact frozen input configuration sent to the model, and every `job_source` stores per-page output evidence including the complete REST response envelope returned.
|
||||
* **Inlined Revisions:** Human corrections occur on `source.revised_text`. UI renders `COALESCE(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
|
||||
|
||||
* `Document` has many `Source` pages, many `Job` runs, and many `Person` records via `DocumentPerson` junction (`author` or `recipient`).
|
||||
* `Source` belongs to one `Document` and can be processed across many `JobSource` executions.
|
||||
* `Job` has many `JobSource` execution records.
|
||||
* `JobSource` holds page-level execution status, output text, and raw response JSON.
|
||||
|
||||
## Test Strategy
|
||||
|
||||
* Unit tests for SQLModel/Pydantic V2 models, JSON cross-dialect serialization, and file hashing functions.
|
||||
* Integration tests for async database connection handling, session management, and queries.
|
||||
* Async workflow tests using mock AI providers to verify `partial_success`, page-level failure isolation, and retry logic.
|
||||
* UI integration tests for multi-page rendering and person attribution management.
|
||||
|
||||
---
|
||||
|
||||
## Technology References
|
||||
|
||||
* [FastAPI documentation](https://fastapi.tiangolo.com/)
|
||||
* [NiceGUI documentation](https://nicegui.io/documentation)
|
||||
* [SQLModel documentation](https://sqlmodel.tiangolo.com/)
|
||||
* [SQLAlchemy Async I/O documentation](https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html)
|
||||
* [Python asyncio](https://www.google.com/search?q=https://docs.python.org/3/library/asyncio.html%23module-asyncio)
|
||||
* [Pydantic Validation](https://pydantic.dev/docs/validation/latest/get-started/)
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v3.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- System Architecture (this document)
|
||||
- [System Requirements](requirements_v3.md)
|
||||
- [Data model](schema_v3.md)
|
||||
- [Error Handling Policy](error_handling_v3.md)
|
||||
- [Implementation Plan](implementation_plan_v3.md)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# Error Handling Policy (Version 3)
|
||||
|
||||
This document defines the canonical error-handling policy for the v3 document transcription system.
|
||||
|
||||
## Error Handling Objectives
|
||||
|
||||
* Make failures visible in clear, actionable language at both the document and individual page levels.
|
||||
* Support **isolated failure handling** in multi-image batches so single page errors do not crash an entire batch job.
|
||||
* Preserve diagnostic detail (Pydantic validation errors, raw provider REST envelopes, exact input prompts) in generic database JSON structures for fast troubleshooting.
|
||||
* Ensure consistent error envelope structure across API, UI, and async worker boundaries.
|
||||
|
||||
## Scope And Authority
|
||||
|
||||
Governs error behavior across NiceGUI pages, FastAPI routes, service orchestration, `asyncio` background tasks, database interactions, and AI provider adapters.
|
||||
|
||||
## Error Taxonomy
|
||||
|
||||
| Category | Definition | Retriable |
|
||||
| --- | --- | --- |
|
||||
| `validation_error` | Pydantic payload or parameter schema validation failure | no |
|
||||
| `user_input_error` | Unacceptable user file (unsupported image type, corrupt file) | no |
|
||||
| `not_found_error` | Requested resource (`Document`, `Source`, `Person`, `Job`) missing | no |
|
||||
| `conflict_error` | Operation violates state constraints (e.g., duplicate `document_person` role) | no |
|
||||
| `external_provider_error` | AI Provider API failure (rate limit, vision execution error) | yes |
|
||||
| `infrastructure_transient_error` | Temporary DB connection reset or HTTP timeout | yes |
|
||||
| `infrastructure_persistent_error` | Database down, missing API credentials, misconfiguration | no |
|
||||
| `internal_unexpected_error` | Uncaught Python exception or logic defect | no |
|
||||
|
||||
## Async Batch & Page-Level Error Behavior
|
||||
|
||||
In multi-image `asyncio` batch processing:
|
||||
|
||||
1. **Page Isolation:** Exceptions caught during individual page calls are trapped within the `asyncio` task wrapper.
|
||||
2. **Page Record Logging:** Page failure details, along with the prompt inputs and hyperparameters attempted, are written directly to `job_source.error_detail` and `job_source.status = 'failed'`.
|
||||
3. **Batch Aggregate State:**
|
||||
* If **all** page tasks succeed -> `job.status = 'completed'`.
|
||||
* If **some** page tasks fail -> `job.status = 'partial_success'`.
|
||||
* If **all** page tasks fail -> `job.status = 'failed'`.
|
||||
|
||||
|
||||
4. **Retry Strategy:** The UI exposes a "Retry Failed Pages" option for `partial_success` jobs, which spawns a new targeted `Job` containing *only* the `Source` IDs marked as `failed`.
|
||||
|
||||
## API Error Response Contract
|
||||
|
||||
API error responses return a structured JSON envelope:
|
||||
^^^json
|
||||
{
|
||||
"error_id": "err_uuid_12345",
|
||||
"category": "validation_error",
|
||||
"message": "The uploaded payload failed schema validation.",
|
||||
"suggestion": "Check file format and metadata fields, then try again.",
|
||||
"details": {
|
||||
"pydantic_errors": [...]
|
||||
},
|
||||
"timestamp": "2026-08-08T15:00:00Z"
|
||||
}
|
||||
^^^
|
||||
|
||||
HTTP Status Mappings:
|
||||
|
||||
* `validation_error`, `user_input_error` -> `400`
|
||||
* `not_found_error` -> `404`
|
||||
* `conflict_error` -> `409`
|
||||
* `external_provider_error` -> `502` / `503`
|
||||
* `infrastructure_transient_error` -> `503`
|
||||
* `infrastructure_persistent_error`, `internal_unexpected_error` -> `500`
|
||||
|
||||
---
|
||||
|
||||
## Technology References
|
||||
|
||||
* [FastAPI documentation](https://fastapi.tiangolo.com/)
|
||||
* [NiceGUI documentation](https://nicegui.io/documentation)
|
||||
* [SQLModel documentation](https://sqlmodel.tiangolo.com/)
|
||||
* [Python asyncio](https://www.google.com/search?q=https://docs.python.org/3/library/asyncio.html%23module-asyncio)
|
||||
* [Pydantic Validation](https://pydantic.dev/docs/validation/latest/get-started/)
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v3.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- [System Architecture](architecture_v3.md)
|
||||
- [System Requirements](requirements_v3.md)
|
||||
- [Data model](schema_v3.md)
|
||||
- Error Handling Policy (this document)
|
||||
- [Implementation Plan](implementation_plan_v3.md)
|
||||
@@ -0,0 +1,81 @@
|
||||
# Implementation Plan (Version 3)
|
||||
|
||||
## Goal
|
||||
|
||||
Replace the current v2 SQLModel schema with the approved v3 schema and make sure every database operation works through the existing async SQLAlchemy/SQLModel session layer.
|
||||
|
||||
Use a fresh database. There will be no migrations, data conversion, legacy compatibility shims, or parallel v2/v3 code paths.
|
||||
|
||||
## Current Project Impact
|
||||
|
||||
* `src/transcription/db/models.py` defines the SQLModel tables. It must be updated to match the approved v3 schema (`Document`, `Person`, `DocumentPerson`, `Source`, `Job`, `JobSource`).
|
||||
* The v3 target adds frozen submission-time prompt snapshot fields (`prompt_name`, `prompt_hash`, `system_prompt`, `user_prompt`, `temperature`, `top_p`) to `Job` and full output payloads (`raw_api_response`, `ai_metadata`) to `JobSource`.
|
||||
* The v3 target adds image asset verification fields (`file_hash`, `file_size_bytes`) to `Source`.
|
||||
* Database operations must utilize `JSONBCompat` and the existing SQLModel/SQLAlchemy abstractions to preserve the same logical schema and JSON behavior across the supported backends, while keeping PostgreSQL as the intended production database.
|
||||
* Async CRUD lives in `DocumentService`, `JobService`, `TranscriptionService`, and upload helpers. Their queries and relationship loading must be updated for v3 fields.
|
||||
* Canonical operator tooling must remain OS-independent; safety workflows such as destructive-test backup and restore should run through Python or other cross-platform entry points rather than platform-specific shells.
|
||||
|
||||
## Implementation
|
||||
|
||||
### 1. Update the Schema and Domain Models
|
||||
|
||||
* Replace the models in `src/transcription/db/models.py` with the approved v3 tables, enums, relationships, foreign keys, constraints, and indexes.
|
||||
* Ensure all JSON fields use `JSONBCompat` for dialect portability across SQLite and PostgreSQL.
|
||||
* Keep `SQLModel.metadata.create_all()` as the schema bootstrap for fresh databases.
|
||||
* Delete `_ensure_sqlite_compat_columns()` and all legacy schema patching from `src/transcription/db/operations.py`.
|
||||
* Keep the Python models and `docs/schema_v3.md` perfectly synchronized.
|
||||
|
||||
### 2. Update Data Services and Async Worker Layer
|
||||
|
||||
* Update job creation and worker orchestration so prompt configuration is resolved at submission and frozen onto `Job` (`prompt_name`, `prompt_hash`, `system_prompt`, `user_prompt`, `temperature`, `top_p`) before execution starts.
|
||||
* Update `TranscriptionService` and provider adapters to store the complete unedited API REST response dictionary into `job_source.raw_api_response` alongside operational metrics in `job_source.ai_metadata`.
|
||||
* Update upload handlers to calculate and store file metadata (`file_hash` via SHA-256, `file_size_bytes`) on `Source` records during file ingestion.
|
||||
* Remove legacy single-source compatibility flows so worker paths persist per-page outcomes only through `JobSource` updates.
|
||||
|
||||
### 3. Update Integration Tests and Mock AI Providers
|
||||
|
||||
* Update mock provider fixtures in test suites to return realistic complete API response envelopes.
|
||||
* Verify test coverage for `JSONBCompat` field writes and reads under SQLite in-memory test databases.
|
||||
* Add assertions in async workflow tests to verify frozen prompt snapshot fields on `Job`, plus per-page failure isolation and output evidence on `JobSource`.
|
||||
|
||||
### 4. Update the UI for the v3 Schema
|
||||
|
||||
* Review the UI components and views displaying document, job, person, and source data so they reference v3 schema properties instead of v2 relationships.
|
||||
* Ensure the UI correctly renders `COALESCE(revised_text, raw_transcription)` for page viewing and inline editing.
|
||||
* Ensure resubmit actions only queue failed pages and preserve frozen prompt snapshot behavior on the existing `Job`.
|
||||
* Consider the guidance in `docs/ui_style_guide.md` when making UI changes so updated views remain consistent with the project’s visual conventions.
|
||||
|
||||
### 5. Keep Operational Tooling Portable
|
||||
|
||||
* Implement destructive-test backup and restore workflows in Python so the canonical path runs on Windows, Linux, and macOS.
|
||||
* Avoid making core developer or recovery procedures depend on PowerShell-only or shell-specific semantics.
|
||||
* Keep operational documentation aligned with the cross-platform command path used by the repository.
|
||||
|
||||
## Done When
|
||||
|
||||
* A fresh database is created directly from the v3 SQLModel metadata.
|
||||
* Frozen prompt input provenance is captured on `Job` for each submission, and full per-page output evidence is captured on `JobSource` for every AI execution task.
|
||||
* The focused tests and full test suite pass on both SQLite and PostgreSQL backends.
|
||||
* Canonical operator workflows required for development and destructive-test recovery run without a Windows-only shell dependency.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
* Database migrations or preservation of v2 data
|
||||
* Legacy compatibility code
|
||||
* UI redesign, batch orchestration, worker concurrency, deployment, and operational runbooks
|
||||
|
||||
---
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v3.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- [System Architecture](architecture_v3.md)
|
||||
- [System Requirements](requirements_v3.md)
|
||||
- [Data model](schema_v3.md)
|
||||
- [Error Handling Policy](error_handling_v3.md)
|
||||
- Implementation Plan (this document)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Document Transcription System Overview (Version 3)
|
||||
|
||||
This project is a personal-scale application for transcribing, indexing, and preserving historical family documents, letters, postcards, and journals.
|
||||
|
||||
## Start Here
|
||||
|
||||
Read [architecture_v3.md](https://www.google.com/search?q=architecture_v3.md) first for technical overview and system design.
|
||||
|
||||
## Core V3 Capabilities
|
||||
|
||||
* **Folder & Multi-Image Ingestion:** Upload one or more images that map sequentially (`page_number`) under a single `Document`.
|
||||
* **Parallel Async AI Vision Engine:** Concurrently process single-page image transcriptions using Python `asyncio` bounded by rate limiters.
|
||||
* **Portable Relational Storage:** SQLModel and SQLAlchemy preserve a portable relational model across the supported backends, with SQLite for local development/testing and PostgreSQL as the production database target.
|
||||
* **Cross-Platform Operations:** Canonical developer and recovery workflows run through Python-based, OS-independent tooling rather than platform-specific shell scripts.
|
||||
* **Complete Auditability & Provenance:** Capture frozen submission-time input prompts (`system_prompt`, `user_prompt`) and hyperparameters (`temperature`, `top_p`) on `Job`, plus per-page operational metrics (`ai_metadata`) and full provider response envelopes (`raw_api_response`) on `JobSource`.
|
||||
* **Asset Integrity Tracking:** Calculate and store cryptographic hashes (SHA-256) and file sizes on `Source` image records while preserving clean filesystem storage.
|
||||
* **Pydantic V2 Validation:** End-to-end type safety, DB row mapping, and JSON payload validation.
|
||||
* **Historical Person Management:** Track authors and recipients across documents with rich biographical entities (`Person`).
|
||||
* **Page-Level Execution Auditing & Revisions:** Store immutable point-in-time machine output per run while enabling inline human corrections (`revised_text`).
|
||||
* **Partial Failure Recovery:** Bounded batch execution that isolates single-page API errors (`partial_success`) for simple retries.
|
||||
|
||||
## Technical Stack
|
||||
|
||||
* **Application Web Framework:** FastAPI + NiceGUI
|
||||
* **Persistence Engine:** SQLModel / SQLAlchemy (SQLite for development/testing, PostgreSQL for production)
|
||||
* **Data Validation & Schemas:** Pydantic V2
|
||||
* **Concurrency & Workers:** Python `asyncio` worker pool with `asyncio.Semaphore`
|
||||
* **Vision Providers:** OpenAI, Anthropic, and OpenRouter Vision models via native SDK adapters
|
||||
|
||||
---
|
||||
|
||||
## Technology References
|
||||
|
||||
* [FastAPI documentation](https://fastapi.tiangolo.com/)
|
||||
* [NiceGUI documentation](https://nicegui.io/documentation)
|
||||
* [SQLModel documentation](https://sqlmodel.tiangolo.com/)
|
||||
* [Python asyncio](https://www.google.com/search?q=https://docs.python.org/3/library/asyncio.html%23module-asyncio)
|
||||
* [Pydantic Validation](https://pydantic.dev/docs/validation/latest/get-started/)
|
||||
|
||||
## Documentation Index
|
||||
|
||||
- System Overview (this document)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- [System Architecture](architecture_v3.md)
|
||||
- [System Requirements](requirements_v3.md)
|
||||
- [Data model](schema_v3.md)
|
||||
- [Error Handling Policy](error_handling_v3.md)
|
||||
- [Implementation Plan](implementation_plan_v3.md)
|
||||
@@ -0,0 +1,45 @@
|
||||
# Document Transcription System Requirements (Version 3)
|
||||
|
||||
This document captures the **Version 3 baseline requirements** for the production implementation.
|
||||
|
||||
## Requirements Model
|
||||
|
||||
| ID | Category | Requirement | Verify Method |
|
||||
| --- | --- | --- | --- |
|
||||
| REQ-0 | System | Provide end-to-end multi-page document transcription with persistent, inspectable async job states. | demonstration |
|
||||
| REQ-1 | Functional | Allow users to upload multi-image batches as sequential `Source` pages under a `Document`. | test |
|
||||
| REQ-2 | Functional | Process multi-page jobs asynchronously using an `asyncio` worker pool bounded by rate limits. | test |
|
||||
| REQ-3 | Functional | Persist frozen submission-time execution parameters and full input prompts (`system_prompt`, `user_prompt`, `prompt_name`, `prompt_hash`, `temperature`, `top_p`) on `Job`, and persist page-level output responses (`raw_transcription`, `ai_metadata`, `raw_api_response`) on `JobSource`. | test |
|
||||
| REQ-4 | Functional | Support job states (`queued`, `processing`, `completed`, `partial_success`, `failed`) and page states (`pending`, `transcribed`, `failed`). | inspection |
|
||||
| REQ-5 | Functional | Allow users to manage historical `Person` records and link multiple authors/recipients to a `Document` via `DocumentPerson`. | test |
|
||||
| REQ-6 | Functional | Maintain immutable original machine output on `Source.raw_transcription` while permitting inline human edits on `Source.revised_text`. | test |
|
||||
| REQ-7 | Data Constraint | Use SQLModel/SQLAlchemy to preserve a portable relational domain model and compatible data shape across the supported backends, with SQLite for local development/testing and PostgreSQL as the production system of record. | inspection |
|
||||
| REQ-8 | Data Constraint | Validate all API requests, database rows, and JSON structures using Pydantic V2 schemas and SQLModel. | test |
|
||||
| REQ-9 | Interface | Render multi-page transcriptions sequentially by `page_number` in the web UI with author/recipient metadata. | demonstration |
|
||||
| REQ-10 | Operations | Allow operators to resubmit only failed pages for queued reprocessing while preserving the frozen prompt snapshot on the existing `Job`. | test |
|
||||
| REQ-11 | Data Constraint | Calculate and store cryptographic file hashes (SHA-256) and file sizes for uploaded source images to track asset integrity. | test |
|
||||
| REQ-12 | Operations Constraint | Keep core development, testing, restore, and recovery workflows OS-independent across Windows, Linux, and macOS; do not require a platform-specific shell for canonical project processes. | inspection |
|
||||
|
||||
## Element Satisfaction Mapping
|
||||
|
||||
* **UI (NiceGUI):** Satisfies REQ-1, REQ-5, REQ-6, REQ-9, REQ-10.
|
||||
* **API (FastAPI):** Satisfies REQ-1, REQ-4, REQ-5, REQ-8.
|
||||
* **WORKER (asyncio):** Satisfies REQ-2, REQ-3, REQ-4, REQ-10.
|
||||
* **PERSISTENCE (SQLModel/SQLAlchemy):** Satisfies REQ-3, REQ-6, REQ-7, REQ-11.
|
||||
* **MODELS (Pydantic V2 / SQLModel):** Satisfies REQ-8.
|
||||
* **OPERATIONS TOOLING (Python / OS-neutral automation):** Satisfies REQ-12.
|
||||
|
||||
---
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v3.md)
|
||||
- [System Design Intent](invariant/intent.md)
|
||||
- [Transcription Methodology](invariant/transcription_methodology.md)
|
||||
- [System Architecture](architecture_v3.md)
|
||||
- System Requirements (this document)
|
||||
- [Data model](schema_v3.md)
|
||||
- [Error Handling Policy](error_handling_v3.md)
|
||||
- [Implementation Plan](implementation_plan_v3.md)
|
||||
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
# Database Schema (Version 3)
|
||||
|
||||
This document describes the relational schema for the transcription platform. It incorporates multi-image batch orchestration, page-level execution tracking, many-to-many author/recipient attribution, submission-time prompt snapshot capture, and raw API payload evidence for archival auditing.
|
||||
|
||||
The schema uses generic JSON columns compatible with SQLite in local development and PostgreSQL native JSONB/UUID types in production.
|
||||
|
||||
## Entity Relationship Diagram
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
PERSON {
|
||||
UUID id PK
|
||||
TEXT full_name
|
||||
TEXT display_name
|
||||
TEXT maiden_name
|
||||
DATE birth_date
|
||||
TEXT birth_date_raw
|
||||
TEXT birth_place
|
||||
DATE death_date
|
||||
TEXT death_date_raw
|
||||
TEXT death_place
|
||||
TEXT biography
|
||||
TEXT portrait_path
|
||||
JSONB metadata
|
||||
TIMESTAMPTZ created_at
|
||||
TIMESTAMPTZ updated_at
|
||||
}
|
||||
|
||||
DOCUMENT {
|
||||
UUID id PK
|
||||
TEXT name
|
||||
TEXT document_type
|
||||
DATE document_date
|
||||
TEXT document_date_raw
|
||||
TEXT location_created
|
||||
TEXT notes
|
||||
TEXT archive_identifier
|
||||
TIMESTAMPTZ created_at
|
||||
TIMESTAMPTZ updated_at
|
||||
}
|
||||
|
||||
DOCUMENT_PERSON {
|
||||
UUID id PK
|
||||
UUID document_id FK
|
||||
UUID person_id FK
|
||||
VARCHAR role "author | recipient"
|
||||
TIMESTAMPTZ created_at
|
||||
}
|
||||
|
||||
JOB {
|
||||
UUID id PK
|
||||
UUID document_id FK
|
||||
VARCHAR status "queued | processing | transcribed | completed | partial_success | failed"
|
||||
INTEGER retry_count
|
||||
TEXT provider
|
||||
TEXT model
|
||||
TEXT prompt_name
|
||||
TEXT prompt_hash
|
||||
TEXT system_prompt
|
||||
TEXT user_prompt
|
||||
FLOAT temperature
|
||||
FLOAT top_p
|
||||
TIMESTAMPTZ date_created
|
||||
TIMESTAMPTZ date_updated
|
||||
}
|
||||
|
||||
SOURCE {
|
||||
UUID id PK
|
||||
UUID document_id FK
|
||||
INTEGER page_number
|
||||
TEXT upload_name
|
||||
TEXT filename
|
||||
TEXT file_path
|
||||
TEXT file_hash
|
||||
BIGINT file_size_bytes
|
||||
TEXT raw_transcription
|
||||
TEXT revised_text
|
||||
TIMESTAMPTZ date_uploaded
|
||||
TIMESTAMPTZ date_revised
|
||||
}
|
||||
|
||||
JOB_SOURCE {
|
||||
UUID id PK
|
||||
UUID job_id FK
|
||||
UUID source_id FK
|
||||
VARCHAR status "pending | transcribed | failed"
|
||||
TEXT raw_transcription
|
||||
JSONB ai_metadata
|
||||
JSONB raw_api_response
|
||||
TEXT error_detail
|
||||
TIMESTAMPTZ executed_at
|
||||
}
|
||||
|
||||
DOCUMENT ||--o{ DOCUMENT_PERSON : "has_people"
|
||||
PERSON ||--o{ DOCUMENT_PERSON : "participates_in"
|
||||
DOCUMENT ||--o{ JOB : "has_jobs"
|
||||
DOCUMENT ||--o{ SOURCE : "contains_pages"
|
||||
JOB ||--o{ JOB_SOURCE : "executes"
|
||||
SOURCE ||--o{ JOB_SOURCE : "processed_in"
|
||||
```
|
||||
|
||||
## Domain Invariants & Provenance Rules
|
||||
|
||||
### Page-Level Execution & AI Outputs
|
||||
|
||||
* **Execution Granularity:** Every single image execution attempt by an AI model produces a dedicated record in `job_source`.
|
||||
* **Submission Snapshot Provenance:** Every `job` captures the frozen prompt identifier details (`prompt_name`, `prompt_hash`), full prompt text strings (`system_prompt`, `user_prompt`), and hyperparameters (`temperature`, `top_p`) at submission time.
|
||||
* **Point-in-Time Output Auditability:** `job_source.raw_api_response` stores the complete, unedited provider REST response envelope for that specific image page call. `job_source.ai_metadata` stores spatial bounding boxes, normalized token usage, latency, and cost details for fast querying.
|
||||
* **Active Output Caching:** Upon successful completion of an image call, `source.raw_transcription` is updated with the latest output string from `job_source.raw_transcription` for fast UI rendering.
|
||||
|
||||
### Image Storage & Integrity
|
||||
|
||||
* **Filesystem Storage:** Binary images are stored on disk in the local file system. The `source` table holds the relative `file_path`.
|
||||
* **File Integrity Tracking:** `source` captures `file_hash` (SHA-256) and `file_size_bytes` at upload time to guarantee document file integrity and duplicate checking over long-term preservation.
|
||||
|
||||
### Page Ordering & Revisions
|
||||
|
||||
* **Sequential Integrity:** `source.page_number` dictates page ordering within a document. Reads assembling full documents must query `ORDER BY source.document_id, source.page_number ASC`.
|
||||
* **Inlined Human Corrections:** User edits occur at the page level inside `source.revised_text`. `source.raw_transcription` remains immutable. If `source.revised_text` is non-null, application frontends must render `source.revised_text`.
|
||||
|
||||
### Async Job Lifecycle & Failure Isolation
|
||||
|
||||
* **Batch Orchestrator:** A job represents an overarching execution run across one or more source images belonging to a document.
|
||||
* **Isolated Failures:** API requests run concurrently (e.g., using `asyncio`). A failure on page 3 does not invalidate successful transcriptions on page 1 or 2.
|
||||
* **Job States:**
|
||||
* `queued`: Created, awaiting worker execution.
|
||||
* `processing`: Concurrent HTTP tasks actively running.
|
||||
* `completed`: 100% of linked `job_source` tasks succeeded (`transcribed`).
|
||||
* `partial_success`: At least one `job_source` succeeded and at least one failed.
|
||||
* `failed`: All linked `job_source` tasks failed or a job-level runtime error occurred.
|
||||
|
||||
|
||||
|
||||
### Attribution & Person Roles
|
||||
|
||||
* **Multi-Person Roles:** Documents support zero, one, or many authors and recipients linked via `document_person`.
|
||||
* **Role Uniqueness:** `(document_id, person_id, role)` must be unique to prevent duplicate role tagging.
|
||||
@@ -0,0 +1,147 @@
|
||||
# System Architecture (Version 4)
|
||||
|
||||
This document describes the production architecture of the document transcription system.
|
||||
|
||||
## Architecture Objectives
|
||||
|
||||
- Preserve original source material and immutable machine transcription output.
|
||||
- Support batching one or more images into ordered multi-page documents.
|
||||
- Capture complete submission-time prompt provenance and per-page provider response evidence.
|
||||
- Execute page transcription concurrently with bounded `asyncio` workers.
|
||||
- Maintain relational portability across SQLite and PostgreSQL.
|
||||
- Keep operator workflows cross-platform and Python-driven.
|
||||
- Support many-to-many document-person relationships with extensible roles.
|
||||
- Support registry-driven document type classification.
|
||||
- Enforce relationship-role exclusivity rules consistently across UI, API, and persistence boundaries.
|
||||
|
||||
## Runtime Topology
|
||||
|
||||
The runtime operates as an asynchronous Python application:
|
||||
|
||||
- FastAPI + NiceGUI web application process.
|
||||
- In-process `asyncio` worker engine for transcription execution.
|
||||
- Relational persistence via SQLModel / SQLAlchemy.
|
||||
- Pydantic V2 validation across API payloads, prompt configuration, and structured metadata.
|
||||
|
||||
^^^mermaid
|
||||
flowchart LR
|
||||
U[Browser User] --> A[FastAPI + NiceGUI App]
|
||||
A --> W[Asyncio Worker Engine]
|
||||
A --> DB[(Relational DB)]
|
||||
W --> P[Vision Provider APIs]
|
||||
W --> DB
|
||||
^^^
|
||||
|
||||
## Lifecycle Ownership
|
||||
|
||||
Application lifespan owns runtime setup and teardown:
|
||||
|
||||
- Initialize logging, settings, directories, and prompt configuration.
|
||||
- Manage asynchronous database engine connection pools.
|
||||
- Execute database bootstrap or migrations.
|
||||
- Recover stale or interrupted jobs on startup.
|
||||
- Manage graceful shutdown of active background tasks.
|
||||
|
||||
## Layered Module Structure
|
||||
|
||||
### Interface Layer
|
||||
|
||||
- `src/transcription/ui/**`
|
||||
- `src/transcription/api/**`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Render document, source, person, job, and classification views.
|
||||
- Accept user input for uploads, editing, linking, and revisions.
|
||||
- Present structured validation and conflict feedback.
|
||||
|
||||
### Application and Async Worker Layer
|
||||
|
||||
- `src/transcription/services/workflows.py`
|
||||
- `src/transcription/worker.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Orchestrate uploads, job creation, and status transitions.
|
||||
- Execute per-page provider calls through bounded concurrency.
|
||||
- Persist page-level outcomes and update aggregate job state.
|
||||
|
||||
### Domain and Service Layer
|
||||
|
||||
- `src/transcription/db/models.py`
|
||||
- `src/transcription/services/*.py`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Manage transactional operations for documents, people, types, links, sources, jobs, and job sources.
|
||||
- Apply deterministic conflict handling for relationship-role writes.
|
||||
- Use set-based synchronization for many-to-many relationship updates.
|
||||
- Resolve and validate registry-backed document types.
|
||||
|
||||
### Infrastructure Layer
|
||||
|
||||
- `src/transcription/db/**`
|
||||
- `src/transcription/providers/**`
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Provide async database sessions and engine configuration.
|
||||
- Provide provider adapters for vision model execution.
|
||||
|
||||
## Core Workflows
|
||||
|
||||
### 1. Multi-Page Transcription
|
||||
|
||||
1. User uploads one or more images for a `Document`.
|
||||
2. System stores files, hashes them, creates ordered `Source` rows, and creates a `Job`.
|
||||
3. Worker claims the job, marks it `processing`, and executes page calls concurrently.
|
||||
4. Each page writes a `JobSource` result with raw output, metadata, and full provider response evidence.
|
||||
5. Aggregate status becomes `completed`, `partial_success`, or `failed`.
|
||||
|
||||
### 2. Document-Person Relationship Management
|
||||
|
||||
1. User opens a document or person edit flow.
|
||||
2. UI loads existing links grouped by role.
|
||||
3. User adds or removes people within one or more roles.
|
||||
4. Service computes add/remove deltas rather than replacing all links blindly.
|
||||
5. Conflict checks enforce exclusivity policy before persistence commits.
|
||||
|
||||
### 3. Document Type Management
|
||||
|
||||
1. User selects a registry-backed document type for a document.
|
||||
2. Service resolves the stable type code or id.
|
||||
3. Persistence stores the `document_type_id` reference.
|
||||
4. Inactive types remain valid for historical rows but are excluded from default selectors.
|
||||
|
||||
## Domain Invariants
|
||||
|
||||
- `Source.raw_transcription` stores immutable machine output.
|
||||
- Human corrections occur only in `Source.revised_text`.
|
||||
- Prompt and parameter provenance is frozen on `Job` at submission time.
|
||||
- Provider output evidence is stored on `JobSource` for each page execution.
|
||||
- `DocumentPerson` links are unique for `(document_id, person_id, role_id)`.
|
||||
- Configured exclusive role pairs cannot coexist for the same `(document_id, person_id)`.
|
||||
- Relationship mutations are deterministic and set-based.
|
||||
- `DocumentType.code` is stable; `DocumentType.label` may evolve.
|
||||
|
||||
## Data Model Summary
|
||||
|
||||
- `Document` has one `DocumentType`, many `Source` pages, many `Job` runs, and many `Person` records through `DocumentPerson`.
|
||||
- `Source` belongs to one `Document` and may participate in many `JobSource` executions.
|
||||
- `Job` has many `JobSource` rows.
|
||||
- `PersonRole` defines available relationship roles.
|
||||
- `RoleExclusivity` defines role pairs that cannot coexist for the same document-person pair.
|
||||
|
||||
## Test Strategy
|
||||
|
||||
- Unit tests for models, validation, hashing, and registry resolution.
|
||||
- Service tests for CRUD, set-based sync, and exclusivity enforcement.
|
||||
- Async workflow tests for page isolation, partial failure handling, and stored evidence.
|
||||
- UI integration tests for multi-page rendering, role grouping, and document type selection.
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v4.md)
|
||||
- [System Requirements](requirements_v4.md)
|
||||
- [Data Model](schema_v4.md)
|
||||
- [Error Handling Policy](error_handling_v4.md)
|
||||
@@ -0,0 +1,110 @@
|
||||
# Error Handling Policy (Version 4)
|
||||
|
||||
This document defines the canonical error-handling policy for the document transcription system.
|
||||
|
||||
## Error Handling Objectives
|
||||
|
||||
- Make failures visible in clear, actionable language at both the document and page levels.
|
||||
- Support isolated failure handling in multi-page jobs so one failing page does not invalidate successful pages.
|
||||
- Preserve diagnostic detail for validation failures, provider failures, and policy conflicts.
|
||||
- Ensure consistent error envelope structure across API, UI, service, and worker boundaries.
|
||||
|
||||
## Scope and Authority
|
||||
|
||||
This policy governs error behavior across:
|
||||
|
||||
- NiceGUI pages
|
||||
- FastAPI routes
|
||||
- Service-layer orchestration
|
||||
- `asyncio` worker tasks
|
||||
- Database interactions
|
||||
- Provider adapters
|
||||
|
||||
## Error Taxonomy
|
||||
|
||||
| Category | Definition | Retriable |
|
||||
| --- | --- | --- |
|
||||
| `validation_error` | Payload, parameter, or schema validation failure | no |
|
||||
| `user_input_error` | Unacceptable file, invalid selection, or malformed request from the operator | no |
|
||||
| `not_found_error` | Requested `Document`, `Source`, `Person`, `Job`, role, or type does not exist | no |
|
||||
| `conflict_error` | Operation violates uniqueness or exclusivity policy | no |
|
||||
| `external_provider_error` | Provider API failure, rate limit, or execution problem | yes |
|
||||
| `infrastructure_transient_error` | Temporary DB, file-system, or network instability | yes |
|
||||
| `infrastructure_persistent_error` | Persistent configuration, credential, or database availability failure | no |
|
||||
| `internal_unexpected_error` | Uncaught exception or logic defect | no |
|
||||
|
||||
## Async Batch and Page-Level Error Behavior
|
||||
|
||||
In multi-page `asyncio` processing:
|
||||
|
||||
1. Exceptions from individual page calls are trapped within the page task wrapper.
|
||||
2. Failed page detail is written to `JobSource.error_detail` and the page state becomes `failed`.
|
||||
3. Aggregate job status is derived from page outcomes:
|
||||
- all pages succeed -> `completed`
|
||||
- some succeed and some fail -> `partial_success`
|
||||
- all fail -> `failed`
|
||||
4. Successful pages remain valid even when sister pages fail.
|
||||
|
||||
## Relationship and Classification Conflict Behavior
|
||||
|
||||
When relationship or document-type writes fail policy checks:
|
||||
|
||||
1. Reject the full write operation.
|
||||
2. Return structured conflict detail including target identifiers and the violated rule.
|
||||
3. Preserve existing persisted relationships unchanged.
|
||||
|
||||
## API Error Response Contract
|
||||
|
||||
API error responses return a structured envelope:
|
||||
|
||||
^^^json
|
||||
{
|
||||
"error_id": "err_uuid_12345",
|
||||
"category": "conflict_error",
|
||||
"message": "Role assignment violates exclusivity policy.",
|
||||
"suggestion": "Remove recipient before assigning author for this person on this document.",
|
||||
"details": {
|
||||
"document_id": "...",
|
||||
"person_id": "...",
|
||||
"attempted_role": "author",
|
||||
"conflicting_role": "recipient",
|
||||
"policy_rule": "author+recipient exclusive"
|
||||
},
|
||||
"timestamp": "2026-08-10T15:00:00Z"
|
||||
}
|
||||
^^^
|
||||
|
||||
HTTP status mappings:
|
||||
|
||||
- `validation_error`, `user_input_error` -> `400`
|
||||
- `not_found_error` -> `404`
|
||||
- `conflict_error` -> `409`
|
||||
- `external_provider_error` -> `502` or `503`
|
||||
- `infrastructure_transient_error` -> `503`
|
||||
- `infrastructure_persistent_error`, `internal_unexpected_error` -> `500`
|
||||
|
||||
## UI Error Presentation Rules
|
||||
|
||||
- Display concise failure summaries with the next action the operator can take.
|
||||
- Keep form state in context when feasible.
|
||||
- Distinguish validation issues, conflict issues, provider failures, and infrastructure failures.
|
||||
- For bulk relationship updates, identify the specific role or person that caused a conflict.
|
||||
|
||||
## Logging and Audit Expectations
|
||||
|
||||
- Log worker failures with correlation IDs and provider context.
|
||||
- Log relationship and classification conflicts with machine-readable detail.
|
||||
- Log persisted provider errors and page-level execution failures.
|
||||
|
||||
## Retry Guidance
|
||||
|
||||
- Do not auto-retry validation or conflict failures.
|
||||
- Permit user-driven retry after the input or selection changes.
|
||||
- Allow bounded retry for transient provider or infrastructure failures when the operation is idempotent.
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v4.md)
|
||||
- [System Requirements](requirements_v4.md)
|
||||
- [Data Model](schema_v4.md)
|
||||
- [System Architecture](architecture_v4.md)
|
||||
@@ -0,0 +1,97 @@
|
||||
# Implementation Plan (Version 4)
|
||||
|
||||
## Goal
|
||||
|
||||
Implement the Version 4 project definition from the current repository state while preserving existing data by default.
|
||||
|
||||
## Migration Policy
|
||||
|
||||
- Database changes are non-destructive by default.
|
||||
- Exception: the legacy `document_type` text field may be replaced by a `document_type_id` reference without migrating existing text values.
|
||||
- Exception: `document_person` links may be recreated manually.
|
||||
|
||||
## Current Project Impact
|
||||
|
||||
- `src/transcription/db/models.py` requires full schema alignment with the V4 core documents.
|
||||
- `src/transcription/services/documents.py` requires set-based document-person sync, exclusivity checks, and document-type resolution.
|
||||
- API modules require additive role-aware relationship behavior and document-type selection behavior.
|
||||
- UI pages require grouped role displays, multi-role editing, and registry-backed document-type selection.
|
||||
- Existing tests require updates for role enforcement, document-type selection, and regression safety.
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### 1. Finalize the Transition Documents
|
||||
|
||||
- Confirm the reset scope.
|
||||
- Confirm the database exception policy.
|
||||
- Keep core V4 documents as the only authoritative product definition.
|
||||
|
||||
### 2. Align the Persistence Layer
|
||||
|
||||
- Update SQLModel definitions to match the final V4 schema.
|
||||
- Add `person_role`, `role_exclusivity`, and `document_type` support.
|
||||
- Replace legacy document-type storage with `document_type_id`.
|
||||
- Apply the accepted manual exception strategy for `document_type` and `document_person` data.
|
||||
- Preserve all other data structures non-destructively.
|
||||
|
||||
### 3. Update Services and Write Semantics
|
||||
|
||||
- Implement set-based synchronization for document-person updates.
|
||||
- Implement deterministic exclusivity conflict checks.
|
||||
- Remove suggestion-related service behavior.
|
||||
- Add document-type resolution and validation by stable code or id.
|
||||
|
||||
### 4. Update API Contracts
|
||||
|
||||
- Keep API evolution additive.
|
||||
- Add role-aware relationship retrieval and write behavior.
|
||||
- Add document-type catalog retrieval and code-based selection for document writes.
|
||||
- Remove suggestion-related API surfaces from the V4 target state.
|
||||
|
||||
### 5. Update UI Workflows
|
||||
|
||||
- Replace single-person link editing with grouped multi-role editing.
|
||||
- Render grouped role links on document and person detail views.
|
||||
- Replace free-text document type entry with registry-backed selection.
|
||||
- Preserve clear validation and conflict messaging.
|
||||
|
||||
### 6. Verification and Hardening
|
||||
|
||||
- Add or update service tests for many-per-role behavior, exclusivity enforcement, and set-based sync correctness.
|
||||
- Add API tests for relationship behavior and document-type selection.
|
||||
- Add UI tests or walkthrough coverage for grouped roles and type selection.
|
||||
- Add regression coverage for delete and cleanup semantics.
|
||||
|
||||
## Done When
|
||||
|
||||
- Core V4 documents and code paths agree on the final project definition.
|
||||
- Relationship-role writes are deterministic and non-destructive.
|
||||
- Exclusivity rules are enforced consistently.
|
||||
- Document type selection is registry-backed.
|
||||
- The accepted manual exceptions for `document_type` and `document_person` are completed.
|
||||
- The focused test coverage passes.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Suggested/asserted relationship state.
|
||||
- Suggestion review or extraction workflows.
|
||||
- Global person entity-resolution engine.
|
||||
- Automated semantic document-type classification.
|
||||
|
||||
## Delivery Order Recommendation
|
||||
|
||||
1. Freeze scope boundary and implementation plan.
|
||||
2. Freeze core V4 documents.
|
||||
3. Align persistence models.
|
||||
4. Align services and API behavior.
|
||||
5. Align UI behavior.
|
||||
6. Run focused verification and regression checks.
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [V4 Scope Boundary](scope_boundary_v4.md)
|
||||
- [System Overview](index_v4.md)
|
||||
- [System Requirements](requirements_v4.md)
|
||||
- [Data Model](schema_v4.md)
|
||||
- [System Architecture](architecture_v4.md)
|
||||
- [Error Handling Policy](error_handling_v4.md)
|
||||
@@ -0,0 +1,40 @@
|
||||
# Document Transcription System Overview (Version 4)
|
||||
|
||||
This project is a personal-scale application for transcribing, organizing, and preserving historical documents, images, and related people records.
|
||||
|
||||
## Start Here
|
||||
|
||||
Read [architecture_v4.md](architecture_v4.md) first for the technical overview and system design.
|
||||
|
||||
## Core Capabilities
|
||||
|
||||
- Folder and multi-image ingestion into sequential `Source` pages under a single `Document`.
|
||||
- Parallel asynchronous AI vision transcription using Python `asyncio` bounded by rate limits.
|
||||
- Portable relational storage using SQLModel and SQLAlchemy across SQLite and PostgreSQL.
|
||||
- Complete prompt and response provenance for every transcription job and page execution.
|
||||
- File-integrity tracking through SHA-256 hashing and stored file sizes.
|
||||
- Historical `Person` management with many-to-many document links and extensible relationship roles.
|
||||
- Registry-driven `DocumentType` classification with stable codes and controlled selection.
|
||||
- Inline human revision of transcribed pages while preserving immutable machine output.
|
||||
- Partial-failure recovery for multi-page jobs.
|
||||
- Cross-platform operational workflows driven by Python-based tooling.
|
||||
|
||||
## Technical Stack
|
||||
|
||||
- Application Web Framework: FastAPI + NiceGUI
|
||||
- Persistence Engine: SQLModel / SQLAlchemy
|
||||
- Data Validation and Schemas: Pydantic V2
|
||||
- Concurrency and Workers: Python `asyncio`
|
||||
- Vision Providers: OpenAI, Anthropic, and OpenRouter adapters
|
||||
|
||||
## Core Documentation Index
|
||||
|
||||
- [System Architecture](architecture_v4.md)
|
||||
- [System Requirements](requirements_v4.md)
|
||||
- [Data Model](schema_v4.md)
|
||||
- [Error Handling Policy](error_handling_v4.md)
|
||||
|
||||
## Transition Documents
|
||||
|
||||
- [Scope Boundary](scope_boundary_v4.md)
|
||||
- [Implementation Plan](implementation_plan_v4.md)
|
||||
@@ -0,0 +1,51 @@
|
||||
# Document Transcription System Requirements (Version 4)
|
||||
|
||||
This document defines the baseline requirements for the document transcription system.
|
||||
|
||||
## Requirements Model
|
||||
|
||||
| ID | Category | Requirement | Verify Method |
|
||||
| --- | --- | --- | --- |
|
||||
| REQ-0 | System | Provide end-to-end multi-page document transcription with persistent, inspectable async job states. | demonstration |
|
||||
| REQ-1 | Functional | Allow users to upload one or more images as ordered `Source` pages under a `Document`. | test |
|
||||
| REQ-2 | Functional | Process page transcription asynchronously using an `asyncio` worker pool bounded by rate limits. | test |
|
||||
| REQ-3 | Functional | Persist submission-time prompt configuration and full page-level provider response evidence for every job execution. | test |
|
||||
| REQ-4 | Functional | Support job states `queued`, `processing`, `completed`, `partial_success`, and `failed`, plus page states `pending`, `transcribed`, and `failed`. | inspection |
|
||||
| REQ-5 | Functional | Allow users to manage historical `Person` records and link multiple people per role to a `Document`. | test |
|
||||
| REQ-6 | Functional | Support an extensible role taxonomy for document-person relationships. | inspection |
|
||||
| REQ-7 | Policy Constraint | Enforce a role exclusivity matrix for a single `(document_id, person_id)` pair; initial rules must block `author` + `recipient` coexistence while allowing `mentioned` to coexist with other roles. | test |
|
||||
| REQ-8 | Functional | Use set-based synchronization for document-person mutations so updates add and remove only the intended links. | test |
|
||||
| REQ-9 | Functional | Maintain immutable machine output on `Source.raw_transcription` while permitting inline human edits on `Source.revised_text`. | test |
|
||||
| REQ-10 | Functional | Support a registry-driven `DocumentType` taxonomy with stable codes, mutable labels, and active/inactive lifecycle control. | test |
|
||||
| REQ-11 | Data Constraint | Store `Document` type as a controlled reference to `DocumentType`. | test |
|
||||
| REQ-12 | Interface | Render multi-page transcriptions sequentially by `page_number` with document, people, and document-type metadata. | demonstration |
|
||||
| REQ-13 | Interface | Document create/edit UI must support selecting multiple people per role and selecting an active document type from the registry. | demonstration |
|
||||
| REQ-14 | API Constraint | Expose additive, role-aware retrieval and write behavior for document-person links and code-based selection for document types. | test |
|
||||
| REQ-15 | Data Constraint | Calculate and store cryptographic file hashes (SHA-256) and file sizes for uploaded source images. | test |
|
||||
| REQ-16 | Data Constraint | Preserve a portable relational model across supported backends using SQLModel, SQLAlchemy, SQLite, and PostgreSQL. | inspection |
|
||||
| REQ-17 | Reliability | Ensure delete and update flows for documents, people, and relationship links remain deterministic and safe. | test |
|
||||
| REQ-18 | Operations Constraint | Keep canonical development, testing, restore, and recovery workflows OS-independent. | inspection |
|
||||
| REQ-19 | Quality | Provide automated coverage for async transcription workflows, relationship-role enforcement, document-type selection, and regression behavior. | test |
|
||||
|
||||
## Clarifying Constraints
|
||||
|
||||
1. `DocumentType.code` and `PersonRole.code` are stable machine identifiers.
|
||||
2. `DocumentType.label` and `PersonRole.label` may evolve without changing canonical identity.
|
||||
3. Role-policy enforcement must be consistent across UI, API, services, and persistence.
|
||||
4. Many-per-role behavior is required for document-person links.
|
||||
5. Relationship conflicts must fail deterministically without partial mutation.
|
||||
|
||||
## Element Satisfaction Mapping
|
||||
|
||||
- UI (NiceGUI): Satisfies REQ-0, REQ-1, REQ-5, REQ-9, REQ-12, REQ-13.
|
||||
- API (FastAPI): Satisfies REQ-1, REQ-4, REQ-5, REQ-7, REQ-8, REQ-14.
|
||||
- Worker (`asyncio`): Satisfies REQ-2, REQ-3, REQ-4.
|
||||
- Persistence (SQLModel / SQLAlchemy): Satisfies REQ-3, REQ-9, REQ-10, REQ-11, REQ-15, REQ-16, REQ-17.
|
||||
- Test Suite: Verifies all test-marked requirements and satisfies REQ-19.
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v4.md)
|
||||
- [System Architecture](architecture_v4.md)
|
||||
- [Data Model](schema_v4.md)
|
||||
- [Error Handling Policy](error_handling_v4.md)
|
||||
@@ -0,0 +1,192 @@
|
||||
# Database Schema (Version 4)
|
||||
|
||||
This document defines the relational schema for the document transcription system.
|
||||
|
||||
## Entity Relationship Diagram
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
DOCUMENT_TYPE {
|
||||
UUID id PK
|
||||
TEXT code
|
||||
TEXT label
|
||||
BOOLEAN is_active
|
||||
INTEGER sort_order
|
||||
TIMESTAMPTZ created_at
|
||||
TIMESTAMPTZ updated_at
|
||||
}
|
||||
|
||||
PERSON_ROLE {
|
||||
UUID id PK
|
||||
TEXT code
|
||||
TEXT label
|
||||
BOOLEAN is_active
|
||||
TIMESTAMPTZ created_at
|
||||
TIMESTAMPTZ updated_at
|
||||
}
|
||||
|
||||
ROLE_EXCLUSIVITY {
|
||||
UUID id PK
|
||||
UUID left_role_id FK
|
||||
UUID right_role_id FK
|
||||
TIMESTAMPTZ created_at
|
||||
}
|
||||
|
||||
PERSON {
|
||||
UUID id PK
|
||||
TEXT full_name
|
||||
TEXT display_name
|
||||
TEXT maiden_name
|
||||
DATE birth_date
|
||||
TEXT birth_date_raw
|
||||
TEXT birth_place
|
||||
DATE death_date
|
||||
TEXT death_date_raw
|
||||
TEXT death_place
|
||||
TEXT biography
|
||||
TEXT portrait_path
|
||||
JSONB metadata
|
||||
TIMESTAMPTZ created_at
|
||||
TIMESTAMPTZ updated_at
|
||||
}
|
||||
|
||||
DOCUMENT {
|
||||
UUID id PK
|
||||
UUID document_type_id FK
|
||||
TEXT name
|
||||
DATE document_date
|
||||
TEXT document_date_raw
|
||||
TEXT location_created
|
||||
TEXT notes
|
||||
TEXT archive_identifier
|
||||
TIMESTAMPTZ created_at
|
||||
TIMESTAMPTZ updated_at
|
||||
}
|
||||
|
||||
DOCUMENT_PERSON {
|
||||
UUID id PK
|
||||
UUID document_id FK
|
||||
UUID person_id FK
|
||||
UUID role_id FK
|
||||
TIMESTAMPTZ created_at
|
||||
TIMESTAMPTZ updated_at
|
||||
}
|
||||
|
||||
JOB {
|
||||
UUID id PK
|
||||
UUID document_id FK
|
||||
VARCHAR status
|
||||
INTEGER retry_count
|
||||
TEXT provider
|
||||
TEXT model
|
||||
TEXT prompt_name
|
||||
TEXT prompt_hash
|
||||
TEXT system_prompt
|
||||
TEXT user_prompt
|
||||
FLOAT temperature
|
||||
FLOAT top_p
|
||||
TIMESTAMPTZ date_created
|
||||
TIMESTAMPTZ date_updated
|
||||
}
|
||||
|
||||
SOURCE {
|
||||
UUID id PK
|
||||
UUID document_id FK
|
||||
INTEGER page_number
|
||||
TEXT upload_name
|
||||
TEXT filename
|
||||
TEXT file_path
|
||||
TEXT file_hash
|
||||
BIGINT file_size_bytes
|
||||
TEXT raw_transcription
|
||||
TEXT revised_text
|
||||
TIMESTAMPTZ date_uploaded
|
||||
TIMESTAMPTZ date_revised
|
||||
}
|
||||
|
||||
JOB_SOURCE {
|
||||
UUID id PK
|
||||
UUID job_id FK
|
||||
UUID source_id FK
|
||||
VARCHAR status
|
||||
TEXT raw_transcription
|
||||
JSONB ai_metadata
|
||||
JSONB raw_api_response
|
||||
TEXT error_detail
|
||||
TIMESTAMPTZ executed_at
|
||||
}
|
||||
|
||||
DOCUMENT_TYPE ||--o{ DOCUMENT : classifies
|
||||
DOCUMENT ||--o{ DOCUMENT_PERSON : has_people
|
||||
PERSON ||--o{ DOCUMENT_PERSON : appears_in
|
||||
PERSON_ROLE ||--o{ DOCUMENT_PERSON : labels
|
||||
PERSON_ROLE ||--o{ ROLE_EXCLUSIVITY : left_rule
|
||||
PERSON_ROLE ||--o{ ROLE_EXCLUSIVITY : right_rule
|
||||
DOCUMENT ||--o{ JOB : has_jobs
|
||||
DOCUMENT ||--o{ SOURCE : contains_pages
|
||||
JOB ||--o{ JOB_SOURCE : executes
|
||||
SOURCE ||--o{ JOB_SOURCE : processed_in
|
||||
```
|
||||
|
||||
## Domain Invariants and Provenance Rules
|
||||
|
||||
### Page-Level Execution and AI Outputs
|
||||
|
||||
- Every single page execution by an AI model produces a dedicated `JOB_SOURCE` record.
|
||||
- Every `JOB` stores the frozen prompt identifier, prompt text, and hyperparameters used at submission time.
|
||||
- Every `JOB_SOURCE` stores the complete provider response envelope and page-level operational metadata.
|
||||
- `SOURCE.raw_transcription` caches the latest successful machine output for that page.
|
||||
|
||||
### Image Storage and Integrity
|
||||
|
||||
- Binary images are stored on disk; `SOURCE.file_path` stores the persisted path.
|
||||
- `SOURCE.file_hash` stores a SHA-256 digest.
|
||||
- `SOURCE.file_size_bytes` stores the original file size.
|
||||
|
||||
### Page Ordering and Revisions
|
||||
|
||||
- `SOURCE.page_number` dictates page ordering within a document.
|
||||
- `SOURCE.raw_transcription` remains immutable machine output.
|
||||
- `SOURCE.revised_text` stores human edits and is the preferred display value when present.
|
||||
|
||||
### Document-Person Role Governance
|
||||
|
||||
- Documents support zero, one, or many people per relationship role.
|
||||
- Relationship roles are defined by `PERSON_ROLE` rather than hardcoded columns.
|
||||
- `DOCUMENT_PERSON` must be unique for `(document_id, person_id, role_id)`.
|
||||
- Configured exclusive role pairs from `ROLE_EXCLUSIVITY` cannot coexist for the same `(document_id, person_id)`.
|
||||
- Initial exclusivity seed blocks `author` and `recipient` for the same person-document pair.
|
||||
|
||||
### Document Type Governance
|
||||
|
||||
- Every document type is defined by `DOCUMENT_TYPE`.
|
||||
- `DOCUMENT_TYPE.code` is a stable machine identifier.
|
||||
- `DOCUMENT_TYPE.label` is mutable display text.
|
||||
- Inactive types remain valid for historical rows but should be excluded from default selection UIs.
|
||||
|
||||
## Constraint Summary
|
||||
|
||||
- `DOCUMENT_TYPE.code` is unique.
|
||||
- `PERSON_ROLE.code` is unique.
|
||||
- `DOCUMENT_PERSON(document_id, person_id, role_id)` is unique.
|
||||
- `ROLE_EXCLUSIVITY(left_role_id, right_role_id)` is unique.
|
||||
- `ROLE_EXCLUSIVITY` must use canonical ordering to avoid duplicate mirrored pairs.
|
||||
|
||||
## Indexing Guidance
|
||||
|
||||
- `document(document_type_id)`
|
||||
- `document_person(document_id)`
|
||||
- `document_person(person_id)`
|
||||
- `document_person(role_id)`
|
||||
- `role_exclusivity(left_role_id, right_role_id)`
|
||||
- `source(document_id, page_number)`
|
||||
- `job(document_id, status)`
|
||||
- `job_source(job_id)`
|
||||
- `job_source(source_id)`
|
||||
|
||||
## Related Local References
|
||||
|
||||
- [System Overview](index_v4.md)
|
||||
- [System Architecture](architecture_v4.md)
|
||||
- [System Requirements](requirements_v4.md)
|
||||
- [Error Handling Policy](error_handling_v4.md)
|
||||
@@ -0,0 +1,95 @@
|
||||
# V4 Scope Boundary
|
||||
|
||||
This document defines the scope for the transition from the current repository state to the Version 4 project definition.
|
||||
|
||||
## Purpose
|
||||
|
||||
Define what this revision includes, what it intentionally excludes, and what migration rules govern the transition work.
|
||||
|
||||
## In Scope
|
||||
|
||||
### 1. Relationship Model
|
||||
|
||||
- Extensible role taxonomy for document-person relationships.
|
||||
- Many-to-many document-person links with many people per role.
|
||||
- Deterministic exclusivity policy for configured role pairs.
|
||||
- Set-based add/remove synchronization for document-person updates.
|
||||
|
||||
### 2. Document Type Governance
|
||||
|
||||
- Registry-driven `DocumentType` model with stable codes and controlled selection.
|
||||
- Minimal rollout for the current corpus with no alias helper table.
|
||||
|
||||
### 3. UI and API Behavior
|
||||
|
||||
- Grouped role links on document and person views.
|
||||
- Multi-role relationship editing on document create/edit flows.
|
||||
- Role-aware API retrieval and write behavior.
|
||||
- Additive API evolution with explicit deprecations.
|
||||
|
||||
### 4. Verification
|
||||
|
||||
- Tests for many-per-role behavior.
|
||||
- Tests for exclusivity enforcement.
|
||||
- Tests for set-based relationship mutation behavior.
|
||||
- Tests for document and person delete/link cleanup regressions.
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Suggested versus asserted relationship states.
|
||||
- Suggestion storage, review, acceptance, or rejection workflows.
|
||||
- Automatic relationship extraction or recommendation features.
|
||||
- Full entity resolution or identity merge across all people.
|
||||
- Automated semantic document type classification.
|
||||
- Redesign of the core transcription execution model.
|
||||
|
||||
## Locked Design Decisions
|
||||
|
||||
### A. Role Extensibility Mechanism
|
||||
|
||||
- Use registry tables for relationship roles.
|
||||
|
||||
### B. Exclusivity Matrix Baseline
|
||||
|
||||
- `author` and `recipient` are mutually exclusive for the same `(document, person)` pair.
|
||||
- `mentioned` remains non-exclusive.
|
||||
|
||||
### C. API Compatibility Strategy
|
||||
|
||||
- Use additive API evolution.
|
||||
- In development mode, the current revision is authoritative.
|
||||
- Deprecations should be explicit and short-lived.
|
||||
|
||||
### D. Document Type Rollout Strategy
|
||||
|
||||
- Use a minimal registry rollout for the current corpus.
|
||||
- Do not introduce a `document_type_alias` helper table.
|
||||
|
||||
### E. Database Change Policy
|
||||
|
||||
- Future schema changes are non-destructive by default.
|
||||
- Exception: `document_type` text may be replaced by `document_type_id` without migrating the legacy text values.
|
||||
- Exception: `document_person` links may be recreated manually.
|
||||
|
||||
## Compatibility and Rollout
|
||||
|
||||
- Preserve existing repository behavior where unaffected by the V4 scope.
|
||||
- Treat scope boundary and implementation plan as the only transition documents.
|
||||
- Treat core V4 documents as the authoritative project definition once rewritten.
|
||||
|
||||
## Exit Criteria for Scope Freeze
|
||||
|
||||
V4 scope is considered frozen when:
|
||||
|
||||
- Relationship model, exclusivity rules, and document-type governance are approved.
|
||||
- Additive API change list and deprecation schedule are approved.
|
||||
- Migration exceptions are explicitly acknowledged.
|
||||
|
||||
## Core V4 Documents
|
||||
|
||||
1. `docs/ver4/index_v4.md`
|
||||
2. `docs/ver4/requirements_v4.md`
|
||||
3. `docs/ver4/schema_v4.md`
|
||||
4. `docs/ver4/architecture_v4.md`
|
||||
5. `docs/ver4/error_handling_v4.md`
|
||||
6. `docs/ver4/implementation_plan_v4.md`
|
||||
Binary file not shown.
@@ -0,0 +1,27 @@
|
||||
import uvicorn
|
||||
from fastapi import FastAPI
|
||||
|
||||
from .app import create_app
|
||||
from .config import parse_cli_settings
|
||||
|
||||
|
||||
def create_cli_app() -> FastAPI:
|
||||
"""Create an app from CLI settings for Uvicorn's reload process."""
|
||||
return create_app(settings=parse_cli_settings())
|
||||
|
||||
|
||||
def main() -> None:
|
||||
settings = parse_cli_settings()
|
||||
application = "transcription.__main__:create_cli_app" if settings.reload else create_app(settings=settings)
|
||||
uvicorn.run(
|
||||
application,
|
||||
factory=settings.reload,
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
log_level=settings.log_level,
|
||||
reload=settings.reload,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -16,6 +16,7 @@ from fastapi.staticfiles import StaticFiles
|
||||
|
||||
from .api.errors import register_error_handlers
|
||||
from .api.health import router as health_router
|
||||
from .config import Settings
|
||||
from .config import configure_logging
|
||||
from .config import get_settings
|
||||
from .db import create_all
|
||||
@@ -31,9 +32,8 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
@asynccontextmanager
|
||||
async def _lifespan(app: FastAPI):
|
||||
configure_logging()
|
||||
|
||||
settings = getattr(app.state, "settings", None) or get_settings()
|
||||
configure_logging(settings)
|
||||
app.state.settings = settings
|
||||
app.state.services = ServiceBundle()
|
||||
app.state.runtime = initialize_database_runtime(settings=settings)
|
||||
@@ -73,24 +73,28 @@ async def _recover_stale_processing_jobs(app: FastAPI) -> None:
|
||||
logger.warning("Recovered %s stale processing job(s) at startup", recovered)
|
||||
|
||||
|
||||
def create_app() -> FastAPI:
|
||||
def create_app(settings: Settings | None = None) -> FastAPI:
|
||||
"""Create and configure the FastAPI application."""
|
||||
app = FastAPI(title="Transcription", lifespan=_lifespan)
|
||||
settings = get_settings()
|
||||
app.state.settings = settings
|
||||
active_settings = settings or get_settings()
|
||||
app.state.settings = active_settings
|
||||
app.mount(
|
||||
"/uploads",
|
||||
StaticFiles(directory=settings.upload_dir, check_dir=False),
|
||||
StaticFiles(directory=active_settings.upload_dir, check_dir=False),
|
||||
name="uploads",
|
||||
)
|
||||
|
||||
@app.get("/", include_in_schema=False)
|
||||
async def root_redirect() -> RedirectResponse:
|
||||
return RedirectResponse(url="/ui", status_code=status.HTTP_307_TEMPORARY_REDIRECT)
|
||||
return RedirectResponse(url="/ui/homepage", status_code=status.HTTP_307_TEMPORARY_REDIRECT)
|
||||
|
||||
@app.get("/ui", include_in_schema=False)
|
||||
async def ui_redirect() -> RedirectResponse:
|
||||
return RedirectResponse(url="/ui/upload", status_code=status.HTTP_307_TEMPORARY_REDIRECT)
|
||||
return RedirectResponse(url="/ui/homepage", status_code=status.HTTP_307_TEMPORARY_REDIRECT)
|
||||
|
||||
@app.get("/healthz")
|
||||
def health() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
register_error_handlers(app)
|
||||
register_pages(app)
|
||||
|
||||
@@ -7,7 +7,7 @@ from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from transcription.db.runtime import DatabaseRuntime
|
||||
from transcription.db.runtime import get_session_factory
|
||||
from transcription.db.session import get_session_factory
|
||||
from transcription.worker import WorkerNotifier
|
||||
from transcription.worker import resolve_worker_notifier
|
||||
|
||||
|
||||
+55
-14
@@ -6,12 +6,17 @@ are resolved by the provider adapters, not here.
|
||||
"""
|
||||
|
||||
import logging.config
|
||||
from contextvars import ContextVar
|
||||
from collections.abc import Sequence
|
||||
from enum import StrEnum
|
||||
from functools import cache
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
from typing import Any
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic import Field
|
||||
from pydantic import SecretStr
|
||||
from pydantic_settings import BaseSettings
|
||||
from pydantic_settings import SettingsConfigDict
|
||||
|
||||
@@ -22,26 +27,58 @@ class Provider(StrEnum):
|
||||
OPENROUTER = "openrouter"
|
||||
|
||||
|
||||
class SqliteSettings(BaseModel):
|
||||
driver: Literal["sqlite"] = "sqlite"
|
||||
path: str = "app.db"
|
||||
|
||||
|
||||
class PostgresSettings(BaseModel):
|
||||
driver: Literal["postgres"] = "postgres"
|
||||
host: str
|
||||
port: int = 5432
|
||||
database: str
|
||||
user: str
|
||||
password: SecretStr
|
||||
|
||||
|
||||
DatabaseSettings = Annotated[
|
||||
SqliteSettings | PostgresSettings,
|
||||
Field(discriminator="driver"),
|
||||
]
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
env_nested_delimiter="__",
|
||||
cli_implicit_flags=True,
|
||||
cli_kebab_case=True,
|
||||
)
|
||||
|
||||
# --- NiceGUI Server ---
|
||||
host: str = "0.0.0.0"
|
||||
port: int = 8000
|
||||
log_level: Literal["critical", "error", "warning", "info", "debug", "trace"] = "info"
|
||||
reload: bool = False
|
||||
|
||||
# --- AI provider ---
|
||||
provider: Provider = Provider.OPENROUTER
|
||||
openrouter_api_key: str
|
||||
provider_model: str | None = None
|
||||
openrouter_http_referer: str | None = None
|
||||
openrouter_app_title: str | None = None
|
||||
default_prompt_name: str = "transcribe_document.md"
|
||||
transcription_temperature: float | None = None
|
||||
transcription_top_p: float | None = None
|
||||
|
||||
# --- runtime environment ---
|
||||
environment: Literal["development", "test", "production"] = "development"
|
||||
|
||||
# --- persistence ---
|
||||
database_url: str = "sqlite:///./transcription.db"
|
||||
bootstrap_schema_on_startup: bool | None = None
|
||||
database: DatabaseSettings = Field(default_factory=SqliteSettings)
|
||||
bootstrap_schema_on_startup: bool = False
|
||||
sqlite_check_same_thread: bool = False
|
||||
|
||||
# --- filesystem paths ---
|
||||
@@ -59,23 +96,24 @@ class Settings(BaseSettings):
|
||||
@property
|
||||
def should_bootstrap_schema(self) -> bool:
|
||||
"""Return whether startup should auto-create schema for this environment."""
|
||||
if self.bootstrap_schema_on_startup is not None:
|
||||
if "bootstrap_schema_on_startup" in self.model_fields_set:
|
||||
return self.bootstrap_schema_on_startup
|
||||
return self.environment in {"development", "test"}
|
||||
|
||||
|
||||
_settings: ContextVar[Settings | None] = ContextVar("settings", default=None)
|
||||
@cache
|
||||
def get_settings(**kwargs: Any) -> Settings:
|
||||
"""Load cached settings without reading process CLI arguments."""
|
||||
return Settings(_cli_parse_args=False, **kwargs) # pyright: ignore[reportCallIssue]
|
||||
|
||||
|
||||
def get_settings(**kwargs) -> Settings:
|
||||
settings = _settings.get()
|
||||
if settings is None:
|
||||
settings = Settings(**kwargs) # pyright: ignore[reportCallIssue]
|
||||
_settings.set(settings)
|
||||
return settings
|
||||
def parse_cli_settings(args: Sequence[str] | None = None) -> Settings:
|
||||
"""Load settings with CLI arguments at the executable boundary."""
|
||||
cli_args = True if args is None else list(args)
|
||||
return Settings(_cli_parse_args=cli_args) # pyright: ignore[reportCallIssue]
|
||||
|
||||
|
||||
LOGGING_CONFIG: dict[str, object] = {
|
||||
LOGGING_CONFIG: dict[str, Any] = {
|
||||
"version": 1,
|
||||
"disable_existing_loggers": False,
|
||||
"formatters": {
|
||||
@@ -105,7 +143,10 @@ LOGGING_CONFIG: dict[str, object] = {
|
||||
}
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
def configure_logging(settings: Settings | None = None) -> None:
|
||||
"""Configure root logging once at startup."""
|
||||
logging.config.dictConfig(LOGGING_CONFIG)
|
||||
cfg = LOGGING_CONFIG.copy()
|
||||
active_settings = settings or get_settings()
|
||||
cfg["loggers"]["transcription"]["level"] = active_settings.log_level.upper()
|
||||
logging.config.dictConfig(cfg)
|
||||
logger.debug("Logging configured")
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
from .operations import create_all
|
||||
from .runtime import dispose_database_runtime
|
||||
from .runtime import get_session
|
||||
from .runtime import initialize_database_runtime
|
||||
from .session import session_scope
|
||||
from .session import transaction_scope
|
||||
|
||||
__all__ = ["create_all", "dispose_database_runtime", "get_session", "initialize_database_runtime"]
|
||||
__all__ = [
|
||||
"create_all",
|
||||
"dispose_database_runtime",
|
||||
"initialize_database_runtime",
|
||||
"session_scope",
|
||||
"transaction_scope",
|
||||
]
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
from functools import cache
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import URL
|
||||
from sqlalchemy import StaticPool
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
|
||||
from ..config import PostgresSettings
|
||||
from ..config import Settings
|
||||
from ..config import SqliteSettings
|
||||
from ..config import get_settings
|
||||
|
||||
|
||||
def get_database_url(settings: Settings) -> str:
|
||||
match settings.database:
|
||||
case SqliteSettings(path=path):
|
||||
url = URL.create(
|
||||
drivername="sqlite+aiosqlite",
|
||||
database=path,
|
||||
)
|
||||
case PostgresSettings() as database:
|
||||
url = URL.create(
|
||||
drivername="postgresql+asyncpg",
|
||||
host=database.host,
|
||||
port=database.port,
|
||||
database=database.database,
|
||||
username=database.user,
|
||||
password=database.password.get_secret_value(),
|
||||
)
|
||||
return url.render_as_string(hide_password=False)
|
||||
|
||||
|
||||
def resolve_engine(settings: Settings | None = None) -> AsyncEngine:
|
||||
active_settings = settings or get_settings()
|
||||
return get_engine(get_database_url(active_settings))
|
||||
|
||||
|
||||
@cache
|
||||
def get_engine(database_url: str) -> AsyncEngine:
|
||||
kwargs: dict[str, Any] = {"echo": False, "pool_pre_ping": True}
|
||||
if database_url.startswith("sqlite"):
|
||||
kwargs["connect_args"] = {"check_same_thread": False}
|
||||
if ":memory:" in database_url:
|
||||
kwargs["poolclass"] = StaticPool
|
||||
|
||||
return create_async_engine(database_url, **kwargs)
|
||||
|
||||
|
||||
async def dispose_engine(database_url: str) -> None:
|
||||
engine = get_engine(database_url)
|
||||
try:
|
||||
await engine.dispose()
|
||||
finally:
|
||||
get_engine.cache_clear()
|
||||
|
||||
|
||||
async def refresh_engine(database_url: str) -> AsyncEngine:
|
||||
await dispose_engine(database_url)
|
||||
return get_engine(database_url)
|
||||
@@ -0,0 +1,240 @@
|
||||
"""SQLModel domain models for the V3 transcription system."""
|
||||
|
||||
from datetime import UTC
|
||||
from datetime import date
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Any
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import Column
|
||||
from sqlalchemy import BigInteger
|
||||
from sqlalchemy import JSON
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm.exc import DetachedInstanceError
|
||||
from sqlalchemy.types import TypeDecorator
|
||||
from sqlmodel import Field
|
||||
from sqlmodel import Relationship
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
|
||||
class JSONBCompat(TypeDecorator):
|
||||
"""JSONB for PostgreSQL and JSON for SQLite/testing backends."""
|
||||
|
||||
impl = JSON
|
||||
|
||||
def load_dialect_impl(self, dialect):
|
||||
if dialect.name == "postgresql":
|
||||
return dialect.type_descriptor(JSONB())
|
||||
return dialect.type_descriptor(JSON())
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
QUEUED = "queued"
|
||||
PROCESSING = "processing"
|
||||
TRANSCRIBED = "transcribed"
|
||||
COMPLETED = "completed"
|
||||
PARTIAL_SUCCESS = "partial_success"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
class DocumentPersonRole(StrEnum):
|
||||
AUTHOR = "author"
|
||||
RECIPIENT = "recipient"
|
||||
|
||||
|
||||
class JobSourceStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
TRANSCRIBED = "transcribed"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
class Document(SQLModel, table=True):
|
||||
"""An historical document."""
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
name: str
|
||||
document_type: str | None = None
|
||||
document_date: date | None = None
|
||||
document_date_raw: str | None = None
|
||||
location_created: str | None = None
|
||||
notes: str | None = None
|
||||
archive_identifier: str | None = None
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
|
||||
jobs: list["Job"] = Relationship(back_populates="document", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
sources: list["Source"] = Relationship(back_populates="document", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
document_people: list["DocumentPerson"] = Relationship(back_populates="document", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
|
||||
|
||||
class Person(SQLModel, table=True):
|
||||
"""A historical person linked to one or more documents."""
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
full_name: str
|
||||
display_name: str | None = None
|
||||
maiden_name: str | None = None
|
||||
birth_date: date | None = None
|
||||
birth_date_raw: str | None = None
|
||||
birth_place: str | None = None
|
||||
death_date: date | None = None
|
||||
death_date_raw: str | None = None
|
||||
death_place: str | None = None
|
||||
biography: str | None = None
|
||||
portrait_path: str | None = None
|
||||
metadata_: dict[str, Any] | None = Field(
|
||||
default=None,
|
||||
sa_column=Column("metadata", JSONBCompat(), nullable=True),
|
||||
)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
|
||||
document_people: list["DocumentPerson"] = Relationship(back_populates="person", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
|
||||
|
||||
class DocumentPerson(SQLModel, table=True):
|
||||
"""Associates documents with people in a given role."""
|
||||
|
||||
__tablename__ = "document_person"
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
document_id: UUID = Field(foreign_key="document.id")
|
||||
person_id: UUID = Field(foreign_key="person.id")
|
||||
role: DocumentPersonRole = Field(default=DocumentPersonRole.AUTHOR)
|
||||
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("document_id", "person_id", "role", name="uq_document_person_role"),
|
||||
)
|
||||
|
||||
document: Optional["Document"] = Relationship(back_populates="document_people", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
person: Optional["Person"] = Relationship(back_populates="document_people", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
|
||||
|
||||
class Job(SQLModel, table=True):
|
||||
"""A transcription job tied to a single document."""
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
document_id: UUID = Field(foreign_key="document.id")
|
||||
status: JobStatus = Field(default=JobStatus.QUEUED)
|
||||
retry_count: int = Field(default=0, ge=0)
|
||||
date_created: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
date_updated: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
provider: str | None = None
|
||||
model: str | None = None
|
||||
prompt_name: str | None = None
|
||||
prompt_hash: str | None = None
|
||||
system_prompt: str | None = None
|
||||
user_prompt: str | None = None
|
||||
temperature: float | None = None
|
||||
top_p: float | None = None
|
||||
|
||||
document: Optional["Document"] = Relationship(back_populates="jobs", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
job_sources: list["JobSource"] = Relationship(back_populates="job", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
|
||||
@property
|
||||
def filename(self) -> str:
|
||||
"""Return the filename of the associated source, when available."""
|
||||
if not self.job_sources:
|
||||
return "unknown"
|
||||
|
||||
for job_source in self.job_sources:
|
||||
source = job_source.__dict__.get("source")
|
||||
if source is None:
|
||||
try:
|
||||
source = job_source.source
|
||||
except DetachedInstanceError:
|
||||
source = None
|
||||
except Exception: # noqa: BLE001
|
||||
source = None
|
||||
|
||||
if source is not None:
|
||||
return source.filename
|
||||
|
||||
return "unknown"
|
||||
|
||||
@property
|
||||
def error_detail(self) -> str | None:
|
||||
"""Return the first available source-level error detail for the job."""
|
||||
if not self.job_sources:
|
||||
return None
|
||||
|
||||
for job_source in self.job_sources:
|
||||
if job_source.error_detail:
|
||||
return job_source.error_detail
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class Source(SQLModel, table=True):
|
||||
"""A document source image or PDF page."""
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
document_id: UUID = Field(foreign_key="document.id")
|
||||
page_number: int = Field(default=1, ge=1)
|
||||
upload_name: str
|
||||
filename: str
|
||||
file_path: str
|
||||
file_hash: str
|
||||
file_size_bytes: int = Field(sa_column=Column(BigInteger(), nullable=False))
|
||||
raw_transcription: str | None = None
|
||||
revised_text: str | None = None
|
||||
date_uploaded: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
date_revised: datetime | None = None
|
||||
|
||||
document: Optional["Document"] = Relationship(
|
||||
back_populates="sources",
|
||||
sa_relationship_kwargs={"lazy": "selectin"},
|
||||
)
|
||||
job_sources: list["JobSource"] = Relationship(
|
||||
back_populates="source",
|
||||
sa_relationship_kwargs={"lazy": "selectin"},
|
||||
)
|
||||
|
||||
@property
|
||||
def latest_job_source(self) -> Optional["JobSource"]:
|
||||
"""Return the most recent job execution record for this source."""
|
||||
if not self.job_sources:
|
||||
return None
|
||||
return max(self.job_sources, key=lambda js: js.executed_at)
|
||||
|
||||
@property
|
||||
def latest_status(self) -> JobSourceStatus | None:
|
||||
"""Return the execution status of the latest job run."""
|
||||
latest = self.latest_job_source
|
||||
return latest.status if latest else None
|
||||
|
||||
@property
|
||||
def latest_error_detail(self) -> str | None:
|
||||
"""Return the error detail from the latest job run, if present."""
|
||||
latest = self.latest_job_source
|
||||
return latest.error_detail if latest else None
|
||||
|
||||
@property
|
||||
def document_name(self) -> str | None:
|
||||
"""Return the parent document name if loaded."""
|
||||
return self.document.name if self.document else None
|
||||
|
||||
class JobSource(SQLModel, table=True):
|
||||
"""A single AI execution record for one source page."""
|
||||
|
||||
__tablename__ = "job_source"
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
job_id: UUID = Field(foreign_key="job.id")
|
||||
source_id: UUID = Field(foreign_key="source.id")
|
||||
status: JobSourceStatus = Field(default=JobSourceStatus.PENDING)
|
||||
raw_transcription: str | None = None
|
||||
ai_metadata: dict[str, Any] | None = Field(default=None, sa_column=Column(JSONBCompat(), nullable=True))
|
||||
raw_api_response: dict[str, Any] | None = Field(default=None, sa_column=Column(JSONBCompat(), nullable=True))
|
||||
error_detail: str | None = None
|
||||
executed_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
|
||||
job: Optional["Job"] = Relationship(back_populates="job_sources", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
source: Optional["Source"] = Relationship(back_populates="job_sources", sa_relationship_kwargs={"lazy": "selectin"})
|
||||
|
||||
|
||||
@@ -2,21 +2,29 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from sqlalchemy import inspect
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.engine import Connection
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
from sqlmodel import SQLModel
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..models import Job
|
||||
from ..models import JobStatus
|
||||
from .runtime import get_engine
|
||||
from .engine import resolve_engine
|
||||
from .models import Job
|
||||
from .models import JobStatus
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def create_all(*, engine: AsyncEngine | None = None) -> None:
|
||||
"""Create any missing tables on the selected engine."""
|
||||
# Import models so SQLModel metadata is fully registered before bootstrap.
|
||||
from transcription.db import models as _models # noqa: F401
|
||||
|
||||
active_engine = engine or resolve_engine()
|
||||
async with active_engine.begin() as connection:
|
||||
await connection.run_sync(SQLModel.metadata.create_all)
|
||||
logger.debug("Database schema bootstrap complete for database_url=%s", active_engine.url)
|
||||
|
||||
|
||||
async def get_next_queued_job(*, session: AsyncSession) -> Job | None:
|
||||
"""Get the next queued job, if any."""
|
||||
result = await session.exec(
|
||||
@@ -26,54 +34,3 @@ async def get_next_queued_job(*, session: AsyncSession) -> Job | None:
|
||||
.limit(1)
|
||||
) # fmt: skip
|
||||
return result.first()
|
||||
|
||||
|
||||
async def create_all(*, engine: AsyncEngine | None = None) -> None:
|
||||
"""Create all tables on the selected engine."""
|
||||
# Import models so SQLModel metadata is fully registered before bootstrap.
|
||||
from transcription import models as _models # noqa: F401
|
||||
|
||||
active_engine = engine or get_engine()
|
||||
async with active_engine.begin() as connection:
|
||||
await connection.run_sync(SQLModel.metadata.create_all)
|
||||
await connection.run_sync(_ensure_sqlite_compat_columns)
|
||||
logger.debug("Database schema bootstrap complete for database_url=%s", active_engine.url)
|
||||
|
||||
|
||||
def _ensure_sqlite_compat_columns(connection: Connection) -> None:
|
||||
"""Apply lightweight dev/test SQLite compatibility column patches.
|
||||
|
||||
This keeps local bootstrap resilient when models evolve but no full
|
||||
migration tooling is in place yet.
|
||||
"""
|
||||
if connection.engine.url.get_backend_name() != "sqlite":
|
||||
return
|
||||
|
||||
inspector = inspect(connection)
|
||||
table_names = set(inspector.get_table_names())
|
||||
|
||||
if "job" in table_names:
|
||||
job_columns = {column["name"] for column in inspector.get_columns("job")}
|
||||
if "retry_count" not in job_columns:
|
||||
connection.execute(text("ALTER TABLE job ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0"))
|
||||
logger.warning("Applied SQLite compatibility schema patch table=job column=retry_count default=0")
|
||||
|
||||
if "revision" in table_names:
|
||||
revision_columns = {column["name"] for column in inspector.get_columns("revision")}
|
||||
if "source_id" in revision_columns:
|
||||
has_unique_source = False
|
||||
for index in inspector.get_indexes("revision"):
|
||||
if index.get("unique") and index.get("column_names") == ["source_id"]:
|
||||
has_unique_source = True
|
||||
break
|
||||
if not has_unique_source:
|
||||
connection.execute(
|
||||
text(
|
||||
"CREATE UNIQUE INDEX IF NOT EXISTS "
|
||||
"ux_revision_source_id ON revision(source_id)"
|
||||
)
|
||||
)
|
||||
logger.warning(
|
||||
"Applied SQLite compatibility schema patch "
|
||||
"table=revision unique_index=ux_revision_source_id"
|
||||
)
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
import logging
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from contextvars import ContextVar
|
||||
from dataclasses import dataclass
|
||||
from functools import partial
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
from sqlalchemy.ext.asyncio import create_async_engine
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
from sqlmodel.pool import StaticPool
|
||||
|
||||
from ..config import Settings
|
||||
from ..config import get_settings
|
||||
from .engine import get_database_url
|
||||
from .engine import get_engine
|
||||
from .session import get_session_factory
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -37,33 +35,6 @@ async def dispose_database_runtime() -> None:
|
||||
_runtime.set(None)
|
||||
|
||||
|
||||
def _to_async_database_url(database_url: str) -> str:
|
||||
"""Normalize configured database URL to an async SQLAlchemy driver URL."""
|
||||
if database_url.startswith("sqlite://") and not database_url.startswith("sqlite+aiosqlite://"):
|
||||
return database_url.replace("sqlite://", "sqlite+aiosqlite://", 1)
|
||||
if database_url.startswith("postgresql://") and not database_url.startswith("postgresql+asyncpg://"):
|
||||
return database_url.replace("postgresql://", "postgresql+asyncpg://", 1)
|
||||
return database_url
|
||||
|
||||
|
||||
def _build_engine(settings: Settings) -> AsyncEngine:
|
||||
database_url = _to_async_database_url(settings.database_url)
|
||||
engine_factory = partial(
|
||||
create_async_engine,
|
||||
url=database_url,
|
||||
echo=False,
|
||||
pool_pre_ping=True,
|
||||
)
|
||||
|
||||
if database_url.startswith("sqlite"):
|
||||
sqlite_connect_settings = {"check_same_thread": settings.sqlite_check_same_thread}
|
||||
engine_factory = partial(engine_factory, connect_args=sqlite_connect_settings)
|
||||
if ":memory:" in database_url:
|
||||
engine_factory = partial(engine_factory, poolclass=StaticPool)
|
||||
|
||||
return engine_factory()
|
||||
|
||||
|
||||
def initialize_database_runtime(*, settings: Settings | None = None) -> DatabaseRuntime:
|
||||
"""Initialize lifespan-owned async DB resources once per process."""
|
||||
runtime = _runtime.get()
|
||||
@@ -71,33 +42,10 @@ def initialize_database_runtime(*, settings: Settings | None = None) -> Database
|
||||
return runtime
|
||||
|
||||
active_settings = settings or get_settings()
|
||||
engine = _build_engine(active_settings)
|
||||
session_factory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
database_url = get_database_url(active_settings)
|
||||
engine = get_engine(database_url)
|
||||
session_factory = get_session_factory(database_url)
|
||||
runtime = DatabaseRuntime(engine=engine, session_factory=session_factory)
|
||||
_runtime.set(runtime)
|
||||
logger.debug("Initialized async database runtime for database_url=%s", engine.url)
|
||||
return runtime
|
||||
|
||||
|
||||
def get_engine(settings: Settings | None = None) -> AsyncEngine:
|
||||
"""Return the current async SQLAlchemy engine."""
|
||||
runtime = _runtime.get() or initialize_database_runtime(settings=settings)
|
||||
return runtime.engine
|
||||
|
||||
|
||||
def get_session_factory(settings: Settings | None = None) -> async_sessionmaker[AsyncSession]:
|
||||
"""Return the shared async session factory."""
|
||||
runtime = _runtime.get() or initialize_database_runtime(settings=settings)
|
||||
return runtime.session_factory
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def get_session(
|
||||
*,
|
||||
settings: Settings | None = None,
|
||||
session_factory: async_sessionmaker[AsyncSession] | None = None,
|
||||
) -> AsyncGenerator[AsyncSession]:
|
||||
"""Yield a database session and ensure cleanup."""
|
||||
active_session_factory = session_factory or get_session_factory(settings)
|
||||
async with active_session_factory() as session:
|
||||
yield session
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
from collections.abc import AsyncGenerator
|
||||
from contextlib import asynccontextmanager
|
||||
from functools import cache
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSessionTransaction
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..config import Settings
|
||||
from ..config import get_settings
|
||||
from .engine import dispose_engine
|
||||
from .engine import get_database_url
|
||||
from .engine import get_engine
|
||||
|
||||
type SessionFactory = async_sessionmaker[AsyncSession]
|
||||
|
||||
|
||||
@cache
|
||||
def get_session_factory(database_url: str) -> SessionFactory:
|
||||
return async_sessionmaker(
|
||||
bind=get_engine(database_url),
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
)
|
||||
|
||||
|
||||
def resolve_session_factory(
|
||||
database_url: str | None = None,
|
||||
*,
|
||||
settings: Settings | None = None,
|
||||
) -> SessionFactory:
|
||||
if database_url is not None:
|
||||
return get_session_factory(database_url)
|
||||
return get_session_factory(get_database_url(settings or get_settings()))
|
||||
|
||||
|
||||
type SessionFactoryDep = Annotated[SessionFactory, Depends(resolve_session_factory)]
|
||||
|
||||
|
||||
async def dispose_session_factory(database_url: str) -> None:
|
||||
get_session_factory.cache_clear()
|
||||
await dispose_engine(database_url)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def session_scope(
|
||||
*,
|
||||
settings: Settings | None = None,
|
||||
database_url: str | None = None,
|
||||
session_factory: SessionFactory | None = None,
|
||||
session: AsyncSession | None = None,
|
||||
) -> AsyncGenerator[AsyncSession]:
|
||||
if session is not None:
|
||||
yield session
|
||||
return
|
||||
|
||||
active_session_factory = session_factory or resolve_session_factory(
|
||||
database_url,
|
||||
settings=settings,
|
||||
)
|
||||
async with active_session_factory() as owned_session:
|
||||
yield owned_session
|
||||
|
||||
|
||||
type SessionScopeDep = Annotated[AsyncSession, Depends(session_scope)]
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def transaction_scope(
|
||||
*,
|
||||
settings: Settings | None = None,
|
||||
database_url: str | None = None,
|
||||
session_factory: SessionFactory | None = None,
|
||||
session: AsyncSession | AsyncSessionTransaction | None = None,
|
||||
) -> AsyncGenerator[AsyncSession | AsyncSessionTransaction]:
|
||||
match session:
|
||||
case AsyncSession() as async_session:
|
||||
if not async_session.in_transaction():
|
||||
raise RuntimeError("A supplied session must have an active transaction")
|
||||
yield async_session
|
||||
return
|
||||
case AsyncSessionTransaction() as async_transaction:
|
||||
yield async_transaction
|
||||
return
|
||||
|
||||
active_session_factory = session_factory or resolve_session_factory(
|
||||
database_url,
|
||||
settings=settings,
|
||||
)
|
||||
async with active_session_factory.begin() as owned_session:
|
||||
yield owned_session
|
||||
|
||||
|
||||
type TransactionScopeDep = Annotated[
|
||||
AsyncSession | AsyncSessionTransaction,
|
||||
Depends(transaction_scope),
|
||||
]
|
||||
@@ -1,110 +0,0 @@
|
||||
"""SQLModel domain models for the transcription system.
|
||||
|
||||
Core V1 lifecycle:
|
||||
Document -> one-to-many -> Source
|
||||
Document -> one-to-many -> Job
|
||||
Source -> one-to-one? -> Revision (optional)
|
||||
"""
|
||||
|
||||
from datetime import UTC
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import UniqueConstraint
|
||||
from sqlmodel import Field
|
||||
from sqlmodel import Relationship
|
||||
from sqlmodel import SQLModel
|
||||
|
||||
|
||||
class JobStatus(StrEnum):
|
||||
QUEUED = "queued"
|
||||
PROCESSING = "processing"
|
||||
TRANSCRIBED = "transcribed"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
class Document(SQLModel, table=True):
|
||||
"""An historical document."""
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
name: str
|
||||
|
||||
# Relationships
|
||||
jobs: list["Job"] = Relationship(back_populates="document")
|
||||
sources: list["Source"] = Relationship(back_populates="document")
|
||||
|
||||
|
||||
class Source(SQLModel, table=True):
|
||||
"""A document source (image or PDF)."""
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
document_id: UUID = Field(foreign_key="document.id")
|
||||
job_id: UUID = Field(foreign_key="job.id")
|
||||
upload_name: str
|
||||
"""The filename of the source that was uploaded for transcription."""
|
||||
filename: str
|
||||
"""The system generated unique source name."""
|
||||
file_path: str
|
||||
"""The location where the sources are stored on the local filesystem."""
|
||||
date_uploaded: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
|
||||
# Relationships
|
||||
document: Optional["Document"] = Relationship(back_populates="sources")
|
||||
job: Optional["Job"] = Relationship(back_populates="sources")
|
||||
revision: Optional["Revision"] = Relationship(
|
||||
back_populates="source",
|
||||
sa_relationship_kwargs={"uselist": False},
|
||||
)
|
||||
|
||||
|
||||
class Job(SQLModel, table=True):
|
||||
"""A transcription job tied to a single document."""
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
document_id: UUID = Field(foreign_key="document.id")
|
||||
status: JobStatus = Field(default=JobStatus.QUEUED)
|
||||
retry_count: int = Field(default=0, ge=0)
|
||||
date_created: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
date_updated: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
provider: str | None = None
|
||||
"""Name of the transcription provider used to generate this transcript."""
|
||||
model: str | None = None
|
||||
"""Model identifier used to generate this transcript."""
|
||||
prompt_name: str | None = None
|
||||
"""Name of the prompt used to generate this transcript."""
|
||||
text: str | None = None
|
||||
"""The transcribed text. This may be None if the job failed or is still in progress."""
|
||||
error_detail: str | None = None
|
||||
"""Details of any error that occurred during transcription."""
|
||||
|
||||
# Relationships
|
||||
document: Optional["Document"] = Relationship(back_populates="jobs")
|
||||
sources: list["Source"] = Relationship(back_populates="job")
|
||||
|
||||
@property
|
||||
def filename(self) -> str:
|
||||
"""Return the filename of the associated source, when available."""
|
||||
if not self.sources:
|
||||
return "unknown"
|
||||
return self.sources[0].filename
|
||||
|
||||
|
||||
class Revision(SQLModel, table=True):
|
||||
"""A revision of a transcription text."""
|
||||
|
||||
id: UUID = Field(default_factory=uuid4, primary_key=True)
|
||||
source_id: UUID = Field(foreign_key="source.id")
|
||||
"""ID for the associated source."""
|
||||
revision: int = Field(default=1, ge=1)
|
||||
"""Revision number of this transcription revision, starting at 1."""
|
||||
text: str
|
||||
"""The revised text."""
|
||||
date_created: datetime = Field(default_factory=lambda: datetime.now(UTC))
|
||||
|
||||
__table_args__ = (UniqueConstraint("source_id", name="uq_revision_source_id"),)
|
||||
|
||||
# Relationships
|
||||
source: Optional["Source"] = Relationship(back_populates="revision")
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Provider interfaces and shared types for transcription adapters."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from typing import Protocol
|
||||
|
||||
|
||||
@@ -24,15 +25,30 @@ class TranscriptionResult:
|
||||
provider: str
|
||||
prompt_name: str
|
||||
model: str
|
||||
prompt_hash: str | None = None
|
||||
system_prompt: str | None = None
|
||||
user_prompt: str | None = None
|
||||
temperature: float | None = None
|
||||
top_p: float | None = None
|
||||
finish_reason: str | None = None
|
||||
usage_input_tokens: int | None = None
|
||||
usage_output_tokens: int | None = None
|
||||
usage_total_tokens: int | None = None
|
||||
ai_metadata: dict[str, Any] | None = None
|
||||
raw_api_response: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class TranscriptionProvider(Protocol):
|
||||
"""Contract every transcription provider adapter must satisfy."""
|
||||
|
||||
async def transcribe(self, *, prompt_text: str, image_bytes: bytes, mime_type: str) -> TranscriptionResult:
|
||||
async def transcribe(
|
||||
self,
|
||||
*,
|
||||
prompt_text: str,
|
||||
image_bytes: bytes,
|
||||
mime_type: str,
|
||||
temperature: float | None = None,
|
||||
top_p: float | None = None,
|
||||
) -> TranscriptionResult:
|
||||
"""Transcribe the provided image according to the prompt text."""
|
||||
...
|
||||
|
||||
@@ -31,6 +31,8 @@ class OpenRouterRequest:
|
||||
messages: list[dict[str, Any]]
|
||||
http_referer: str | None
|
||||
x_open_router_title: str | None
|
||||
temperature: float | None
|
||||
top_p: float | None
|
||||
|
||||
|
||||
class OpenRouterTranscriptionProvider:
|
||||
@@ -46,15 +48,31 @@ class OpenRouterTranscriptionProvider:
|
||||
"""Return the resolved OpenRouter model slug."""
|
||||
return self._model
|
||||
|
||||
async def transcribe(self, *, prompt_text: str, image_bytes: bytes, mime_type: str) -> TranscriptionResult:
|
||||
async def transcribe(
|
||||
self,
|
||||
*,
|
||||
prompt_text: str,
|
||||
image_bytes: bytes,
|
||||
mime_type: str,
|
||||
temperature: float | None = None,
|
||||
top_p: float | None = None,
|
||||
) -> TranscriptionResult:
|
||||
"""Send prompt + image to OpenRouter and return normalized text output."""
|
||||
request = self._build_request(prompt_text=prompt_text, image_bytes=image_bytes, mime_type=mime_type)
|
||||
request = self._build_request(
|
||||
prompt_text=prompt_text,
|
||||
image_bytes=image_bytes,
|
||||
mime_type=mime_type,
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
)
|
||||
try:
|
||||
response = await self._client.chat.send_async(
|
||||
messages=cast(list[ChatMessagesTypedDict], request.messages),
|
||||
model=request.model,
|
||||
http_referer=request.http_referer,
|
||||
x_open_router_title=request.x_open_router_title,
|
||||
temperature=request.temperature,
|
||||
top_p=request.top_p,
|
||||
)
|
||||
except Exception as exc:
|
||||
message = str(exc).lower()
|
||||
@@ -66,19 +84,102 @@ class OpenRouterTranscriptionProvider:
|
||||
model = self._get_optional_attr(response, "model") or self.model
|
||||
finish_reason = self._extract_finish_reason(response)
|
||||
usage_input_tokens, usage_output_tokens, usage_total_tokens = self._extract_usage(response)
|
||||
logger.info("OpenRouter transcription completed using model=%s", model)
|
||||
return TranscriptionResult(
|
||||
text=text,
|
||||
provider="openrouter",
|
||||
prompt_name="",
|
||||
model=model,
|
||||
ai_metadata = self._build_ai_metadata(
|
||||
finish_reason=finish_reason,
|
||||
usage_input_tokens=usage_input_tokens,
|
||||
usage_output_tokens=usage_output_tokens,
|
||||
usage_total_tokens=usage_total_tokens,
|
||||
)
|
||||
raw_api_response = self._coerce_raw_response(response)
|
||||
logger.info("OpenRouter transcription completed using model=%s", model)
|
||||
return TranscriptionResult(
|
||||
text=text,
|
||||
provider="openrouter",
|
||||
prompt_name="",
|
||||
prompt_hash=None,
|
||||
system_prompt=None,
|
||||
user_prompt=prompt_text,
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
model=model,
|
||||
finish_reason=finish_reason,
|
||||
usage_input_tokens=usage_input_tokens,
|
||||
usage_output_tokens=usage_output_tokens,
|
||||
usage_total_tokens=usage_total_tokens,
|
||||
ai_metadata=ai_metadata,
|
||||
raw_api_response=raw_api_response,
|
||||
)
|
||||
|
||||
def _build_request(self, *, prompt_text: str, image_bytes: bytes, mime_type: str) -> OpenRouterRequest:
|
||||
def _build_ai_metadata(
|
||||
self,
|
||||
*,
|
||||
finish_reason: str | None,
|
||||
usage_input_tokens: int | None,
|
||||
usage_output_tokens: int | None,
|
||||
usage_total_tokens: int | None,
|
||||
) -> dict[str, Any] | None:
|
||||
metadata: dict[str, Any] = {}
|
||||
if finish_reason is not None:
|
||||
metadata["finish_reason"] = finish_reason
|
||||
|
||||
usage: dict[str, int] = {}
|
||||
if usage_input_tokens is not None:
|
||||
usage["input_tokens"] = usage_input_tokens
|
||||
if usage_output_tokens is not None:
|
||||
usage["output_tokens"] = usage_output_tokens
|
||||
if usage_total_tokens is not None:
|
||||
usage["total_tokens"] = usage_total_tokens
|
||||
|
||||
if usage:
|
||||
metadata["usage"] = usage
|
||||
|
||||
return metadata or None
|
||||
|
||||
def _coerce_raw_response(self, response: Any) -> dict[str, Any] | None:
|
||||
payload = self._to_json_compatible(response)
|
||||
if payload is None:
|
||||
return None
|
||||
if isinstance(payload, dict):
|
||||
return payload
|
||||
return {"response": payload}
|
||||
|
||||
def _to_json_compatible(self, value: Any) -> Any:
|
||||
if value is None or isinstance(value, str | int | float | bool):
|
||||
return value
|
||||
|
||||
if isinstance(value, dict):
|
||||
return {str(key): self._to_json_compatible(item) for key, item in value.items()}
|
||||
|
||||
if isinstance(value, list | tuple | set):
|
||||
return [self._to_json_compatible(item) for item in value]
|
||||
|
||||
for method_name in ("model_dump", "dict", "to_dict"):
|
||||
serializer = getattr(value, method_name, None)
|
||||
if callable(serializer):
|
||||
try:
|
||||
return self._to_json_compatible(serializer())
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
|
||||
object_dict = getattr(value, "__dict__", None)
|
||||
if isinstance(object_dict, dict):
|
||||
return {
|
||||
str(key): self._to_json_compatible(item)
|
||||
for key, item in object_dict.items()
|
||||
if not str(key).startswith("_")
|
||||
}
|
||||
|
||||
return repr(value)
|
||||
|
||||
def _build_request(
|
||||
self,
|
||||
*,
|
||||
prompt_text: str,
|
||||
image_bytes: bytes,
|
||||
mime_type: str,
|
||||
temperature: float | None,
|
||||
top_p: float | None,
|
||||
) -> OpenRouterRequest:
|
||||
image_b64 = base64.b64encode(image_bytes).decode("ascii")
|
||||
data_url = f"data:{mime_type};base64,{image_b64}"
|
||||
|
||||
@@ -97,6 +198,8 @@ class OpenRouterTranscriptionProvider:
|
||||
messages=messages,
|
||||
http_referer=self._settings.openrouter_http_referer,
|
||||
x_open_router_title=self._settings.openrouter_app_title,
|
||||
temperature=temperature,
|
||||
top_p=top_p,
|
||||
)
|
||||
|
||||
def _extract_text(self, response: Any) -> str:
|
||||
|
||||
@@ -8,7 +8,8 @@ from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..config import Settings
|
||||
from ..config import get_settings
|
||||
from ..db.runtime import get_session_factory
|
||||
from ..db.session import resolve_session_factory
|
||||
from ..db.session import session_scope
|
||||
|
||||
|
||||
class ServiceBase(ABC):
|
||||
@@ -24,19 +25,17 @@ class ServiceBase(ABC):
|
||||
queue: asyncio.Queue | None = None,
|
||||
):
|
||||
self.settings = get_settings()
|
||||
self.session_factory = session_factory or get_session_factory()
|
||||
self.session_factory = session_factory or resolve_session_factory()
|
||||
self.queue = queue or asyncio.Queue()
|
||||
|
||||
@asynccontextmanager
|
||||
async def _session_scope(self, session: AsyncSession | None = None):
|
||||
"""Provide a transactional scope around a series of operations."""
|
||||
if session is not None:
|
||||
# Reuse the provided session if one is passed in
|
||||
yield session
|
||||
else:
|
||||
# Otherwise, create a new session for this scope
|
||||
async with self.session_factory() as new_session:
|
||||
yield new_session
|
||||
async with session_scope(
|
||||
session_factory=self.session_factory,
|
||||
session=session,
|
||||
) as active_session:
|
||||
yield active_session
|
||||
|
||||
async def _finalize(
|
||||
self,
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import logging
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
@@ -9,9 +12,11 @@ from sqlalchemy.orm import selectinload
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..db.models import Document
|
||||
from ..db.models import DocumentPerson
|
||||
from ..db.models import Person
|
||||
from ..errors import AppError
|
||||
from ..errors import ErrorCategory
|
||||
from ..models import Document
|
||||
from .base import ServiceBase
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -33,6 +38,14 @@ class DocumentAlreadyExistsError(DocumentError):
|
||||
"""Raised when a document with the same name already exists in the database."""
|
||||
|
||||
|
||||
class DocumentDeleteBlockedError(DocumentError):
|
||||
"""Raised when a document delete is blocked by dependent records."""
|
||||
|
||||
|
||||
class PersonDeleteBlockedError(DocumentError):
|
||||
"""Raised when a person delete is blocked by linked documents."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UploadJobResult:
|
||||
"""Summary of created upload records."""
|
||||
@@ -100,14 +113,186 @@ class DocumentService(ServiceBase):
|
||||
async def update_document(self, document: Document, *, session: AsyncSession | None = None) -> Document:
|
||||
"""Update an existing document in the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
document.updated_at = datetime.now(UTC)
|
||||
merged = await _session.merge(document)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(merged,))
|
||||
return merged
|
||||
|
||||
async def delete_document(self, document: Document, *, session: AsyncSession | None = None) -> None:
|
||||
"""Delete a document from the database."""
|
||||
document_id = document.id
|
||||
async with self._session_scope(session) as _session:
|
||||
await _session.delete(document)
|
||||
existing = await _session.get(
|
||||
Document,
|
||||
document.id,
|
||||
options=(
|
||||
selectinload(Document.jobs), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Document.sources), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Document.document_people), # pyright: ignore[reportArgumentType]
|
||||
),
|
||||
)
|
||||
if existing is None:
|
||||
raise DocumentError(
|
||||
f"Document with id {document.id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the document id and retry.",
|
||||
)
|
||||
|
||||
has_jobs = bool(existing.jobs)
|
||||
has_sources = bool(existing.sources)
|
||||
if has_jobs or has_sources:
|
||||
blocked_by: list[str] = []
|
||||
if has_sources:
|
||||
blocked_by.append("Sources")
|
||||
if has_jobs:
|
||||
blocked_by.append("Jobs")
|
||||
raise DocumentDeleteBlockedError(
|
||||
f"Document delete blocked by related records: {', '.join(blocked_by)}",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Remove related Sources and Jobs first, then retry deletion.",
|
||||
)
|
||||
|
||||
for link in list(existing.document_people):
|
||||
await _session.delete(link)
|
||||
|
||||
await _session.delete(existing)
|
||||
await self._finalize(session=_session, caller_session=session)
|
||||
|
||||
self._delete_document_storage_folder(document_id=document_id)
|
||||
|
||||
def _delete_document_storage_folder(self, *, document_id: UUID) -> None:
|
||||
"""Best-effort cleanup for document-scoped source storage."""
|
||||
document_dir = self.settings.upload_dir / "documents" / str(document_id)
|
||||
if not document_dir.exists():
|
||||
return
|
||||
|
||||
try:
|
||||
shutil.rmtree(document_dir)
|
||||
logger.info("Deleted document storage folder: %s", document_dir)
|
||||
except OSError:
|
||||
logger.warning("Failed to delete document storage folder: %s", document_dir)
|
||||
|
||||
async def create_person(self, person: Person, *, session: AsyncSession | None = None) -> Person:
|
||||
"""Create a new person in the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
_session.add(person)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(person,))
|
||||
return person
|
||||
|
||||
async def read_person(self, person_id: UUID, *, session: AsyncSession | None = None) -> Person:
|
||||
"""Read an existing person from the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
person = await _session.get(Person, person_id)
|
||||
if person is None:
|
||||
raise DocumentError(
|
||||
f"Person with id {person_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the person id and retry.",
|
||||
)
|
||||
return person
|
||||
|
||||
async def read_person_detail(self, person_id: UUID, *, session: AsyncSession | None = None) -> Person:
|
||||
"""Read a person with eagerly loaded document links for UI detail rendering."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = (
|
||||
select(Person)
|
||||
.options(
|
||||
selectinload(Person.document_people).selectinload(DocumentPerson.document), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
.where(Person.id == person_id)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
person = (await _session.exec(query)).first()
|
||||
|
||||
if person is None:
|
||||
raise DocumentError(
|
||||
f"Person with id {person_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the person id and retry.",
|
||||
)
|
||||
return person
|
||||
|
||||
async def update_person(self, person: Person, *, session: AsyncSession | None = None) -> Person:
|
||||
"""Update an existing person in the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
person.updated_at = datetime.now(UTC)
|
||||
merged = await _session.merge(person)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(merged,))
|
||||
return merged
|
||||
|
||||
async def delete_person(self, person: Person, *, session: AsyncSession | None = None) -> None:
|
||||
"""Delete a person from the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
existing = await _session.get(
|
||||
Person,
|
||||
person.id,
|
||||
options=(
|
||||
selectinload(Person.document_people), # pyright: ignore[reportArgumentType]
|
||||
),
|
||||
)
|
||||
if existing is None:
|
||||
raise DocumentError(
|
||||
f"Person with id {person.id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the person id and retry.",
|
||||
)
|
||||
|
||||
for link in list(existing.document_people):
|
||||
await _session.delete(link)
|
||||
|
||||
await _session.delete(existing)
|
||||
await self._finalize(session=_session, caller_session=session)
|
||||
|
||||
async def create_document_person(
|
||||
self,
|
||||
document_person: DocumentPerson,
|
||||
*,
|
||||
session: AsyncSession | None = None,
|
||||
) -> DocumentPerson:
|
||||
"""Create a document-person association in the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
_session.add(document_person)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(document_person,))
|
||||
return document_person
|
||||
|
||||
async def read_document_person(
|
||||
self,
|
||||
document_person_id: UUID,
|
||||
*,
|
||||
session: AsyncSession | None = None,
|
||||
) -> DocumentPerson:
|
||||
"""Read an existing document-person association from the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
document_person = await _session.get(DocumentPerson, document_person_id)
|
||||
if document_person is None:
|
||||
raise DocumentError(
|
||||
f"DocumentPerson with id {document_person_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the document-person id and retry.",
|
||||
)
|
||||
return document_person
|
||||
|
||||
async def update_document_person(
|
||||
self,
|
||||
document_person: DocumentPerson,
|
||||
*,
|
||||
session: AsyncSession | None = None,
|
||||
) -> DocumentPerson:
|
||||
"""Update an existing document-person association in the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
merged = await _session.merge(document_person)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(merged,))
|
||||
return merged
|
||||
|
||||
async def delete_document_person(
|
||||
self,
|
||||
document_person: DocumentPerson,
|
||||
*,
|
||||
session: AsyncSession | None = None,
|
||||
) -> None:
|
||||
"""Delete a document-person association from the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
await _session.delete(document_person)
|
||||
await self._finalize(session=_session, caller_session=session)
|
||||
|
||||
# Query Operations
|
||||
@@ -128,3 +313,51 @@ class DocumentService(ServiceBase):
|
||||
async with self._session_scope(session) as _session:
|
||||
result = await _session.exec(select(Document))
|
||||
return result.all()
|
||||
|
||||
async def read_document_detail(self, document_id: UUID, *, session: AsyncSession | None = None) -> Document:
|
||||
"""Read a document with eagerly loaded relations for UI detail rendering."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = (
|
||||
select(Document)
|
||||
.options(
|
||||
selectinload(Document.jobs), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Document.sources), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Document.document_people).selectinload(DocumentPerson.person), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
.where(Document.id == document_id)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
document = (await _session.exec(query)).first()
|
||||
if document is None:
|
||||
raise DocumentError(
|
||||
f"Document with id {document_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the document id and retry.",
|
||||
)
|
||||
return document
|
||||
|
||||
async def list_people(self, *, session: AsyncSession | None = None) -> Sequence[Person]:
|
||||
"""List all people in the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
result = await _session.exec(select(Person))
|
||||
return result.all()
|
||||
|
||||
async def list_document_people(
|
||||
self,
|
||||
*,
|
||||
document_id: UUID | None = None,
|
||||
person_id: UUID | None = None,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Sequence[DocumentPerson]:
|
||||
"""List document-person associations, optionally filtered by document or person."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = select(DocumentPerson).options(
|
||||
selectinload(DocumentPerson.document), # pyright: ignore[reportArgumentType]
|
||||
selectinload(DocumentPerson.person), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
if document_id is not None:
|
||||
query = query.where(DocumentPerson.document_id == document_id)
|
||||
if person_id is not None:
|
||||
query = query.where(DocumentPerson.person_id == person_id)
|
||||
result = await _session.exec(query)
|
||||
return result.all()
|
||||
|
||||
@@ -7,12 +7,28 @@ from sqlalchemy.orm import selectinload
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..models import Job
|
||||
from ..models import JobStatus
|
||||
from ..models import Source
|
||||
from ..errors import AppError
|
||||
from ..errors import ErrorCategory
|
||||
from ..db.models import Job
|
||||
from ..db.models import JobSource
|
||||
from ..db.models import JobSourceStatus
|
||||
from ..db.models import JobStatus
|
||||
from ..db.models import Source
|
||||
from .base import ServiceBase
|
||||
|
||||
|
||||
class JobDeleteBlockedError(AppError):
|
||||
"""Raised when a job delete operation is blocked by lifecycle policy."""
|
||||
|
||||
|
||||
class JobCancelBlockedError(AppError):
|
||||
"""Raised when a job cancel operation is blocked by lifecycle policy."""
|
||||
|
||||
|
||||
class JobResubmitBlockedError(AppError):
|
||||
"""Raised when a job resubmit operation is blocked by lifecycle policy."""
|
||||
|
||||
|
||||
class JobService(ServiceBase):
|
||||
"""Thin service class for managing jobs in the database."""
|
||||
|
||||
@@ -38,7 +54,7 @@ class JobService(ServiceBase):
|
||||
select(Job)
|
||||
.options(
|
||||
selectinload(Job.document), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Job.sources).selectinload(Source.revision), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Job.job_sources).selectinload(JobSource.source), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
.where(Job.id == job_id)
|
||||
.execution_options(populate_existing=True)
|
||||
@@ -74,12 +90,12 @@ class JobService(ServiceBase):
|
||||
async with self._session_scope(session) as _session:
|
||||
query = select(Job).options(
|
||||
selectinload(Job.document), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Job.sources), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Job.job_sources).selectinload(JobSource.source), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
if status is not None:
|
||||
query = query.where(Job.status == status)
|
||||
if filename is not None:
|
||||
query = query.where(Job.sources.any(Source.filename == filename))
|
||||
query = query.where(Job.job_sources.any(JobSource.source.has(Source.filename == filename)))
|
||||
result = await _session.exec(query)
|
||||
return result.all()
|
||||
|
||||
@@ -94,7 +110,7 @@ class JobService(ServiceBase):
|
||||
async with self._session_scope(session) as _session:
|
||||
query = select(Job).options(
|
||||
selectinload(Job.document), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Job.sources), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Job.job_sources).selectinload(JobSource.source), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
result = await _session.exec(query)
|
||||
return result.all()
|
||||
@@ -151,10 +167,11 @@ class JobService(ServiceBase):
|
||||
select(Job)
|
||||
.options(
|
||||
selectinload(Job.document), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Job.sources).selectinload(Source.revision), # pyright: ignore[reportArgumentType]
|
||||
selectinload(Job.job_sources).selectinload(JobSource.source), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
.where(Job.status == JobStatus.QUEUED)
|
||||
.order_by(Job.date_created) # pyright: ignore[reportArgumentType]
|
||||
# Break ties by id so "next" is stable when two rows share close timestamps.
|
||||
.order_by(Job.date_created, Job.id) # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
return (await _session.exec(query)).first()
|
||||
|
||||
@@ -170,11 +187,7 @@ class JobService(ServiceBase):
|
||||
``stale_before`` are considered stale and re-queued.
|
||||
"""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = (
|
||||
select(Job)
|
||||
.where(Job.status == JobStatus.PROCESSING)
|
||||
.where(Job.date_updated < stale_before)
|
||||
)
|
||||
query = select(Job).where(Job.status == JobStatus.PROCESSING).where(Job.date_updated < stale_before)
|
||||
stale_jobs = (await _session.exec(query)).all()
|
||||
if not stale_jobs:
|
||||
return 0
|
||||
@@ -186,3 +199,118 @@ class JobService(ServiceBase):
|
||||
|
||||
await self._finalize(session=_session, caller_session=session, refresh=stale_jobs)
|
||||
return len(stale_jobs)
|
||||
|
||||
async def delete_job_with_guardrails(self, *, job_id: UUID, session: AsyncSession | None = None) -> None:
|
||||
"""Delete a job with lifecycle guardrails and dependent cleanup policy.
|
||||
|
||||
Policy:
|
||||
- Block when the job is actively processing.
|
||||
- Otherwise remove related JobSource rows, then delete the job.
|
||||
"""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = (
|
||||
select(Job)
|
||||
.options(selectinload(Job.job_sources)) # pyright: ignore[reportArgumentType]
|
||||
.where(Job.id == job_id)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
job = (await _session.exec(query)).first()
|
||||
if job is None:
|
||||
raise ValueError(f"Job with id {job_id} not found")
|
||||
|
||||
if job.status == JobStatus.PROCESSING:
|
||||
raise JobDeleteBlockedError(
|
||||
"Job delete blocked while status is processing",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Wait for processing to complete, or move the job out of processing before deleting.",
|
||||
)
|
||||
|
||||
for job_source in list(job.job_sources):
|
||||
await _session.delete(job_source)
|
||||
|
||||
await _session.delete(job)
|
||||
await self._finalize(session=_session, caller_session=session)
|
||||
|
||||
async def cancel_job(self, *, job_id: UUID, session: AsyncSession | None = None) -> Job:
|
||||
"""Cancel a queued/processing job and stop remaining source work."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = (
|
||||
select(Job)
|
||||
.options(
|
||||
selectinload(Job.job_sources).selectinload(JobSource.source), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
.where(Job.id == job_id)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
job = (await _session.exec(query)).first()
|
||||
if job is None:
|
||||
raise ValueError(f"Job with id {job_id} not found")
|
||||
|
||||
if job.status in {JobStatus.TRANSCRIBED, JobStatus.COMPLETED}:
|
||||
raise JobCancelBlockedError(
|
||||
"Job cancel is not allowed for transcribed/completed jobs",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Use resubmit for reprocessing needs, or leave the terminal job unchanged.",
|
||||
)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
job.status = JobStatus.FAILED
|
||||
job.date_updated = now
|
||||
|
||||
for job_source in job.job_sources:
|
||||
if job_source.status == JobSourceStatus.TRANSCRIBED:
|
||||
continue
|
||||
job_source.status = JobSourceStatus.FAILED
|
||||
job_source.raw_transcription = None
|
||||
job_source.error_detail = "Cancelled by user"
|
||||
job_source.executed_at = now
|
||||
if job_source.source is not None:
|
||||
job_source.source.raw_transcription = None
|
||||
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(job,))
|
||||
return job
|
||||
|
||||
async def resubmit_failed_sources(self, *, job_id: UUID, session: AsyncSession | None = None) -> int:
|
||||
"""Reset failed source executions and queue the job for reprocessing."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = (
|
||||
select(Job)
|
||||
.options(
|
||||
selectinload(Job.job_sources).selectinload(JobSource.source), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
.where(Job.id == job_id)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
job = (await _session.exec(query)).first()
|
||||
if job is None:
|
||||
raise ValueError(f"Job with id {job_id} not found")
|
||||
|
||||
if job.status == JobStatus.PROCESSING:
|
||||
raise JobResubmitBlockedError(
|
||||
"Job resubmit is blocked while processing is active",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Cancel processing first, then resubmit remaining sources.",
|
||||
)
|
||||
|
||||
candidates = [job_source for job_source in job.job_sources if job_source.status == JobSourceStatus.FAILED]
|
||||
if not candidates:
|
||||
raise JobResubmitBlockedError(
|
||||
"Job has no failed sources to resubmit",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Only failed sources can be resubmitted.",
|
||||
)
|
||||
|
||||
now = datetime.now(UTC)
|
||||
for job_source in candidates:
|
||||
job_source.status = JobSourceStatus.PENDING
|
||||
job_source.raw_transcription = None
|
||||
job_source.error_detail = None
|
||||
job_source.executed_at = now
|
||||
if job_source.source is not None:
|
||||
job_source.source.raw_transcription = None
|
||||
|
||||
job.status = JobStatus.QUEUED
|
||||
job.date_updated = now
|
||||
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(job,))
|
||||
return len(candidates)
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlmodel import select
|
||||
from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from transcription.config import Settings
|
||||
@@ -11,20 +16,44 @@ from transcription.config import get_settings
|
||||
from transcription.errors import AppError
|
||||
from transcription.errors import ErrorCategory
|
||||
|
||||
from ..models import Document
|
||||
from ..models import Job
|
||||
from ..models import Source
|
||||
from ..db.models import Document
|
||||
from ..db.models import Job
|
||||
from ..db.models import JobSource
|
||||
from ..db.models import JobSourceStatus
|
||||
from ..db.models import Source
|
||||
from .documents import UploadJobResult
|
||||
from .transcription import build_prompt_execution
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SUPPORTED_UPLOAD_EXTENSIONS = {".jpg", ".jpeg", ".png", ".tif", ".tiff", ".pdf"}
|
||||
SUPPORTED_PORTRAIT_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff"}
|
||||
|
||||
|
||||
class UploadError(AppError):
|
||||
"""Raised when uploaded content cannot be persisted safely."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class JobCreateResult:
|
||||
"""Summary of explicit Job create records."""
|
||||
|
||||
document_id: UUID
|
||||
job_id: UUID
|
||||
source_ids: tuple[UUID, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PendingStoredUpload:
|
||||
"""Pre-staged upload artifact tied to a source id."""
|
||||
|
||||
source_id: UUID
|
||||
original_filename: str
|
||||
stored_path: Path
|
||||
file_hash: str
|
||||
file_size_bytes: int
|
||||
|
||||
|
||||
async def create_upload_job(
|
||||
*,
|
||||
filename: str,
|
||||
@@ -34,16 +63,27 @@ async def create_upload_job(
|
||||
) -> UploadJobResult:
|
||||
"""Create upload-backed document and queued job records."""
|
||||
runtime_settings = settings or get_settings()
|
||||
prompt_execution = build_prompt_execution(settings=runtime_settings)
|
||||
document_id = uuid4()
|
||||
source_id = uuid4()
|
||||
stored_path = store_file(
|
||||
filename=filename,
|
||||
file_bytes=file_bytes,
|
||||
settings=runtime_settings,
|
||||
relative_directory=Path("documents") / str(document_id),
|
||||
filename_stem=str(source_id),
|
||||
)
|
||||
file_hash, file_size_bytes = _compute_file_metadata(file_bytes)
|
||||
try:
|
||||
document, job = await _create_upload_records(
|
||||
session=session,
|
||||
document_id=document_id,
|
||||
source_id=source_id,
|
||||
original_filename=filename,
|
||||
stored_path=stored_path,
|
||||
file_hash=file_hash,
|
||||
file_size_bytes=file_size_bytes,
|
||||
prompt_execution=prompt_execution,
|
||||
)
|
||||
except Exception as exc:
|
||||
_best_effort_delete(stored_path)
|
||||
@@ -63,30 +103,122 @@ async def create_upload_job(
|
||||
)
|
||||
|
||||
|
||||
async def create_job_for_document(
|
||||
*,
|
||||
document_id: UUID,
|
||||
uploads: Sequence[tuple[str, bytes]],
|
||||
session: AsyncSession,
|
||||
provider: str | None = None,
|
||||
model: str | None = None,
|
||||
settings: Settings | None = None,
|
||||
) -> JobCreateResult:
|
||||
"""Create a queued job for an existing document with one or more uploaded sources."""
|
||||
if not uploads:
|
||||
raise UploadError(
|
||||
"At least one upload is required to create a job",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Upload one or more files and try again.",
|
||||
)
|
||||
|
||||
runtime_settings = settings or get_settings()
|
||||
prompt_execution = build_prompt_execution(settings=runtime_settings)
|
||||
sorted_uploads = sorted(uploads, key=lambda item: Path(item[0]).name.casefold())
|
||||
stored_uploads: list[PendingStoredUpload] = []
|
||||
for filename, file_bytes in sorted_uploads:
|
||||
source_id = uuid4()
|
||||
stored_uploads.append(
|
||||
PendingStoredUpload(
|
||||
source_id=source_id,
|
||||
original_filename=filename,
|
||||
stored_path=store_file(
|
||||
filename=filename,
|
||||
file_bytes=file_bytes,
|
||||
settings=runtime_settings,
|
||||
relative_directory=Path("documents") / str(document_id),
|
||||
filename_stem=str(source_id),
|
||||
),
|
||||
file_hash=_compute_file_hash(file_bytes),
|
||||
file_size_bytes=len(file_bytes),
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
job, source_ids = await _create_job_for_document_records(
|
||||
session=session,
|
||||
document_id=document_id,
|
||||
stored_uploads=stored_uploads,
|
||||
provider=provider,
|
||||
model=model,
|
||||
prompt_execution=prompt_execution,
|
||||
)
|
||||
except Exception as exc:
|
||||
for upload in stored_uploads:
|
||||
_best_effort_delete(upload.stored_path)
|
||||
raise UploadError(
|
||||
"Failed to create job records from uploads",
|
||||
category=ErrorCategory.INFRA_TRANSIENT,
|
||||
suggestion="Retry creation. If this keeps happening, verify database availability.",
|
||||
retriable=True,
|
||||
) from exc
|
||||
|
||||
logger.info("Created explicit job document_id=%s job_id=%s sources=%s", document_id, job.id, len(source_ids))
|
||||
return JobCreateResult(
|
||||
document_id=document_id,
|
||||
job_id=job.id,
|
||||
source_ids=tuple(source_ids),
|
||||
)
|
||||
|
||||
|
||||
async def _create_upload_records(
|
||||
*,
|
||||
session: AsyncSession,
|
||||
document_id: UUID,
|
||||
source_id: UUID,
|
||||
original_filename: str,
|
||||
stored_path: Path,
|
||||
file_hash: str,
|
||||
file_size_bytes: int,
|
||||
prompt_execution,
|
||||
) -> tuple[Document, Job]:
|
||||
document = Document(
|
||||
id=document_id,
|
||||
name=Path(original_filename).name,
|
||||
)
|
||||
session.add(document)
|
||||
await session.flush()
|
||||
|
||||
job = Job(document_id=document.id)
|
||||
job = Job(
|
||||
document_id=document.id,
|
||||
prompt_name=prompt_execution.prompt_name,
|
||||
prompt_hash=prompt_execution.prompt_hash,
|
||||
system_prompt=prompt_execution.system_prompt,
|
||||
user_prompt=prompt_execution.user_prompt,
|
||||
temperature=prompt_execution.temperature,
|
||||
top_p=prompt_execution.top_p,
|
||||
)
|
||||
session.add(job)
|
||||
await session.flush()
|
||||
|
||||
source = Source(
|
||||
id=source_id,
|
||||
document_id=document.id,
|
||||
job_id=job.id,
|
||||
page_number=1,
|
||||
upload_name=Path(original_filename).name,
|
||||
filename=stored_path.name,
|
||||
file_path=str(stored_path),
|
||||
file_hash=file_hash,
|
||||
file_size_bytes=file_size_bytes,
|
||||
)
|
||||
session.add(source)
|
||||
await session.flush()
|
||||
|
||||
session.add(
|
||||
JobSource(
|
||||
job_id=job.id,
|
||||
source_id=source.id,
|
||||
status=JobSourceStatus.PENDING,
|
||||
)
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(document)
|
||||
@@ -94,6 +226,71 @@ async def _create_upload_records(
|
||||
return document, job
|
||||
|
||||
|
||||
async def _create_job_for_document_records(
|
||||
*,
|
||||
session: AsyncSession,
|
||||
document_id: UUID,
|
||||
stored_uploads: Sequence[PendingStoredUpload],
|
||||
provider: str | None,
|
||||
model: str | None,
|
||||
prompt_execution,
|
||||
) -> tuple[Job, list[UUID]]:
|
||||
document = await session.get(Document, document_id)
|
||||
if document is None:
|
||||
raise UploadError(
|
||||
f"Document with id {document_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Select an existing document and retry.",
|
||||
)
|
||||
|
||||
existing_sources = (
|
||||
await session.exec(select(Source).where(Source.document_id == document_id))
|
||||
).all()
|
||||
next_page_number = (max((source.page_number for source in existing_sources), default=0) + 1)
|
||||
|
||||
job = Job(
|
||||
document_id=document_id,
|
||||
provider=(provider or None),
|
||||
model=(model or None),
|
||||
prompt_name=prompt_execution.prompt_name,
|
||||
prompt_hash=prompt_execution.prompt_hash,
|
||||
system_prompt=prompt_execution.system_prompt,
|
||||
user_prompt=prompt_execution.user_prompt,
|
||||
temperature=prompt_execution.temperature,
|
||||
top_p=prompt_execution.top_p,
|
||||
)
|
||||
session.add(job)
|
||||
await session.flush()
|
||||
|
||||
source_ids: list[UUID] = []
|
||||
for page_offset, upload in enumerate(stored_uploads):
|
||||
source = Source(
|
||||
id=upload.source_id,
|
||||
document_id=document_id,
|
||||
page_number=next_page_number + page_offset,
|
||||
upload_name=Path(upload.original_filename).name,
|
||||
filename=upload.stored_path.name,
|
||||
file_path=str(upload.stored_path),
|
||||
file_hash=upload.file_hash,
|
||||
file_size_bytes=upload.file_size_bytes,
|
||||
)
|
||||
session.add(source)
|
||||
await session.flush()
|
||||
source_ids.append(source.id)
|
||||
|
||||
session.add(
|
||||
JobSource(
|
||||
job_id=job.id,
|
||||
source_id=source.id,
|
||||
status=JobSourceStatus.PENDING,
|
||||
)
|
||||
)
|
||||
|
||||
await session.commit()
|
||||
await session.refresh(job)
|
||||
return job, source_ids
|
||||
|
||||
|
||||
def _best_effort_delete(path: Path) -> None:
|
||||
try:
|
||||
if path.exists():
|
||||
@@ -102,16 +299,66 @@ def _best_effort_delete(path: Path) -> None:
|
||||
logger.warning("Failed to clean up upload file after DB error: %s", path)
|
||||
|
||||
|
||||
def store_file(*, filename: str, file_bytes: bytes, settings: Settings | None = None) -> Path:
|
||||
def _compute_file_hash(file_bytes: bytes) -> str:
|
||||
return hashlib.sha256(file_bytes).hexdigest()
|
||||
|
||||
|
||||
def _compute_file_metadata(file_bytes: bytes) -> tuple[str, int]:
|
||||
return _compute_file_hash(file_bytes), len(file_bytes)
|
||||
|
||||
|
||||
def store_file(
|
||||
*,
|
||||
filename: str,
|
||||
file_bytes: bytes,
|
||||
settings: Settings | None = None,
|
||||
relative_directory: Path | None = None,
|
||||
filename_stem: str | None = None,
|
||||
) -> Path:
|
||||
"""Persist an uploaded file to the configured upload directory."""
|
||||
runtime_settings = settings or get_settings()
|
||||
_validate_upload(filename=filename, file_bytes=file_bytes)
|
||||
_validate_upload(filename=filename, file_bytes=file_bytes, supported_extensions=SUPPORTED_UPLOAD_EXTENSIONS)
|
||||
return _store_file_bytes(
|
||||
filename=filename,
|
||||
file_bytes=file_bytes,
|
||||
settings=runtime_settings,
|
||||
relative_directory=relative_directory,
|
||||
filename_stem=filename_stem,
|
||||
)
|
||||
|
||||
upload_dir = runtime_settings.upload_dir
|
||||
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
stored_name = _build_stored_filename(filename)
|
||||
stored_path = upload_dir / stored_name
|
||||
def store_person_portrait(
|
||||
*,
|
||||
person_id: UUID,
|
||||
filename: str,
|
||||
file_bytes: bytes,
|
||||
settings: Settings | None = None,
|
||||
) -> Path:
|
||||
"""Persist a portrait upload under persons/<person_id>."""
|
||||
runtime_settings = settings or get_settings()
|
||||
_validate_upload(filename=filename, file_bytes=file_bytes, supported_extensions=SUPPORTED_PORTRAIT_EXTENSIONS)
|
||||
return _store_file_bytes(
|
||||
filename=filename,
|
||||
file_bytes=file_bytes,
|
||||
settings=runtime_settings,
|
||||
relative_directory=Path("persons") / str(person_id),
|
||||
)
|
||||
|
||||
|
||||
def _store_file_bytes(
|
||||
*,
|
||||
filename: str,
|
||||
file_bytes: bytes,
|
||||
settings: Settings,
|
||||
relative_directory: Path | None = None,
|
||||
filename_stem: str | None = None,
|
||||
) -> Path:
|
||||
upload_dir = settings.upload_dir
|
||||
target_dir = upload_dir if relative_directory is None else upload_dir / relative_directory
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
stored_name = _build_stored_filename(filename=filename, filename_stem=filename_stem)
|
||||
stored_path = target_dir / stored_name
|
||||
|
||||
try:
|
||||
stored_path.write_bytes(file_bytes)
|
||||
@@ -126,7 +373,7 @@ def store_file(*, filename: str, file_bytes: bytes, settings: Settings | None =
|
||||
return stored_path
|
||||
|
||||
|
||||
def _validate_upload(*, filename: str, file_bytes: bytes) -> None:
|
||||
def _validate_upload(*, filename: str, file_bytes: bytes, supported_extensions: set[str]) -> None:
|
||||
if not file_bytes:
|
||||
raise UploadError(
|
||||
"Upload payload is empty",
|
||||
@@ -143,14 +390,16 @@ def _validate_upload(*, filename: str, file_bytes: bytes) -> None:
|
||||
)
|
||||
|
||||
suffix = Path(safe_name).suffix.lower()
|
||||
if suffix not in SUPPORTED_UPLOAD_EXTENSIONS:
|
||||
if suffix not in supported_extensions:
|
||||
raise UploadError(
|
||||
f"Unsupported upload extension: {suffix}",
|
||||
category=ErrorCategory.USER_INPUT,
|
||||
suggestion="Upload JPG, JPEG, PNG, TIFF, or PDF files only.",
|
||||
suggestion="Upload a supported image or document file and retry.",
|
||||
)
|
||||
|
||||
|
||||
def _build_stored_filename(filename: str) -> str:
|
||||
def _build_stored_filename(*, filename: str, filename_stem: str | None = None) -> str:
|
||||
safe_name = Path(filename).name
|
||||
return f"{uuid4()}_{safe_name}"
|
||||
suffix = Path(safe_name).suffix.lower()
|
||||
stem = filename_stem or str(uuid4())
|
||||
return f"{stem}{suffix}"
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import hashlib
|
||||
import logging
|
||||
import mimetypes
|
||||
from collections.abc import Sequence
|
||||
@@ -18,11 +20,12 @@ from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from transcription.config import Settings
|
||||
from transcription.config import get_settings
|
||||
from transcription.db.models import Job
|
||||
from transcription.db.models import JobSource
|
||||
from transcription.db.models import JobSourceStatus
|
||||
from transcription.db.models import Source
|
||||
from transcription.errors import AppError
|
||||
from transcription.errors import ErrorCategory
|
||||
from transcription.models import Job
|
||||
from transcription.models import Revision
|
||||
from transcription.models import Source
|
||||
from transcription.providers import ProviderAuthError
|
||||
from transcription.providers import ProviderError
|
||||
from transcription.providers import ProviderResponseError
|
||||
@@ -38,6 +41,18 @@ DEFAULT_PROMPT_FILE = "transcribe_document.md"
|
||||
SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".tif", ".tiff", ".pdf"}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PromptExecution:
|
||||
"""Resolved prompt inputs captured for one page execution."""
|
||||
|
||||
prompt_name: str
|
||||
prompt_hash: str
|
||||
system_prompt: str | None
|
||||
user_prompt: str
|
||||
temperature: float | None
|
||||
top_p: float | None
|
||||
|
||||
|
||||
class PromptLoadError(AppError):
|
||||
"""Raised when prompt artifacts cannot be loaded safely."""
|
||||
|
||||
@@ -50,8 +65,12 @@ class TranscriptionNotFoundError(TranscriptionError):
|
||||
"""Raised when a transcription-related resource is not found."""
|
||||
|
||||
|
||||
class SourceDeleteBlockedError(TranscriptionError):
|
||||
"""Raised when source deletion is blocked by dependency policy."""
|
||||
|
||||
|
||||
class TranscriptionService(ServiceBase):
|
||||
"""Service class for job transcription output and optional source revisions."""
|
||||
"""Service class for job transcription output and page-level source revisions."""
|
||||
|
||||
provider: TranscriptionProvider
|
||||
|
||||
@@ -59,89 +78,288 @@ class TranscriptionService(ServiceBase):
|
||||
super().__init__(session_factory=session_factory)
|
||||
self.provider = get_transcription_provider(settings=self.settings)
|
||||
|
||||
async def create_revision(self, revision: Revision, *, session: AsyncSession | None = None) -> Revision:
|
||||
"""Create a new revision in the database."""
|
||||
async def create_source(self, source: Source, *, session: AsyncSession | None = None) -> Source:
|
||||
"""Create a new source page record in the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
_session.add(revision)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(revision,))
|
||||
return revision
|
||||
_session.add(source)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(source,))
|
||||
return source
|
||||
|
||||
async def read_revision(self, revision_id: UUID, *, session: AsyncSession | None = None) -> Revision:
|
||||
"""Read an existing revision from the database."""
|
||||
async def read_source(self, source_id: UUID, *, session: AsyncSession | None = None) -> Source:
|
||||
"""Read an existing source page record."""
|
||||
async with self._session_scope(session) as _session:
|
||||
revision = await _session.get(
|
||||
Revision,
|
||||
revision_id,
|
||||
options=(selectinload(Revision.source),), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
if revision is None:
|
||||
source = await _session.get(Source, source_id)
|
||||
if source is None:
|
||||
raise TranscriptionNotFoundError(
|
||||
f"Revision with id {revision_id} not found",
|
||||
f"Source with id {source_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the revision id and retry.",
|
||||
suggestion="Verify the source id and retry.",
|
||||
)
|
||||
return revision
|
||||
return source
|
||||
|
||||
async def update_revision(self, revision: Revision, *, session: AsyncSession | None = None) -> Revision:
|
||||
"""Update an existing revision in the database."""
|
||||
async def read_source_detail(self, source_id: UUID, *, session: AsyncSession | None = None) -> Source:
|
||||
"""Read a source page record with job-source context for UI detail rendering."""
|
||||
async with self._session_scope(session) as _session:
|
||||
merged = await _session.merge(revision)
|
||||
query = (
|
||||
select(Source)
|
||||
.options(
|
||||
selectinload(Source.job_sources).selectinload(JobSource.job), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
.where(Source.id == source_id)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
source = (await _session.exec(query)).first()
|
||||
|
||||
if source is None:
|
||||
raise TranscriptionNotFoundError(
|
||||
f"Source with id {source_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the source id and retry.",
|
||||
)
|
||||
return source
|
||||
|
||||
async def update_source(self, source: Source, *, session: AsyncSession | None = None) -> Source:
|
||||
"""Update an existing source page record."""
|
||||
async with self._session_scope(session) as _session:
|
||||
merged = await _session.merge(source)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(merged,))
|
||||
return merged
|
||||
|
||||
async def delete_revision(self, revision: Revision, *, session: AsyncSession | None = None) -> None:
|
||||
"""Delete a revision from the database."""
|
||||
async def delete_source(self, source: Source, *, session: AsyncSession | None = None) -> None:
|
||||
"""Delete a source page record."""
|
||||
source_file_path = source.file_path
|
||||
async with self._session_scope(session) as _session:
|
||||
await _session.delete(revision)
|
||||
await _session.delete(source)
|
||||
await self._finalize(session=_session, caller_session=session)
|
||||
|
||||
# Temporary compatibility methods for callers still using transcript naming.
|
||||
self._delete_source_file(source_file_path=source_file_path)
|
||||
|
||||
async def read_transcript(self, transcript_id: UUID, *, session: AsyncSession | None = None) -> Revision:
|
||||
"""Backward-compatible alias for read_revision."""
|
||||
return await self.read_revision(transcript_id, session=session)
|
||||
async def delete_unlinked_source(self, *, source_id: UUID, session: AsyncSession | None = None) -> None:
|
||||
"""Delete a source only when no JobSource links exist."""
|
||||
async with self._session_scope(session) as _session:
|
||||
source = await _session.get(
|
||||
Source,
|
||||
source_id,
|
||||
options=(
|
||||
selectinload(Source.job_sources), # pyright: ignore[reportArgumentType]
|
||||
),
|
||||
)
|
||||
if source is None:
|
||||
raise TranscriptionNotFoundError(
|
||||
f"Source with id {source_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the source id and retry.",
|
||||
)
|
||||
|
||||
async def delete_transcript(self, transcript: Revision, *, session: AsyncSession | None = None) -> None:
|
||||
"""Backward-compatible alias for delete_revision."""
|
||||
await self.delete_revision(transcript, session=session)
|
||||
if source.job_sources:
|
||||
raise SourceDeleteBlockedError(
|
||||
"Source delete blocked because it is linked to one or more jobs",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Remove JobSource links first, then retry deletion.",
|
||||
)
|
||||
|
||||
async def transcribe_document(
|
||||
source_file_path = source.file_path
|
||||
await _session.delete(source)
|
||||
await self._finalize(session=_session, caller_session=session)
|
||||
|
||||
self._delete_source_file(source_file_path=source_file_path)
|
||||
|
||||
async def list_sources(
|
||||
self,
|
||||
image_path: str | Path,
|
||||
job_id: UUID,
|
||||
*,
|
||||
prompt_name: str = DEFAULT_PROMPT_FILE,
|
||||
document_id: UUID | None = None,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Sequence[Source]:
|
||||
"""List source pages, optionally filtered by document."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = select(Source)
|
||||
if document_id is not None:
|
||||
query = query.where(Source.document_id == document_id)
|
||||
result = await _session.exec(query)
|
||||
return result.all()
|
||||
|
||||
async def query_sources(
|
||||
self,
|
||||
*,
|
||||
document_id: UUID | None = None,
|
||||
page_number: int | None = None,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Sequence[Source]:
|
||||
"""Query source pages using the provided filters."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = select(Source)
|
||||
if document_id is not None:
|
||||
query = query.where(Source.document_id == document_id)
|
||||
if page_number is not None:
|
||||
query = query.where(Source.page_number == page_number)
|
||||
result = await _session.exec(query)
|
||||
return result.all()
|
||||
|
||||
async def list_sources_detail(
|
||||
self,
|
||||
*,
|
||||
document_id: UUID | None = None,
|
||||
job_id: UUID | None = None,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Sequence[Source]:
|
||||
"""List source pages with document/job link context for UI rendering."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = select(Source).options(
|
||||
selectinload(Source.document),
|
||||
selectinload(Source.job_sources),
|
||||
)
|
||||
if document_id is not None:
|
||||
query = query.where(Source.document_id == document_id)
|
||||
|
||||
result = await _session.exec(query)
|
||||
sources = list(result.all())
|
||||
|
||||
if job_id is not None:
|
||||
sources = [
|
||||
source for source in sources if any(job_source.job_id == job_id for job_source in source.job_sources)
|
||||
]
|
||||
|
||||
return sources
|
||||
|
||||
async def create_job_source(
|
||||
self,
|
||||
job_source: JobSource,
|
||||
*,
|
||||
session: AsyncSession | None = None,
|
||||
) -> JobSource:
|
||||
"""Create a new job_source execution record in the database."""
|
||||
async with self._session_scope(session) as _session:
|
||||
_session.add(job_source)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(job_source,))
|
||||
return job_source
|
||||
|
||||
async def read_job_source(self, job_source_id: UUID, *, session: AsyncSession | None = None) -> JobSource:
|
||||
"""Read an existing job_source record."""
|
||||
async with self._session_scope(session) as _session:
|
||||
job_source = await _session.get(
|
||||
JobSource,
|
||||
job_source_id,
|
||||
options=(selectinload(JobSource.source),), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
if job_source is None:
|
||||
raise TranscriptionNotFoundError(
|
||||
f"JobSource with id {job_source_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the job source id and retry.",
|
||||
)
|
||||
return job_source
|
||||
|
||||
async def update_job_source(self, job_source: JobSource, *, session: AsyncSession | None = None) -> JobSource:
|
||||
"""Update an existing job_source record."""
|
||||
async with self._session_scope(session) as _session:
|
||||
merged = await _session.merge(job_source)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(merged,))
|
||||
return merged
|
||||
|
||||
async def delete_job_source(self, job_source: JobSource, *, session: AsyncSession | None = None) -> None:
|
||||
"""Delete a job_source record."""
|
||||
async with self._session_scope(session) as _session:
|
||||
await _session.delete(job_source)
|
||||
await self._finalize(session=_session, caller_session=session)
|
||||
|
||||
async def delete_source_from_job_context(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
source_id: UUID,
|
||||
session: AsyncSession | None = None,
|
||||
) -> None:
|
||||
"""Transcribe a local image using the configured prompt and provider."""
|
||||
result = await transcribe_document_image(
|
||||
image_path=image_path,
|
||||
prompt_name=prompt_name,
|
||||
settings=self.settings,
|
||||
provider=self.provider,
|
||||
)
|
||||
await self.update_job_transcription(
|
||||
job_id=job_id,
|
||||
text=result.text,
|
||||
error_detail=None,
|
||||
provider=result.provider,
|
||||
model=result.model,
|
||||
prompt_name=result.prompt_name,
|
||||
session=session,
|
||||
)
|
||||
"""Delete a source from an active job context with dependency guardrails.
|
||||
|
||||
async def update_job_transcription(
|
||||
Policy:
|
||||
- Allowed when exactly one JobSource link exists and it points at ``job_id``.
|
||||
- Blocked when additional JobSource links exist (history/shared dependencies).
|
||||
"""
|
||||
async with self._session_scope(session) as _session:
|
||||
source = await _session.get(
|
||||
Source,
|
||||
source_id,
|
||||
options=(
|
||||
selectinload(Source.job_sources), # pyright: ignore[reportArgumentType]
|
||||
),
|
||||
)
|
||||
if source is None:
|
||||
raise TranscriptionNotFoundError(
|
||||
f"Source with id {source_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the source id and retry.",
|
||||
)
|
||||
|
||||
linked_job_sources = list(source.job_sources)
|
||||
matching_links = [job_source for job_source in linked_job_sources if job_source.job_id == job_id]
|
||||
if not matching_links:
|
||||
raise TranscriptionNotFoundError(
|
||||
f"Source {source_id} is not linked to job {job_id}",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Open the source from its linked job context and retry.",
|
||||
)
|
||||
|
||||
if len(linked_job_sources) > len(matching_links):
|
||||
raise SourceDeleteBlockedError(
|
||||
"Source delete blocked by related job history",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Remove additional JobSource links first, then retry deletion.",
|
||||
)
|
||||
|
||||
for job_source in matching_links:
|
||||
await _session.delete(job_source)
|
||||
|
||||
source_file_path = source.file_path
|
||||
await _session.delete(source)
|
||||
await self._finalize(session=_session, caller_session=session)
|
||||
|
||||
self._delete_source_file(source_file_path=source_file_path)
|
||||
|
||||
def _delete_source_file(self, *, source_file_path: str) -> None:
|
||||
"""Best-effort cleanup for source media files."""
|
||||
candidate_path = Path(source_file_path)
|
||||
resolved_path = candidate_path if candidate_path.is_absolute() else self.settings.upload_dir / candidate_path
|
||||
|
||||
if not resolved_path.exists():
|
||||
return
|
||||
|
||||
try:
|
||||
resolved_path.unlink()
|
||||
logger.info("Deleted source file: %s", resolved_path)
|
||||
except OSError:
|
||||
logger.warning("Failed to delete source file: %s", resolved_path)
|
||||
|
||||
async def list_job_sources(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID | None = None,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Sequence[JobSource]:
|
||||
"""List job-source records, optionally filtered by job."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = select(JobSource).options(
|
||||
selectinload(JobSource.job), # pyright: ignore[reportArgumentType]
|
||||
selectinload(JobSource.source), # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
if job_id is not None:
|
||||
query = query.where(JobSource.job_id == job_id)
|
||||
result = await _session.exec(query)
|
||||
return result.all()
|
||||
|
||||
async def update_job_source_transcription(
|
||||
self,
|
||||
*,
|
||||
job_id: UUID,
|
||||
source_id: UUID,
|
||||
text: str | None,
|
||||
error_detail: str | None = None,
|
||||
ai_metadata: dict[str, object] | None = None,
|
||||
raw_api_response: dict[str, object] | None = None,
|
||||
provider: str | None = None,
|
||||
model: str | None = None,
|
||||
prompt_name: str = DEFAULT_PROMPT_FILE,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Job:
|
||||
"""Persist original transcription output fields on a job."""
|
||||
) -> JobSource:
|
||||
"""Persist transcription fields for one source within a specific job."""
|
||||
async with self._session_scope(session) as _session:
|
||||
job = await _session.get(Job, job_id)
|
||||
if job is None:
|
||||
@@ -151,15 +369,53 @@ class TranscriptionService(ServiceBase):
|
||||
suggestion="Verify the job id and retry.",
|
||||
)
|
||||
|
||||
job.text = text
|
||||
job.error_detail = error_detail
|
||||
source = await _session.get(Source, source_id)
|
||||
if source is None:
|
||||
raise TranscriptionNotFoundError(
|
||||
f"Source with id {source_id} not found",
|
||||
category=ErrorCategory.NOT_FOUND,
|
||||
suggestion="Verify the source id and retry.",
|
||||
)
|
||||
|
||||
if source.document_id != job.document_id:
|
||||
raise TranscriptionError(
|
||||
f"Source {source_id} does not belong to job {job_id}",
|
||||
category=ErrorCategory.VALIDATION,
|
||||
suggestion="Link the source to the same document as the job and retry.",
|
||||
)
|
||||
|
||||
job.provider = provider or job.provider or self.settings.provider.value
|
||||
job.model = model or job.model or _resolve_transcript_model(provider=self.provider, settings=self.settings)
|
||||
job.prompt_name = prompt_name or job.prompt_name or DEFAULT_PROMPT_FILE
|
||||
job.date_updated = datetime.now(UTC)
|
||||
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(job,))
|
||||
return job
|
||||
if text is not None:
|
||||
source.raw_transcription = text
|
||||
|
||||
existing_job_source = await _session.exec(
|
||||
select(JobSource).where(JobSource.job_id == job_id).where(JobSource.source_id == source_id)
|
||||
)
|
||||
job_source = existing_job_source.first()
|
||||
if job_source is None:
|
||||
job_source = JobSource(
|
||||
job_id=job_id,
|
||||
source_id=source_id,
|
||||
status=JobSourceStatus.TRANSCRIBED if text is not None else JobSourceStatus.FAILED,
|
||||
raw_transcription=text,
|
||||
ai_metadata=ai_metadata,
|
||||
raw_api_response=raw_api_response,
|
||||
error_detail=error_detail,
|
||||
)
|
||||
_session.add(job_source)
|
||||
else:
|
||||
job_source.raw_transcription = text
|
||||
job_source.ai_metadata = ai_metadata
|
||||
job_source.raw_api_response = raw_api_response
|
||||
job_source.error_detail = error_detail
|
||||
job_source.status = JobSourceStatus.TRANSCRIBED if text is not None else JobSourceStatus.FAILED
|
||||
job_source.executed_at = datetime.now(UTC)
|
||||
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(job, source, job_source))
|
||||
return job_source
|
||||
|
||||
async def upsert_revision_for_source(
|
||||
self,
|
||||
@@ -167,8 +423,8 @@ class TranscriptionService(ServiceBase):
|
||||
source_id: UUID,
|
||||
text: str,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Revision:
|
||||
"""Create or replace the single optional revision for a source."""
|
||||
) -> Source:
|
||||
"""Persist a human revision on a source page."""
|
||||
async with self._session_scope(session) as _session:
|
||||
source = await _session.get(Source, source_id)
|
||||
if source is None:
|
||||
@@ -178,45 +434,35 @@ class TranscriptionService(ServiceBase):
|
||||
suggestion="Verify the source id and retry.",
|
||||
)
|
||||
|
||||
query = select(Revision).where(Revision.source_id == source_id)
|
||||
existing = (await _session.exec(query)).one_or_none()
|
||||
|
||||
if existing is None:
|
||||
revision = Revision(source_id=source_id, text=text)
|
||||
_session.add(revision)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(revision,))
|
||||
return revision
|
||||
|
||||
existing.text = text
|
||||
merged = await _session.merge(existing)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(merged,))
|
||||
return merged
|
||||
source.revised_text = text
|
||||
source.date_revised = datetime.now(UTC)
|
||||
await self._finalize(session=_session, caller_session=session, refresh=(source,))
|
||||
return source
|
||||
|
||||
async def read_revision_by_source(
|
||||
self,
|
||||
source_id: UUID,
|
||||
*,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Revision | None:
|
||||
"""Read the single optional revision for a source."""
|
||||
) -> Source | None:
|
||||
"""Read the source record for a given page, including any revision text."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = select(Revision).where(Revision.source_id == source_id)
|
||||
result = await _session.exec(query)
|
||||
return result.one_or_none()
|
||||
return await _session.get(Source, source_id)
|
||||
|
||||
async def list_revisions_by_job(
|
||||
self,
|
||||
job_id: UUID,
|
||||
*,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Sequence[Revision]:
|
||||
"""List revisions connected to all sources for a job."""
|
||||
) -> Sequence[Source]:
|
||||
"""List source pages for a job that carry revision text."""
|
||||
async with self._session_scope(session) as _session:
|
||||
query = (
|
||||
select(Revision)
|
||||
.join(Source, Source.id == Revision.source_id)
|
||||
.where(Source.job_id == job_id)
|
||||
.order_by(Revision.date_created) # pyright: ignore[reportArgumentType]
|
||||
select(Source)
|
||||
.join(JobSource, JobSource.source_id == Source.id)
|
||||
.where(JobSource.job_id == job_id)
|
||||
.where(Source.revised_text.is_not(None))
|
||||
.order_by(Source.date_revised) # pyright: ignore[reportArgumentType]
|
||||
)
|
||||
result = await _session.exec(query)
|
||||
return result.all()
|
||||
@@ -236,13 +482,27 @@ def _resolve_transcript_model(*, provider: TranscriptionProvider, settings: Sett
|
||||
async def transcribe_document_image(
|
||||
image_path: str | Path,
|
||||
*,
|
||||
prompt_name: str = DEFAULT_PROMPT_FILE,
|
||||
prompt_name: str | None = None,
|
||||
prompt_text: str | None = None,
|
||||
temperature: float | None = None,
|
||||
top_p: float | None = None,
|
||||
settings: Settings | None = None,
|
||||
provider: TranscriptionProvider | None = None,
|
||||
) -> TranscriptionResult:
|
||||
"""Transcribe a local image using the configured prompt and provider."""
|
||||
runtime_settings = settings or get_settings()
|
||||
prompt_text = load_prompt_text(prompt_name=prompt_name, settings=runtime_settings)
|
||||
if prompt_text is None:
|
||||
prompt_execution = build_prompt_execution(prompt_name=prompt_name, settings=runtime_settings)
|
||||
else:
|
||||
effective_prompt_name = (prompt_name or runtime_settings.default_prompt_name or DEFAULT_PROMPT_FILE).strip()
|
||||
prompt_execution = PromptExecution(
|
||||
prompt_name=effective_prompt_name,
|
||||
prompt_hash=hashlib.sha256(prompt_text.encode("utf-8")).hexdigest(),
|
||||
system_prompt=None,
|
||||
user_prompt=prompt_text,
|
||||
temperature=temperature if temperature is not None else runtime_settings.transcription_temperature,
|
||||
top_p=top_p if top_p is not None else runtime_settings.transcription_top_p,
|
||||
)
|
||||
image_bytes, mime_type = load_image_payload(image_path)
|
||||
|
||||
adapter = provider or get_transcription_provider(settings=runtime_settings)
|
||||
@@ -250,12 +510,45 @@ async def transcribe_document_image(
|
||||
|
||||
with handle_transcription_errors():
|
||||
result = await adapter.transcribe(
|
||||
prompt_text=prompt_text,
|
||||
prompt_text=prompt_execution.user_prompt,
|
||||
image_bytes=image_bytes,
|
||||
mime_type=mime_type,
|
||||
temperature=prompt_execution.temperature,
|
||||
top_p=prompt_execution.top_p,
|
||||
)
|
||||
logger.info("Transcription completed for image=%s provider=%s", image_path, result.provider)
|
||||
return result
|
||||
return TranscriptionResult(
|
||||
text=result.text,
|
||||
provider=result.provider,
|
||||
prompt_name=prompt_execution.prompt_name,
|
||||
prompt_hash=prompt_execution.prompt_hash,
|
||||
system_prompt=prompt_execution.system_prompt,
|
||||
user_prompt=result.user_prompt or prompt_execution.user_prompt,
|
||||
temperature=result.temperature if result.temperature is not None else prompt_execution.temperature,
|
||||
top_p=result.top_p if result.top_p is not None else prompt_execution.top_p,
|
||||
model=result.model,
|
||||
finish_reason=result.finish_reason,
|
||||
usage_input_tokens=result.usage_input_tokens,
|
||||
usage_output_tokens=result.usage_output_tokens,
|
||||
usage_total_tokens=result.usage_total_tokens,
|
||||
ai_metadata=result.ai_metadata,
|
||||
raw_api_response=result.raw_api_response,
|
||||
)
|
||||
|
||||
|
||||
def build_prompt_execution(*, prompt_name: str | None = None, settings: Settings | None = None) -> PromptExecution:
|
||||
"""Resolve the exact prompt payload and provenance for one execution."""
|
||||
runtime_settings = settings or get_settings()
|
||||
effective_prompt_name = (prompt_name or runtime_settings.default_prompt_name or DEFAULT_PROMPT_FILE).strip()
|
||||
user_prompt = load_prompt_text(prompt_name=effective_prompt_name, settings=runtime_settings)
|
||||
return PromptExecution(
|
||||
prompt_name=effective_prompt_name,
|
||||
prompt_hash=hashlib.sha256(user_prompt.encode("utf-8")).hexdigest(),
|
||||
system_prompt=None,
|
||||
user_prompt=user_prompt,
|
||||
temperature=runtime_settings.transcription_temperature,
|
||||
top_p=runtime_settings.transcription_top_p,
|
||||
)
|
||||
|
||||
|
||||
def load_prompt_text(*, prompt_name: str = DEFAULT_PROMPT_FILE, settings: Settings | None = None) -> str:
|
||||
|
||||
@@ -5,16 +5,18 @@ from sqlmodel.ext.asyncio.session import AsyncSession
|
||||
|
||||
from ..config import Settings
|
||||
from ..config import get_settings
|
||||
from ..db.models import Job
|
||||
from ..db.models import JobSourceStatus
|
||||
from ..db.models import JobStatus
|
||||
from ..db.models import Source
|
||||
from ..errors import AppError
|
||||
from ..errors import ErrorCategory
|
||||
from ..errors import classify_unexpected_error
|
||||
from ..errors import format_error_detail
|
||||
from ..models import Job
|
||||
from ..models import JobStatus
|
||||
from ..models import Source
|
||||
from ..providers import TranscriptionResult
|
||||
from . import ServiceBundle
|
||||
from .transcription import DEFAULT_PROMPT_FILE
|
||||
from .transcription import build_prompt_execution
|
||||
from .transcription import PromptExecution
|
||||
from .transcription import transcribe_document_image
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -28,9 +30,13 @@ async def advance_job(
|
||||
) -> Job | None:
|
||||
"""Advance a single job by lifecycle status."""
|
||||
settings = settings or get_settings()
|
||||
match job.status:
|
||||
current_status = _coerce_job_status(job.status)
|
||||
match current_status:
|
||||
case JobStatus.QUEUED:
|
||||
return await process_queued_job(job=job, services=services, settings=settings, session=session)
|
||||
case JobStatus.PROCESSING:
|
||||
# Recover mid-flight jobs by continuing the queued processing path.
|
||||
return await process_queued_job(job=job, services=services, settings=settings, session=session)
|
||||
case JobStatus.FAILED:
|
||||
if job.retry_count < settings.worker_max_retries:
|
||||
return await services.jobs.update_job_state(
|
||||
@@ -55,92 +61,140 @@ async def process_queued_job(
|
||||
) -> Job | None:
|
||||
"""Process one complete transcription attempt for a queued job."""
|
||||
runtime_settings = settings or get_settings()
|
||||
if job.status != JobStatus.QUEUED:
|
||||
current_status = _coerce_job_status(job.status)
|
||||
if current_status not in {JobStatus.QUEUED, JobStatus.PROCESSING}:
|
||||
logger.warning(f"Job {job.id} is not queued. Current status: {job.status}")
|
||||
return
|
||||
|
||||
# Transaction A: claim job for processing.
|
||||
if session is None:
|
||||
job = await services.jobs.mark_job_status(job.id, JobStatus.PROCESSING)
|
||||
else:
|
||||
# If we're sharing the session, need to make sure setting the Job to PROCESSING is committed before we start
|
||||
# the transcription, otherwise other workers may see the job as still QUEUED and try to process it.
|
||||
job = await services.jobs.mark_job_status(job.id, JobStatus.PROCESSING, session=session)
|
||||
await session.commit()
|
||||
if current_status == JobStatus.QUEUED:
|
||||
if session is None:
|
||||
job = await services.jobs.mark_job_status(job.id, JobStatus.PROCESSING)
|
||||
else:
|
||||
# If we're sharing the session, need to make sure setting the Job to PROCESSING is committed before we start
|
||||
# the transcription, otherwise other workers may see the job as still QUEUED and try to process it.
|
||||
job = await services.jobs.mark_job_status(job.id, JobStatus.PROCESSING, session=session)
|
||||
await session.commit()
|
||||
|
||||
source_job = await services.jobs.read_job(job_id=job.id, session=session)
|
||||
source = _resolve_primary_source(source_job)
|
||||
assert source is not None, f"Job {job.id} has no associated source record."
|
||||
started_at = asyncio.get_running_loop().time()
|
||||
sources = _resolve_job_sources(source_job)
|
||||
if not sources and not source_job.job_sources:
|
||||
candidate_sources = await services.transcriptions.list_sources(document_id=job.document_id, session=session)
|
||||
sources = list(sorted(candidate_sources, key=lambda item: (item.page_number, item.upload_name.casefold())))
|
||||
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
transcribe_document_image(source.file_path),
|
||||
timeout=runtime_settings.worker_provider_timeout_seconds,
|
||||
)
|
||||
elapsed_seconds = asyncio.get_running_loop().time() - started_at
|
||||
logger.info(
|
||||
"Provider response diagnostics operation=worker.provider_response "
|
||||
"job_id=%s document_id=%s source_id=%s provider=%s model=%s "
|
||||
"finish_reason=%s usage_input_tokens=%s usage_output_tokens=%s usage_total_tokens=%s "
|
||||
"latency_seconds=%.3f text_chars=%s text_lines=%s",
|
||||
job.id,
|
||||
job.document_id,
|
||||
source.id,
|
||||
result.provider,
|
||||
result.model,
|
||||
result.finish_reason or "unknown",
|
||||
result.usage_input_tokens,
|
||||
result.usage_output_tokens,
|
||||
result.usage_total_tokens,
|
||||
elapsed_seconds,
|
||||
len(result.text),
|
||||
_line_count(result.text),
|
||||
)
|
||||
if not sources:
|
||||
return await services.jobs.mark_job_status(job.id, JobStatus.TRANSCRIBED, session=session)
|
||||
|
||||
_validate_transcription_quality(result=result, settings=runtime_settings)
|
||||
successful_pages: list[tuple[Source, TranscriptionResult]] = []
|
||||
failed_pages: list[tuple[Source, AppError]] = []
|
||||
externally_stopped = False
|
||||
|
||||
job = await _finalize_transcribed(job=job, services=services, result=result, session=session)
|
||||
logger.info(
|
||||
"Job transcribed operation=worker.process_job job_id=%s document_id=%s source_id=%s provider=%s",
|
||||
job.id,
|
||||
job.document_id,
|
||||
source.id,
|
||||
result.provider,
|
||||
)
|
||||
except TimeoutError:
|
||||
error = AppError(
|
||||
f"Provider call timed out after {runtime_settings.worker_provider_timeout_seconds:.1f}s",
|
||||
category=ErrorCategory.EXTERNAL_PROVIDER,
|
||||
suggestion="Retry the job. If this repeats, verify provider latency and request payload size.",
|
||||
retriable=True,
|
||||
)
|
||||
job = await _finalize_failed(job=job, services=services, error=error, session=session)
|
||||
logger.error(
|
||||
"Job failed operation=worker.process_job job_id=%s document_id=%s source_id=%s error_id=%s category=%s",
|
||||
job.id,
|
||||
job.document_id,
|
||||
source.id,
|
||||
error.error_id,
|
||||
error.category.value,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
match exc:
|
||||
case AppError() as error:
|
||||
pass
|
||||
case _:
|
||||
error = classify_unexpected_error(exc, operation="worker.process_job")
|
||||
prompt_execution = _resolve_job_prompt_execution(source_job=source_job, settings=runtime_settings)
|
||||
|
||||
job = await _finalize_failed(job=job, services=services, error=error, session=session)
|
||||
logger.error(
|
||||
"Job failed operation=worker.process_job job_id=%s document_id=%s source_id=%s error_id=%s category=%s",
|
||||
job.id,
|
||||
job.document_id,
|
||||
source.id,
|
||||
error.error_id,
|
||||
error.category.value,
|
||||
)
|
||||
return job
|
||||
for source in sources:
|
||||
if await _job_no_longer_processing(job_id=job.id, services=services, session=session):
|
||||
externally_stopped = True
|
||||
break
|
||||
|
||||
started_at = asyncio.get_running_loop().time()
|
||||
try:
|
||||
result = await asyncio.wait_for(
|
||||
transcribe_document_image(
|
||||
source.file_path,
|
||||
prompt_name=prompt_execution.prompt_name,
|
||||
prompt_text=prompt_execution.user_prompt,
|
||||
temperature=prompt_execution.temperature,
|
||||
top_p=prompt_execution.top_p,
|
||||
settings=runtime_settings,
|
||||
provider=services.transcriptions.provider,
|
||||
),
|
||||
timeout=runtime_settings.worker_provider_timeout_seconds,
|
||||
)
|
||||
elapsed_seconds = asyncio.get_running_loop().time() - started_at
|
||||
logger.info(
|
||||
"Provider response diagnostics operation=worker.provider_response "
|
||||
"job_id=%s document_id=%s source_id=%s provider=%s model=%s "
|
||||
"finish_reason=%s usage_input_tokens=%s usage_output_tokens=%s usage_total_tokens=%s "
|
||||
"latency_seconds=%.3f text_chars=%s text_lines=%s",
|
||||
job.id,
|
||||
job.document_id,
|
||||
source.id,
|
||||
result.provider,
|
||||
result.model,
|
||||
result.finish_reason or "unknown",
|
||||
result.usage_input_tokens,
|
||||
result.usage_output_tokens,
|
||||
result.usage_total_tokens,
|
||||
elapsed_seconds,
|
||||
len(result.text),
|
||||
_line_count(result.text),
|
||||
)
|
||||
|
||||
_validate_transcription_quality(result=result, settings=runtime_settings)
|
||||
successful_pages.append((source, result))
|
||||
except TimeoutError:
|
||||
error = AppError(
|
||||
f"Provider call timed out after {runtime_settings.worker_provider_timeout_seconds:.1f}s",
|
||||
category=ErrorCategory.EXTERNAL_PROVIDER,
|
||||
suggestion="Retry the job. If this repeats, verify provider latency and request payload size.",
|
||||
retriable=True,
|
||||
)
|
||||
failed_pages.append((source, error))
|
||||
logger.error(
|
||||
"Source failed operation=worker.process_job job_id=%s document_id=%s source_id=%s error_id=%s category=%s",
|
||||
job.id,
|
||||
job.document_id,
|
||||
source.id,
|
||||
error.error_id,
|
||||
error.category.value,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
match exc:
|
||||
case AppError() as error:
|
||||
pass
|
||||
case _:
|
||||
error = classify_unexpected_error(exc, operation="worker.process_job")
|
||||
|
||||
failed_pages.append((source, error))
|
||||
logger.error(
|
||||
"Source failed operation=worker.process_job job_id=%s document_id=%s source_id=%s error_id=%s category=%s",
|
||||
job.id,
|
||||
job.document_id,
|
||||
source.id,
|
||||
error.error_id,
|
||||
error.category.value,
|
||||
)
|
||||
|
||||
if await _job_no_longer_processing(job_id=job.id, services=services, session=session):
|
||||
externally_stopped = True
|
||||
break
|
||||
|
||||
terminal_status = JobStatus.TRANSCRIBED
|
||||
if externally_stopped:
|
||||
terminal_status = JobStatus.FAILED
|
||||
elif failed_pages and successful_pages:
|
||||
terminal_status = JobStatus.PARTIAL_SUCCESS
|
||||
elif failed_pages and not successful_pages:
|
||||
terminal_status = JobStatus.FAILED
|
||||
|
||||
updated_job = await _finalize_batch_outcome(
|
||||
job=job,
|
||||
services=services,
|
||||
successful_pages=successful_pages,
|
||||
failed_pages=failed_pages,
|
||||
status=terminal_status,
|
||||
session=session,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Job finished operation=worker.process_job job_id=%s document_id=%s status=%s success_pages=%s failed_pages=%s",
|
||||
updated_job.id,
|
||||
updated_job.document_id,
|
||||
updated_job.status.value,
|
||||
len(successful_pages),
|
||||
len(failed_pages),
|
||||
)
|
||||
return updated_job
|
||||
|
||||
|
||||
async def process_next_queued_job(
|
||||
@@ -151,6 +205,7 @@ async def process_next_queued_job(
|
||||
) -> bool:
|
||||
"""Process the next queued job if one exists."""
|
||||
job = await services.jobs.read_next_queued_job(session=session)
|
||||
|
||||
if job is None:
|
||||
return False
|
||||
|
||||
@@ -158,144 +213,109 @@ async def process_next_queued_job(
|
||||
return True
|
||||
|
||||
|
||||
async def _finalize_transcribed(
|
||||
def _resolve_job_sources(job: Job) -> list[Source]:
|
||||
"""Resolve non-transcribed linked sources for a job in deterministic page order."""
|
||||
if not job.job_sources:
|
||||
return []
|
||||
|
||||
sources = [
|
||||
job_source.source
|
||||
for job_source in job.job_sources
|
||||
if job_source.source is not None and job_source.status != JobSourceStatus.TRANSCRIBED
|
||||
]
|
||||
return list(sorted(sources, key=lambda item: (item.page_number, item.upload_name.casefold())))
|
||||
|
||||
|
||||
def _resolve_job_prompt_execution(*, source_job: Job, settings: Settings) -> PromptExecution:
|
||||
if source_job.user_prompt and source_job.prompt_name:
|
||||
return PromptExecution(
|
||||
prompt_name=source_job.prompt_name,
|
||||
prompt_hash=source_job.prompt_hash or "",
|
||||
system_prompt=source_job.system_prompt,
|
||||
user_prompt=source_job.user_prompt,
|
||||
temperature=source_job.temperature,
|
||||
top_p=source_job.top_p,
|
||||
)
|
||||
|
||||
return build_prompt_execution(settings=settings)
|
||||
|
||||
|
||||
async def _job_no_longer_processing(
|
||||
*,
|
||||
job_id,
|
||||
services: ServiceBundle,
|
||||
session: AsyncSession | None = None,
|
||||
) -> bool:
|
||||
"""Return True when job status changed externally from PROCESSING."""
|
||||
latest_job = await services.jobs.read_job(job_id=job_id, session=session)
|
||||
return latest_job.status != JobStatus.PROCESSING
|
||||
|
||||
|
||||
async def _finalize_batch_outcome(
|
||||
*,
|
||||
job: Job,
|
||||
services: ServiceBundle,
|
||||
result: TranscriptionResult,
|
||||
successful_pages: list[tuple[Source, TranscriptionResult]],
|
||||
failed_pages: list[tuple[Source, AppError]],
|
||||
status: JobStatus,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Job:
|
||||
"""Transaction B: job transcription output + TRANSCRIBED in one commit."""
|
||||
"""Transaction B: write per-source outcomes and terminal job status atomically."""
|
||||
if session is None:
|
||||
async with services.jobs._session_scope() as local_session:
|
||||
await services.transcriptions.update_job_transcription(
|
||||
job_id=job.id,
|
||||
text=result.text,
|
||||
error_detail=None,
|
||||
provider=result.provider,
|
||||
model=result.model,
|
||||
prompt_name=result.prompt_name,
|
||||
session=local_session,
|
||||
)
|
||||
updated_job = await services.jobs.mark_job_status(
|
||||
job.id,
|
||||
JobStatus.TRANSCRIBED,
|
||||
session=local_session,
|
||||
)
|
||||
for source, result in successful_pages:
|
||||
await services.transcriptions.update_job_source_transcription(
|
||||
job_id=job.id,
|
||||
source_id=source.id,
|
||||
text=result.text,
|
||||
error_detail=None,
|
||||
ai_metadata=result.ai_metadata,
|
||||
raw_api_response=result.raw_api_response,
|
||||
provider=result.provider,
|
||||
model=result.model,
|
||||
session=local_session,
|
||||
)
|
||||
|
||||
for source, error in failed_pages:
|
||||
await services.transcriptions.update_job_source_transcription(
|
||||
job_id=job.id,
|
||||
source_id=source.id,
|
||||
text=None,
|
||||
error_detail=format_error_detail(error),
|
||||
session=local_session,
|
||||
)
|
||||
|
||||
updated_job = await services.jobs.mark_job_status(job.id, status, session=local_session)
|
||||
await local_session.commit()
|
||||
return updated_job
|
||||
|
||||
await services.transcriptions.update_job_transcription(
|
||||
job_id=job.id,
|
||||
text=result.text,
|
||||
error_detail=None,
|
||||
provider=result.provider,
|
||||
model=result.model,
|
||||
prompt_name=result.prompt_name,
|
||||
session=session,
|
||||
)
|
||||
updated_job = await services.jobs.mark_job_status(
|
||||
job.id,
|
||||
JobStatus.TRANSCRIBED,
|
||||
session=session,
|
||||
)
|
||||
await session.commit()
|
||||
return updated_job
|
||||
|
||||
|
||||
async def _finalize_retry(
|
||||
*,
|
||||
job: Job,
|
||||
services: ServiceBundle,
|
||||
error: AppError,
|
||||
settings: Settings,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Job:
|
||||
"""Transaction C: job error detail + QUEUED + retry increment in one commit."""
|
||||
if session is None:
|
||||
async with services.jobs._session_scope() as local_session:
|
||||
await services.transcriptions.update_job_transcription(
|
||||
job_id=job.id,
|
||||
text=None,
|
||||
error_detail=format_error_detail(error),
|
||||
prompt_name=DEFAULT_PROMPT_FILE,
|
||||
session=local_session,
|
||||
)
|
||||
updated_job = await services.jobs.update_job_state(
|
||||
job_id=job.id,
|
||||
status=JobStatus.QUEUED,
|
||||
retry_count_increment=1,
|
||||
session=local_session,
|
||||
)
|
||||
await local_session.commit()
|
||||
else:
|
||||
await services.transcriptions.update_job_transcription(
|
||||
for source, result in successful_pages:
|
||||
await services.transcriptions.update_job_source_transcription(
|
||||
job_id=job.id,
|
||||
source_id=source.id,
|
||||
text=result.text,
|
||||
error_detail=None,
|
||||
ai_metadata=result.ai_metadata,
|
||||
raw_api_response=result.raw_api_response,
|
||||
provider=result.provider,
|
||||
model=result.model,
|
||||
session=session,
|
||||
)
|
||||
|
||||
for source, error in failed_pages:
|
||||
await services.transcriptions.update_job_source_transcription(
|
||||
job_id=job.id,
|
||||
source_id=source.id,
|
||||
text=None,
|
||||
error_detail=format_error_detail(error),
|
||||
prompt_name=DEFAULT_PROMPT_FILE,
|
||||
session=session,
|
||||
)
|
||||
updated_job = await services.jobs.update_job_state(
|
||||
job_id=job.id,
|
||||
status=JobStatus.QUEUED,
|
||||
retry_count_increment=1,
|
||||
session=session,
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
if settings.worker_retry_backoff_seconds > 0:
|
||||
await asyncio.sleep(settings.worker_retry_backoff_seconds)
|
||||
return updated_job
|
||||
|
||||
|
||||
async def _finalize_failed(
|
||||
*,
|
||||
job: Job,
|
||||
services: ServiceBundle,
|
||||
error: AppError,
|
||||
session: AsyncSession | None = None,
|
||||
) -> Job:
|
||||
"""Transaction B: job error detail + FAILED in one commit."""
|
||||
if session is None:
|
||||
async with services.jobs._session_scope() as local_session:
|
||||
await services.transcriptions.update_job_transcription(
|
||||
job_id=job.id,
|
||||
text=None,
|
||||
error_detail=format_error_detail(error),
|
||||
prompt_name=DEFAULT_PROMPT_FILE,
|
||||
session=local_session,
|
||||
)
|
||||
updated_job = await services.jobs.mark_job_status(
|
||||
job.id,
|
||||
JobStatus.FAILED,
|
||||
session=local_session,
|
||||
)
|
||||
await local_session.commit()
|
||||
return updated_job
|
||||
|
||||
await services.transcriptions.update_job_transcription(
|
||||
job_id=job.id,
|
||||
text=None,
|
||||
error_detail=format_error_detail(error),
|
||||
prompt_name=DEFAULT_PROMPT_FILE,
|
||||
session=session,
|
||||
)
|
||||
updated_job = await services.jobs.mark_job_status(
|
||||
job.id,
|
||||
JobStatus.FAILED,
|
||||
session=session,
|
||||
)
|
||||
updated_job = await services.jobs.mark_job_status(job.id, status, session=session)
|
||||
await session.commit()
|
||||
return updated_job
|
||||
|
||||
|
||||
def _resolve_primary_source(job: Job) -> Source | None:
|
||||
if not job.sources:
|
||||
return None
|
||||
return job.sources[0]
|
||||
|
||||
|
||||
def _validate_transcription_quality(*, result: TranscriptionResult, settings: Settings) -> None:
|
||||
text_chars = len(result.text)
|
||||
text_lines = _line_count(result.text)
|
||||
@@ -343,3 +363,16 @@ def _line_count(text: str) -> int:
|
||||
if not stripped:
|
||||
return 0
|
||||
return sum(1 for line in stripped.splitlines() if line.strip())
|
||||
|
||||
|
||||
def _coerce_job_status(value: object) -> JobStatus | None:
|
||||
if isinstance(value, JobStatus):
|
||||
return value
|
||||
|
||||
if isinstance(value, str):
|
||||
lowered = value.strip().lower()
|
||||
for member in JobStatus:
|
||||
if lowered in {member.value.lower(), member.name.lower()}:
|
||||
return member
|
||||
|
||||
return None
|
||||
|
||||
@@ -1,38 +1,25 @@
|
||||
"""UI page registration exports."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import FastAPI
|
||||
from nicegui import app as nicegui_app
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.ui.pages.home_page import register_page as register_home_page
|
||||
from transcription.ui.pages.documents_page import register_page as register_documents_page
|
||||
from transcription.ui.pages.jobs_page import register_page as register_jobs_page
|
||||
from transcription.ui.pages.upload_page import register_page as register_upload_page
|
||||
from transcription.ui.pages.people_page import register_page as register_people_page
|
||||
from transcription.ui.pages.sources_page import register_page as register_sources_page
|
||||
from transcription.ui.resources import read_css
|
||||
from transcription.ui.theme import apply_archival_theme
|
||||
|
||||
_THEME_REGISTERED_STATE_KEY = "transcription_ui_theme_registered"
|
||||
|
||||
_THEME_COLORS: dict[str, str] = {
|
||||
"primary": "#6f97e8",
|
||||
"secondary": "#92b5f5",
|
||||
"accent": "#7fc0de",
|
||||
"dark": "#22304a",
|
||||
"dark_page": "#1a2538",
|
||||
"positive": "#86c8ad",
|
||||
"negative": "#d98a9a",
|
||||
"info": "#7ebdda",
|
||||
"warning": "#e2c083",
|
||||
}
|
||||
|
||||
|
||||
def _register_global_styles(app: FastAPI) -> None:
|
||||
if getattr(app.state, _THEME_REGISTERED_STATE_KEY, False):
|
||||
return
|
||||
|
||||
nicegui_app.colors(**_THEME_COLORS)
|
||||
|
||||
css_path = Path(__file__).resolve().parent / "static" / "colors.css"
|
||||
if css_path.exists():
|
||||
ui.add_css(css_path, shared=True)
|
||||
apply_archival_theme()
|
||||
ui.add_css(read_css("theme.css"), shared=True)
|
||||
|
||||
setattr(app.state, _THEME_REGISTERED_STATE_KEY, True)
|
||||
|
||||
@@ -40,6 +27,9 @@ def _register_global_styles(app: FastAPI) -> None:
|
||||
def register_pages(app: FastAPI) -> None:
|
||||
"""Register all NiceGUI pages and mount them onto the FastAPI app."""
|
||||
_register_global_styles(app)
|
||||
register_upload_page()
|
||||
register_home_page()
|
||||
register_documents_page()
|
||||
register_people_page()
|
||||
register_sources_page()
|
||||
register_jobs_page()
|
||||
ui.run_with(app, mount_path="/ui", show_welcome_message=False, dark=True)
|
||||
ui.run_with(app, mount_path="/ui", show_welcome_message=False, dark=False)
|
||||
|
||||
@@ -1,7 +1,19 @@
|
||||
"""Reusable UI component exports."""
|
||||
|
||||
from transcription.ui.components.app_shell import NAV_ITEMS
|
||||
from transcription.ui.components.app_shell import render_app_shell
|
||||
from transcription.ui.components.app_shell import render_navigation_header
|
||||
from transcription.ui.components.document_panzoom import render_document_panzoom
|
||||
from transcription.ui.components.primitives import destructive_button
|
||||
from transcription.ui.components.primitives import render_empty_state
|
||||
from transcription.ui.components.primitives import section_header_row
|
||||
|
||||
__all__ = ["NAV_ITEMS", "render_document_panzoom", "render_navigation_header"]
|
||||
__all__ = [
|
||||
"NAV_ITEMS",
|
||||
"destructive_button",
|
||||
"render_app_shell",
|
||||
"render_document_panzoom",
|
||||
"render_empty_state",
|
||||
"render_navigation_header",
|
||||
"section_header_row",
|
||||
]
|
||||
|
||||
@@ -5,55 +5,66 @@ from __future__ import annotations
|
||||
from nicegui import ui
|
||||
|
||||
NAV_ITEMS: tuple[tuple[str, str, str], ...] = (
|
||||
("Upload", "/upload", "upload_file"),
|
||||
("Documents", "/documents", "description"),
|
||||
("People", "/people", "group"),
|
||||
("Sources", "/sources", "folder"),
|
||||
("Jobs", "/jobs", "work_history"),
|
||||
)
|
||||
|
||||
from transcription.ui.theme import VIBESCRIBE_LOGO_SVG
|
||||
|
||||
def _is_active_path(*, current_path: str, item_path: str) -> bool:
|
||||
if item_path == "/jobs":
|
||||
return current_path == "/jobs" or current_path.startswith("/jobs/")
|
||||
if item_path == "/documents":
|
||||
return current_path == "/documents" or current_path.startswith("/documents/")
|
||||
if item_path == "/people":
|
||||
return current_path == "/people" or current_path.startswith("/people/")
|
||||
if item_path == "/sources":
|
||||
return current_path == "/sources" or current_path.startswith("/sources/")
|
||||
return current_path == item_path
|
||||
|
||||
|
||||
def _button_props(*, icon: str, is_active: bool) -> str:
|
||||
if is_active:
|
||||
return f"icon={icon} no-caps unelevated color=primary text-color=white"
|
||||
return f"icon={icon} no-caps outline color=secondary text-color=secondary"
|
||||
|
||||
|
||||
def _button_classes(*, is_active: bool) -> str:
|
||||
base = "w-full sm:w-auto min-h-[40px] px-3 rounded-lg text-body2 text-weight-medium"
|
||||
if is_active:
|
||||
return f"{base}"
|
||||
return f"{base}"
|
||||
|
||||
|
||||
def _render_nav_button(*, label: str, path: str, icon: str, current_path: str) -> None:
|
||||
is_active = _is_active_path(current_path=current_path, item_path=path)
|
||||
button = ui.button(
|
||||
classes = "app-shell__nav-item"
|
||||
if is_active:
|
||||
classes = f"{classes} app-shell__nav-item--active"
|
||||
|
||||
ui.button(
|
||||
label,
|
||||
icon=icon,
|
||||
on_click=lambda _=None, route=path: ui.navigate.to(route),
|
||||
)
|
||||
button.props(_button_props(icon=icon, is_active=is_active)).classes(_button_classes(is_active=is_active))
|
||||
).props("flat no-caps").classes(classes)
|
||||
|
||||
|
||||
def _normalize_path(current_path: str | None) -> str:
|
||||
normalized = (current_path or "").strip()
|
||||
if not normalized:
|
||||
return "/upload"
|
||||
return "/homepage"
|
||||
return normalized.rstrip("/") or "/"
|
||||
|
||||
|
||||
def render_navigation_header(*, current_path: str | None = None) -> None:
|
||||
"""Render a shared app header with links for top-level pages."""
|
||||
def render_app_shell(*, current_path: str | None = None) -> None:
|
||||
"""Render the shared application shell header."""
|
||||
normalized_path = _normalize_path(current_path)
|
||||
|
||||
with (
|
||||
ui.header(elevated=True).props("bordered").classes("bg-dark text-white q-px-sm q-py-xs"),
|
||||
ui.row().classes("w-full items-center justify-end q-gutter-xs"),
|
||||
ui.element("div").classes("w-full grid grid-cols-2 gap-2 sm:flex sm:justify-start sm:gap-2"),
|
||||
):
|
||||
for label, path, icon in NAV_ITEMS:
|
||||
_render_nav_button(label=label, path=path, icon=icon, current_path=normalized_path)
|
||||
with ui.header().classes("app-shell"), ui.element("div").classes("app-shell__inner"):
|
||||
with ui.element("a").props('href="/ui/homepage"').style(
|
||||
"display:flex; align-items:center; gap:0.75rem; text-decoration:none; color:inherit;"
|
||||
).classes("app-shell__brand no-wrap"):
|
||||
ui.html(VIBESCRIBE_LOGO_SVG).classes("app-shell__brand-mark")
|
||||
ui.label("VibeScribe").classes("app-shell__brand-name")
|
||||
|
||||
with ui.element("nav").props('aria-label="Primary navigation"').classes("app-shell__nav"):
|
||||
for label, path, icon in NAV_ITEMS:
|
||||
_render_nav_button(label=label, path=path, icon=icon, current_path=normalized_path)
|
||||
|
||||
with ui.row().classes("app-shell__actions no-wrap"):
|
||||
ui.label("Saved").classes("app-shell__save-state")
|
||||
ui.button(icon="more_horiz").props("flat round dense").tooltip("More actions")
|
||||
|
||||
|
||||
def render_navigation_header(*, current_path: str | None = None) -> None:
|
||||
"""Render the app shell using the legacy page-level entry point."""
|
||||
render_app_shell(current_path=current_path)
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# transcription/ui/components/cards.py
|
||||
from contextlib import contextmanager
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
|
||||
@contextmanager
|
||||
def archival_card(title: str | None = None, extra_classes: str = ""):
|
||||
"""Reusable container for Flat 2.0 Bento Grid cards."""
|
||||
with ui.card().classes(f"w-full ui-card-surface p-4 {extra_classes}") as card:
|
||||
if title:
|
||||
ui.label(title.upper()).classes(
|
||||
"text-xs font-bold ui-text-muted tracking-wider mb-3 ui-header-divider pb-1"
|
||||
)
|
||||
yield card
|
||||
@@ -0,0 +1,14 @@
|
||||
# transcription/ui/components/data_display.py
|
||||
from nicegui import ui
|
||||
|
||||
|
||||
def metadata_row(label: str, value: str):
|
||||
"""Render a high-density, low-contrast key-value pair."""
|
||||
with ui.row().classes("justify-between w-full border-b ui-border-subtle pb-1 text-xs"):
|
||||
ui.label(label).classes("ui-text-muted")
|
||||
ui.label(value).classes("font-semibold ui-text-primary")
|
||||
|
||||
|
||||
def archival_badge(text: str):
|
||||
"""Standardized Aged Sepia badge."""
|
||||
return ui.badge(text, color="secondary", text_color="dark").classes("text-[10px]")
|
||||
@@ -10,7 +10,7 @@ from uuid import uuid4
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.config import get_settings
|
||||
from transcription.models import Source
|
||||
from transcription.db.models import Source
|
||||
|
||||
PANGOZOOM_CDN_URL = "https://unpkg.com/@panzoom/[email protected]/dist/panzoom.min.js"
|
||||
UPLOADS_URL_PREFIX = "/uploads"
|
||||
@@ -24,10 +24,10 @@ def render_document_panzoom(*, source: Source) -> None:
|
||||
document_url = _document_url(source)
|
||||
document_kind = _document_kind(source)
|
||||
|
||||
with ui.card().classes("w-full q-pa-md"):
|
||||
with ui.card().classes("w-full q-pa-md vibe-card"):
|
||||
with ui.row().classes("w-full items-center justify-between no-wrap"):
|
||||
ui.label("Document preview").classes("text-subtitle1 text-weight-medium")
|
||||
ui.label(source.filename).classes("text-caption text-grey-4 ellipsis").style(
|
||||
ui.label(source.filename).classes("text-caption vibe-text-muted ellipsis").style(
|
||||
"max-width: 60%; text-align: right;"
|
||||
)
|
||||
|
||||
@@ -90,7 +90,7 @@ def _register_panzoom_assets() -> None:
|
||||
height: 100%;
|
||||
border: 0;
|
||||
pointer-events: none;
|
||||
background: white;
|
||||
background: var(--theme-surface-raised);
|
||||
}
|
||||
</style>
|
||||
""",
|
||||
|
||||
@@ -26,7 +26,7 @@ def show_error(exc: Exception, *, title: str, operation: str) -> None:
|
||||
close_button="Dismiss",
|
||||
)
|
||||
|
||||
with ui.card().classes("bg-red-1 text-red-10 q-mt-md q-pa-md"):
|
||||
with ui.card().classes("vibe-card--error q-mt-md q-pa-md"):
|
||||
ui.label(title).classes("text-subtitle1")
|
||||
ui.label(error.message)
|
||||
ui.label(f"Suggested action: {error.suggestion}").classes("text-weight-medium")
|
||||
|
||||
@@ -1,91 +0,0 @@
|
||||
"""Reusable job detail rendering helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.models import Job
|
||||
from transcription.models import Revision
|
||||
from transcription.models import Source
|
||||
from transcription.ui.components.document_panzoom import render_document_panzoom
|
||||
from transcription.ui.components.transcript import render_original_transcription_card
|
||||
from transcription.ui.components.transcript import render_revision_row
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _status_chip_classes(status: str) -> str:
|
||||
if status == "queued":
|
||||
return "bg-blue-1 text-blue-10"
|
||||
if status == "processing":
|
||||
return "bg-amber-1 text-amber-10"
|
||||
if status == "transcribed":
|
||||
return "bg-green-1 text-green-10"
|
||||
if status == "failed":
|
||||
return "bg-red-1 text-red-10"
|
||||
return "bg-grey-2 text-grey-9"
|
||||
|
||||
|
||||
def _metadata_row(label: str, value: str) -> None:
|
||||
with ui.row().classes("w-full items-start justify-between q-gutter-x-md"):
|
||||
ui.label(label).classes("text-caption text-grey-5 text-uppercase w-28")
|
||||
ui.label(value).classes("text-body2 text-right text-grey-1 break-all")
|
||||
|
||||
|
||||
def _render_source_section(source: Source) -> None:
|
||||
with ui.card().classes("w-full q-pa-md"):
|
||||
ui.label("Source").classes("text-subtitle1 text-weight-medium")
|
||||
ui.separator().classes("q-my-sm")
|
||||
with ui.column().classes("w-full q-gutter-y-xs"):
|
||||
_metadata_row("Upload name", source.upload_name)
|
||||
_metadata_row("Stored filename", source.filename)
|
||||
_metadata_row("File path", source.file_path)
|
||||
_metadata_row("Uploaded", source.date_uploaded.isoformat())
|
||||
|
||||
ui.separator().classes("q-my-md")
|
||||
render_document_panzoom(source=source)
|
||||
|
||||
|
||||
def _render_revision_section(revision: Revision | None) -> None:
|
||||
with ui.card().classes("w-full q-pa-md"):
|
||||
ui.label("Revision").classes("text-subtitle1 text-weight-medium")
|
||||
ui.separator().classes("q-my-sm")
|
||||
|
||||
if revision is None:
|
||||
ui.label("No revision exists for this source.").classes("text-body2 text-grey-3")
|
||||
return
|
||||
|
||||
render_revision_row(revision=revision, initially_expanded=True)
|
||||
|
||||
|
||||
def render_job_detail(*, job: Job, source: Source | None, revision: Revision | None) -> None:
|
||||
"""Render all sections for the job detail page."""
|
||||
logger.debug("Rendering job detail for job ID %s", job.id)
|
||||
status_text = job.status.value
|
||||
with ui.column().classes("w-full max-w-4xl q-gutter-md"):
|
||||
with ui.card().classes("w-full q-pa-lg"):
|
||||
with ui.row().classes("w-full items-center justify-between q-gutter-md"):
|
||||
with ui.column().classes("q-gutter-none"):
|
||||
ui.label("Job overview").classes("text-h6 text-weight-bold")
|
||||
ui.label(str(job.id)).classes("text-caption text-grey-5")
|
||||
status_chip_classes = (
|
||||
"q-px-sm q-py-xs rounded-borders "
|
||||
"text-weight-medium text-capitalize "
|
||||
f"{_status_chip_classes(status_text)}"
|
||||
)
|
||||
ui.label(status_text).classes(status_chip_classes)
|
||||
|
||||
ui.separator().classes("q-my-md bg-blue-grey-7")
|
||||
with ui.column().classes("w-full q-gutter-y-xs"):
|
||||
_metadata_row("Created", job.date_created.isoformat())
|
||||
_metadata_row("Updated", job.date_updated.isoformat())
|
||||
_metadata_row("Retries", str(job.retry_count))
|
||||
|
||||
render_original_transcription_card(job=job)
|
||||
|
||||
if source is not None:
|
||||
_render_source_section(source)
|
||||
|
||||
_render_revision_section(revision)
|
||||
@@ -0,0 +1,38 @@
|
||||
from contextlib import contextmanager
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
|
||||
@contextmanager
|
||||
def section_header_row(*, classes: str = ""):
|
||||
"""Render a standardized section header row container."""
|
||||
base_classes = "w-full items-center justify-between pb-2 ui-header-divider"
|
||||
with ui.row().classes(f"{base_classes} {classes}".strip()) as row:
|
||||
yield row
|
||||
|
||||
|
||||
def render_empty_state(message: str, *, italic: bool = False, extra_classes: str = "") -> None:
|
||||
"""Render standardized empty-state helper text."""
|
||||
classes = "text-xs ui-text-muted"
|
||||
if italic:
|
||||
classes = f"{classes} italic"
|
||||
ui.label(message).classes(f"{classes} {extra_classes}".strip())
|
||||
|
||||
|
||||
def destructive_button(
|
||||
label: str,
|
||||
*,
|
||||
on_click,
|
||||
icon: str,
|
||||
variant: str = "outlined",
|
||||
extra_classes: str = "",
|
||||
):
|
||||
"""Render a standardized destructive action button."""
|
||||
button = ui.button(label, on_click=on_click, icon=icon)
|
||||
if variant == "solid":
|
||||
button.props("unelevated color=negative")
|
||||
else:
|
||||
button.props("outlined color=negative")
|
||||
if extra_classes:
|
||||
button.classes(extra_classes)
|
||||
return button
|
||||
@@ -4,26 +4,21 @@ import logging
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from nicegui import events
|
||||
from nicegui import ui
|
||||
from nicegui import events, ui
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _extract_row_id(args: Any) -> str | None:
|
||||
if isinstance(args, dict):
|
||||
if isinstance(args.get("row"), dict):
|
||||
row_id = args["row"].get("id")
|
||||
return str(row_id) if row_id is not None else None
|
||||
row_id = args.get("id")
|
||||
return str(row_id) if row_id is not None else None
|
||||
if isinstance(args, list) and len(args) > 1 and isinstance(args[1], dict):
|
||||
return str(args[1].get("id")) if args[1].get("id") is not None else None
|
||||
|
||||
if isinstance(args, list):
|
||||
for value in args:
|
||||
if isinstance(value, dict):
|
||||
row_id = value.get("id")
|
||||
if row_id is not None:
|
||||
return str(row_id)
|
||||
if isinstance(args, dict):
|
||||
row = args.get("row")
|
||||
if isinstance(row, dict) and "id" in row:
|
||||
return str(row["id"])
|
||||
if "id" in args:
|
||||
return str(args["id"])
|
||||
|
||||
return None
|
||||
|
||||
@@ -40,7 +35,6 @@ def _bind_row_click_handler(
|
||||
on_row_click_id(row_id)
|
||||
|
||||
table.on("rowClick", handle_row_click)
|
||||
logger.debug("Row click handler bound to table")
|
||||
|
||||
|
||||
def build_table(
|
||||
@@ -49,25 +43,47 @@ def build_table(
|
||||
*,
|
||||
default_sort_by: str | None = None,
|
||||
default_descending: bool = False,
|
||||
classes: str = "app-table",
|
||||
classes: str = "",
|
||||
show_search: bool = True,
|
||||
search_placeholder: str = "Search records...",
|
||||
on_row_click_id: Callable[[str], None] | None = None,
|
||||
) -> Any:
|
||||
"""Build a styled Quasar table widget with optional client-side filtering and row-click handlers."""
|
||||
pagination: dict[str, Any] = {"rowsPerPage": 25}
|
||||
if default_sort_by is not None:
|
||||
pagination["sortBy"] = default_sort_by
|
||||
pagination["descending"] = default_descending
|
||||
|
||||
table = (
|
||||
ui.table(
|
||||
rows=rows,
|
||||
columns=columns,
|
||||
row_key="id",
|
||||
pagination=pagination,
|
||||
# Use a parent container to hold both the search bar and the table seamlessly
|
||||
with ui.column().classes("w-full gap-2"):
|
||||
if show_search:
|
||||
with ui.row().classes("w-full items-center justify-end"):
|
||||
search_input = (
|
||||
ui.input(placeholder=search_placeholder)
|
||||
.props("dense outlined clearable icon=search")
|
||||
.classes("w-64 text-xs bg-white")
|
||||
)
|
||||
|
||||
table = (
|
||||
ui.table(
|
||||
rows=rows,
|
||||
columns=columns,
|
||||
row_key="id",
|
||||
pagination=pagination,
|
||||
)
|
||||
.classes(f"w-full ui-table {classes}".strip())
|
||||
.props(
|
||||
'flat square binary-state-sort table-style="table-layout: fixed; width: 100%;" '
|
||||
'header-cell-class="ui-table-header text-xs uppercase tracking-wider" '
|
||||
'table-class="ui-table-body text-xs"'
|
||||
)
|
||||
)
|
||||
.classes(classes)
|
||||
.props('table-style="table-layout: fixed; width: 100%;"')
|
||||
)
|
||||
logger.info("Table built with %d rows and %d columns", len(rows), len(columns))
|
||||
|
||||
# Bind client-side text filter if search input is active
|
||||
if show_search:
|
||||
table.bind_filter_from(search_input, "value")
|
||||
|
||||
if on_row_click_id is not None:
|
||||
_bind_row_click_handler(table, on_row_click_id=on_row_click_id)
|
||||
|
||||
return table
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Documents table rendering helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.primitives import render_empty_state
|
||||
from transcription.ui.components.table.common import build_table
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class DocumentTableRow:
|
||||
"""Read model consumed by the documents table component."""
|
||||
|
||||
id: UUID
|
||||
name: str
|
||||
document_type: str
|
||||
archive_identifier: str
|
||||
created_at: str
|
||||
|
||||
|
||||
def _serialize_rows(rows: Sequence[DocumentTableRow]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"id": str(row.id),
|
||||
"name": row.name,
|
||||
"document_type": row.document_type or "Unspecified",
|
||||
"archive_identifier": row.archive_identifier or "N/A",
|
||||
"created_at": row.created_at,
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def render_documents_table(rows: Sequence[DocumentTableRow]) -> None:
|
||||
"""Render documents table with search filtering and custom type chips."""
|
||||
if not rows:
|
||||
with archival_card(extra_classes="p-8 text-center"):
|
||||
render_empty_state("No documents found in repository.")
|
||||
return
|
||||
|
||||
table = build_table(
|
||||
rows=_serialize_rows(rows),
|
||||
columns=[
|
||||
{
|
||||
"name": "name",
|
||||
"label": "Document Title",
|
||||
"field": "name",
|
||||
"sortable": True,
|
||||
"classes": "font-serif font-semibold",
|
||||
},
|
||||
{
|
||||
"name": "document_type",
|
||||
"label": "Type",
|
||||
"field": "document_type",
|
||||
"sortable": True,
|
||||
},
|
||||
{
|
||||
"name": "archive_identifier",
|
||||
"label": "Archive Ref",
|
||||
"field": "archive_identifier",
|
||||
"sortable": True,
|
||||
"classes": "font-mono text-xs",
|
||||
},
|
||||
{
|
||||
"name": "created_at",
|
||||
"label": "Created",
|
||||
"field": "created_at",
|
||||
"sortable": True,
|
||||
},
|
||||
],
|
||||
default_sort_by="name",
|
||||
search_placeholder="Search documents by title, type, or reference...",
|
||||
on_row_click_id=lambda doc_id: ui.navigate.to(f"/documents/{doc_id}"),
|
||||
)
|
||||
|
||||
# Render document type using a subtle Quasar badge
|
||||
table.add_slot(
|
||||
"body-cell-document_type",
|
||||
r"""
|
||||
<q-td :props="props">
|
||||
<q-chip
|
||||
dense
|
||||
square
|
||||
size="sm"
|
||||
color="primary"
|
||||
text-color="white"
|
||||
>
|
||||
{{ props.value }}
|
||||
</q-chip>
|
||||
</q-td>
|
||||
""",
|
||||
)
|
||||
@@ -4,13 +4,14 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC
|
||||
from datetime import datetime
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.primitives import render_empty_state
|
||||
from .common import build_table
|
||||
|
||||
|
||||
@@ -27,7 +28,7 @@ class JobTableRow:
|
||||
|
||||
|
||||
def _format_timestamp(value: str) -> str:
|
||||
"""Return a friendly UTC timestamp for table display."""
|
||||
"""Return a friendly local timestamp for table display."""
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
@@ -40,7 +41,7 @@ def _serialize_rows(rows: Sequence[JobTableRow]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"id": str(row.id),
|
||||
"status": row.status,
|
||||
"status": row.status.lower(),
|
||||
"filename": row.filename,
|
||||
"retry_count": row.retry_count,
|
||||
"date_created": _format_timestamp(row.date_created),
|
||||
@@ -53,23 +54,80 @@ def _serialize_rows(rows: Sequence[JobTableRow]) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def render_jobs_table(rows: Sequence[JobTableRow]) -> None:
|
||||
"""Render jobs table and open a detail page when clicking a row."""
|
||||
"""Render jobs table with search filtering and custom status chips."""
|
||||
if not rows:
|
||||
ui.label("No jobs yet.")
|
||||
with archival_card(extra_classes="p-8 text-center"):
|
||||
render_empty_state("No job records found in repository.")
|
||||
return
|
||||
|
||||
build_table(
|
||||
table = build_table(
|
||||
rows=_serialize_rows(rows),
|
||||
columns=[
|
||||
{"name": "id", "label": "Job ID", "field": "id", "sortable": True},
|
||||
{"name": "status", "label": "Status", "field": "status", "sortable": True},
|
||||
{"name": "filename", "label": "Filename", "field": "filename", "sortable": True},
|
||||
{"name": "retry_count", "label": "Retries", "field": "retry_count", "sortable": True},
|
||||
{"name": "date_created", "label": "Created", "field": "date_created", "sortable": True},
|
||||
{"name": "date_updated", "label": "Updated", "field": "date_updated", "sortable": True},
|
||||
{
|
||||
"name": "id",
|
||||
"label": "Job ID",
|
||||
"field": "id",
|
||||
"sortable": True,
|
||||
"classes": "font-mono text-xs",
|
||||
},
|
||||
{
|
||||
"name": "status",
|
||||
"label": "Status",
|
||||
"field": "status",
|
||||
"sortable": True,
|
||||
"classes": "font-mono",
|
||||
},
|
||||
{
|
||||
"name": "filename",
|
||||
"label": "Source Filename",
|
||||
"field": "filename",
|
||||
"sortable": True,
|
||||
"classes": "font-mono text-xs",
|
||||
},
|
||||
{
|
||||
"name": "retry_count",
|
||||
"label": "Retries",
|
||||
"field": "retry_count",
|
||||
"sortable": True,
|
||||
},
|
||||
{
|
||||
"name": "date_created",
|
||||
"label": "Created",
|
||||
"field": "created_sort",
|
||||
"sortable": True,
|
||||
},
|
||||
{
|
||||
"name": "date_updated",
|
||||
"label": "Updated",
|
||||
"field": "updated_sort",
|
||||
"sortable": True,
|
||||
},
|
||||
],
|
||||
default_sort_by="created_sort",
|
||||
default_descending=True,
|
||||
classes="app-table w-full",
|
||||
search_placeholder="Search jobs by ID, filename, or status...",
|
||||
on_row_click_id=lambda job_id: ui.navigate.to(f"/jobs/{job_id}"),
|
||||
)
|
||||
|
||||
# Render job execution status using themed Quasar chips
|
||||
table.add_slot(
|
||||
"body-cell-status",
|
||||
r"""
|
||||
<q-td :props="props">
|
||||
<q-chip
|
||||
dense
|
||||
square
|
||||
size="sm"
|
||||
:color="
|
||||
props.value === 'completed' || props.value === 'transcribed' ? 'positive' :
|
||||
props.value === 'failed' ? 'negative' :
|
||||
props.value === 'processing' ? 'secondary' :
|
||||
props.value === 'queued' ? 'warning' : 'grey-6'
|
||||
"
|
||||
text-color="white"
|
||||
>
|
||||
{{ props.value.toUpperCase() }}
|
||||
</q-chip>
|
||||
</q-td>
|
||||
""",
|
||||
)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""People table rendering helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.primitives import render_empty_state
|
||||
from transcription.ui.components.table.common import build_table
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class PersonTableRow:
|
||||
"""Read model consumed by the people table component."""
|
||||
|
||||
id: UUID
|
||||
full_name: str
|
||||
display_name: str
|
||||
maiden_name: str
|
||||
birth_date: str
|
||||
|
||||
|
||||
def _serialize_rows(rows: Sequence[PersonTableRow]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"id": str(row.id),
|
||||
"full_name": row.full_name,
|
||||
"display_name": row.display_name or "Not set",
|
||||
"maiden_name": row.maiden_name or "N/A",
|
||||
"birth_date": row.birth_date or "Unknown",
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def render_people_table(rows: Sequence[PersonTableRow]) -> None:
|
||||
"""Render people table with search filtering and custom typography."""
|
||||
if not rows:
|
||||
with archival_card(extra_classes="p-8 text-center"):
|
||||
render_empty_state("No person records found in repository.")
|
||||
return
|
||||
|
||||
table = build_table(
|
||||
rows=_serialize_rows(rows),
|
||||
columns=[
|
||||
{
|
||||
"name": "full_name",
|
||||
"label": "Full Name",
|
||||
"field": "full_name",
|
||||
"sortable": True,
|
||||
"classes": "font-serif font-semibold",
|
||||
},
|
||||
{
|
||||
"name": "display_name",
|
||||
"label": "Display Name",
|
||||
"field": "display_name",
|
||||
"sortable": True,
|
||||
},
|
||||
{
|
||||
"name": "maiden_name",
|
||||
"label": "Maiden Name",
|
||||
"field": "maiden_name",
|
||||
"sortable": True,
|
||||
},
|
||||
{
|
||||
"name": "birth_date",
|
||||
"label": "Birth Date",
|
||||
"field": "birth_date",
|
||||
"sortable": True,
|
||||
"classes": "font-mono text-xs",
|
||||
},
|
||||
],
|
||||
default_sort_by="full_name",
|
||||
search_placeholder="Search people by name or birth date...",
|
||||
on_row_click_id=lambda person_id: ui.navigate.to(f"/people/{person_id}"),
|
||||
)
|
||||
|
||||
# Custom column template adding an archival entity icon next to person's name
|
||||
table.add_slot(
|
||||
"body-cell-full_name",
|
||||
r"""
|
||||
<q-td :props="props">
|
||||
<div class="row items-center q-gutter-x-xs">
|
||||
<q-icon name="person" size="xs" color="primary" />
|
||||
<span class="font-serif font-semibold">{{ props.value }}</span>
|
||||
</div>
|
||||
</q-td>
|
||||
""",
|
||||
)
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Sources table rendering helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.primitives import render_empty_state
|
||||
from transcription.ui.components.table.common import build_table
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class SourceTableRow:
|
||||
"""Read model consumed by the sources table component."""
|
||||
|
||||
id: UUID
|
||||
page_number: int
|
||||
upload_name: str
|
||||
filename: str
|
||||
document_id: UUID
|
||||
document_name: str | None = None
|
||||
job_source_status: str | None = None
|
||||
job_source_error_detail: str | None = None
|
||||
|
||||
|
||||
def _serialize_rows(rows: Sequence[SourceTableRow]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
"id": str(row.id),
|
||||
"page_number": row.page_number,
|
||||
"upload_name": row.upload_name,
|
||||
"filename": row.filename,
|
||||
"document_id": str(row.document_id),
|
||||
"document_name": row.document_name or "-",
|
||||
"job_source_status": row.job_source_status or "-",
|
||||
"job_source_error_detail": row.job_source_error_detail or "-",
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def render_sources_table(rows: Sequence[SourceTableRow]) -> None:
|
||||
"""Render sources table and open detail page when clicking a row."""
|
||||
if not rows:
|
||||
with archival_card(extra_classes="p-8 text-center"):
|
||||
render_empty_state("No source asset records found in repository.")
|
||||
return
|
||||
|
||||
table = build_table(
|
||||
rows=_serialize_rows(rows),
|
||||
columns=[
|
||||
{
|
||||
"name": "document_name",
|
||||
"label": "Document Name",
|
||||
"field": "document_name",
|
||||
"sortable": True,
|
||||
"classes": "font-serif",
|
||||
},
|
||||
{
|
||||
"name": "page_number",
|
||||
"label": "Page Number",
|
||||
"field": "page_number",
|
||||
"sortable": True,
|
||||
},
|
||||
{
|
||||
"name": "upload_name",
|
||||
"label": "Upload Title",
|
||||
"field": "upload_name",
|
||||
"sortable": True,
|
||||
"classes": "font-serif",
|
||||
},
|
||||
{
|
||||
"name": "filename",
|
||||
"label": "Stored Filename",
|
||||
"field": "filename",
|
||||
"sortable": True,
|
||||
"classes": "font-mono",
|
||||
},
|
||||
{
|
||||
"name": "job_source_status",
|
||||
"label": "Status",
|
||||
"field": "job_source_status",
|
||||
"sortable": True,
|
||||
"classes": "font-mono",
|
||||
},
|
||||
{
|
||||
"name": "job_source_error_detail",
|
||||
"label": "Error Detail",
|
||||
"field": "job_source_error_detail",
|
||||
"sortable": False,
|
||||
"classes": "font-mono text-xs truncate max-w-xs vibe-text-muted",
|
||||
},
|
||||
],
|
||||
default_sort_by="page_number",
|
||||
on_row_click_id=lambda source_id: ui.navigate.to(f"/sources/{source_id}"),
|
||||
)
|
||||
|
||||
# Render job execution status using themed Quasar chips
|
||||
table.add_slot(
|
||||
"body-cell-job_source_status",
|
||||
r"""
|
||||
<q-td :props="props">
|
||||
<q-chip
|
||||
dense
|
||||
square
|
||||
size="sm"
|
||||
:color="props.value === 'transcribed' ? 'positive' : props.value === 'failed' ? 'negative' : 'grey-5'"
|
||||
text-color="white"
|
||||
>
|
||||
{{ props.value }}
|
||||
</q-chip>
|
||||
</q-td>
|
||||
""",
|
||||
)
|
||||
@@ -9,63 +9,68 @@ from typing import Any
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.models import Job
|
||||
from transcription.models import Revision
|
||||
from transcription.db.models import Job
|
||||
from transcription.db.models import JobSource
|
||||
from transcription.db.models import Source
|
||||
|
||||
type RevisionAction = Callable[[Revision], Awaitable[None] | None]
|
||||
type RevisionAction = Callable[[Source], Awaitable[None] | None]
|
||||
|
||||
|
||||
def render_original_transcription_card(*, job: Job, classes: str = "w-full") -> Any:
|
||||
"""Render the immutable original job transcription output."""
|
||||
status_label = "Failed" if job.error_detail else "Transcribed"
|
||||
latest_error_detail = _latest_job_error_detail(job)
|
||||
status_label = "Failed" if latest_error_detail else "Transcribed"
|
||||
header = f"Original Transcription | {status_label}"
|
||||
provider = job.provider or "unknown"
|
||||
model = job.model or "unknown"
|
||||
caption = f"{provider} | {model} | {_format_created_at(job.date_updated)}"
|
||||
|
||||
card = ui.card().classes(f"{classes} q-pa-md bg-blue-grey-10")
|
||||
card = ui.card().classes(f"{classes} q-pa-md vibe-card")
|
||||
with card, ui.column().classes("w-full q-gutter-y-sm"):
|
||||
ui.label(header).classes("text-subtitle1 text-weight-medium")
|
||||
ui.label(caption).classes("text-caption text-grey-5")
|
||||
_metadata_row(label="Prompt", value=job.prompt_name or "unknown")
|
||||
ui.label(caption).classes("text-caption vibe-text-muted")
|
||||
_metadata_row(label="Prompt", value=_latest_job_prompt(job) or "unknown")
|
||||
_metadata_row(label="Updated", value=_format_created_at(job.date_updated))
|
||||
|
||||
if job.text:
|
||||
with ui.card().classes("w-full q-pa-sm"):
|
||||
ui.markdown(job.text)
|
||||
latest_transcription = _latest_job_transcription(job)
|
||||
|
||||
if job.error_detail:
|
||||
with ui.card().classes("w-full bg-red-1 text-red-10 q-pa-sm"):
|
||||
if latest_transcription:
|
||||
with ui.card().classes("w-full q-pa-sm"):
|
||||
ui.markdown(latest_transcription)
|
||||
|
||||
if latest_error_detail:
|
||||
with ui.card().classes("w-full vibe-card--error q-pa-sm"):
|
||||
ui.label("Failure detail").classes("text-caption text-uppercase")
|
||||
ui.label(job.error_detail).classes("text-body2")
|
||||
ui.label(latest_error_detail).classes("text-body2")
|
||||
|
||||
return card
|
||||
|
||||
|
||||
def render_revision_row(
|
||||
*,
|
||||
revision: Revision,
|
||||
revision: Source | None,
|
||||
initially_expanded: bool = False,
|
||||
classes: str = "w-full",
|
||||
on_delete: RevisionAction | None = None,
|
||||
) -> Any:
|
||||
"""Render a collapsible row for the single optional source revision."""
|
||||
header = "Revision | User-authored"
|
||||
caption = _format_created_at(revision.date_created)
|
||||
if revision is None:
|
||||
return None
|
||||
|
||||
expansion = ui.expansion(value=initially_expanded, group="group").classes(
|
||||
f"{classes} rounded-borders bg-blue-grey-10"
|
||||
)
|
||||
header = "Source revision | User-authored"
|
||||
caption = _format_created_at(revision.date_revised or revision.date_uploaded)
|
||||
|
||||
expansion = ui.expansion(value=initially_expanded, group="group").classes(f"{classes} rounded-borders vibe-card")
|
||||
|
||||
with expansion, ui.column().classes("w-full q-gutter-y-sm q-pa-sm"):
|
||||
with expansion.add_slot("header"), ui.row().classes("w-full items-start justify-between q-gutter-md"):
|
||||
with ui.column().classes("q-gutter-none"):
|
||||
ui.label(header).classes("text-subtitle1 text-weight-medium")
|
||||
ui.label(caption).classes("text-caption text-grey-5")
|
||||
ui.label(caption).classes("text-caption vibe-text-muted")
|
||||
|
||||
if on_delete is not None:
|
||||
with ui.dialog() as delete_dialog, ui.card().classes("q-pa-md"):
|
||||
ui.label("Delete this transcript revision?").classes("text-body1")
|
||||
ui.label("Delete this source revision?").classes("text-body1")
|
||||
with ui.row().classes("w-full justify-end q-gutter-sm"):
|
||||
ui.button("Cancel", on_click=lambda: delete_dialog.submit(False)).props("flat")
|
||||
ui.button("Delete", on_click=lambda: delete_dialog.submit(True)).props(
|
||||
@@ -86,15 +91,36 @@ def render_revision_row(
|
||||
ui.button(icon="delete", on_click=delete_current_transcript).props(
|
||||
'flat round dense color="negative"'
|
||||
)
|
||||
_metadata_row(label="Created", value=_format_created_at(revision.date_created))
|
||||
_metadata_row(label="Created", value=_format_created_at(revision.date_revised or revision.date_uploaded))
|
||||
|
||||
if revision.text:
|
||||
if revision.revised_text:
|
||||
with ui.card().classes("w-full q-pa-sm"):
|
||||
ui.markdown(revision.text)
|
||||
ui.markdown(revision.revised_text)
|
||||
|
||||
return expansion
|
||||
|
||||
|
||||
def _latest_job_transcription(job: Job) -> str | None:
|
||||
for job_source in sorted(job.job_sources, key=lambda item: item.executed_at, reverse=True):
|
||||
if job_source.raw_transcription:
|
||||
return job_source.raw_transcription
|
||||
return None
|
||||
|
||||
|
||||
def _latest_job_error_detail(job: Job) -> str | None:
|
||||
for job_source in sorted(job.job_sources, key=lambda item: item.executed_at, reverse=True):
|
||||
if job_source.error_detail:
|
||||
return job_source.error_detail
|
||||
return None
|
||||
|
||||
|
||||
def _latest_job_prompt(job: Job) -> str | None:
|
||||
for job_source in sorted(job.job_sources, key=lambda item: item.executed_at, reverse=True):
|
||||
if job_source.job and job_source.job.prompt_name:
|
||||
return job_source.job.prompt_name
|
||||
return None
|
||||
|
||||
|
||||
def _format_created_at(value: datetime) -> str:
|
||||
"""Return a compact UTC-like timestamp for row captions."""
|
||||
return value.strftime("%Y-%m-%d %H:%M:%S %Z")
|
||||
@@ -102,5 +128,5 @@ def _format_created_at(value: datetime) -> str:
|
||||
|
||||
def _metadata_row(*, label: str, value: str) -> None:
|
||||
with ui.row().classes("w-md items-start justify-between q-gutter-x-md"):
|
||||
ui.label(label).classes("text-caption text-grey-5 text-uppercase")
|
||||
ui.label(value).classes("text-body2 text-right text-grey-1 break-all")
|
||||
ui.label(label).classes("text-caption vibe-text-muted text-uppercase")
|
||||
ui.label(value).classes("text-body2 text-right break-all")
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
"""Reusable upload widget for document submission."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Awaitable
|
||||
from collections.abc import Callable
|
||||
|
||||
from nicegui import ui
|
||||
from nicegui.binding import bindable_dataclass
|
||||
from nicegui.events import UploadEventArguments
|
||||
|
||||
from transcription.errors import AppError
|
||||
from transcription.services.documents import UploadJobResult
|
||||
from transcription.ui.components.error_presenter import show_error
|
||||
from transcription.ui.components.error_presenter import summarize_error
|
||||
from transcription.worker import WorkerNotifier
|
||||
|
||||
type UploadSubmitter = Callable[[str, bytes], Awaitable[UploadJobResult]]
|
||||
|
||||
|
||||
@bindable_dataclass
|
||||
class UploadWidgetState:
|
||||
"""Simple state container for upload feedback."""
|
||||
|
||||
loading: bool = False
|
||||
message: str = ""
|
||||
|
||||
|
||||
def render_upload_widget(*, submitter: UploadSubmitter, notifier: WorkerNotifier | None = None) -> None:
|
||||
"""Render upload controls and common status/error handling."""
|
||||
state = UploadWidgetState()
|
||||
status_label = ui.label("Upload a document to start transcription.")
|
||||
status_label.bind_text(state, "message")
|
||||
|
||||
async def on_upload(event: UploadEventArguments) -> None:
|
||||
if state.loading:
|
||||
ui.notify("Upload already in progress. Please wait.", type="warning")
|
||||
return
|
||||
|
||||
state.loading = True
|
||||
status_label.text = "Uploading..."
|
||||
try:
|
||||
payload = await event.file.read()
|
||||
result = await submitter(event.file.name, payload)
|
||||
job_id = result.job_id
|
||||
state.message = f"Created job {job_id}" if job_id is not None else "Upload complete"
|
||||
status_label.text = state.message
|
||||
if notifier is not None:
|
||||
notifier.notify()
|
||||
ui.notify(state.message, type="positive")
|
||||
except AppError as exc:
|
||||
state.message = summarize_error(exc, operation="upload.submit")
|
||||
status_label.text = f"Upload failed: {state.message}"
|
||||
show_error(exc, title="Upload failed", operation="upload.submit")
|
||||
except Exception as exc: # noqa: BLE001
|
||||
state.message = summarize_error(exc, operation="upload.submit")
|
||||
status_label.text = f"Upload failed: {state.message}"
|
||||
show_error(exc, title="Upload failed", operation="upload.submit")
|
||||
finally:
|
||||
state.loading = False
|
||||
|
||||
ui.upload(
|
||||
on_upload=on_upload,
|
||||
auto_upload=True,
|
||||
label="Select document file",
|
||||
).props('accept=".jpg,.jpeg,.png,.tif,.tiff,.pdf"')
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Simple media display components."""
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
|
||||
def dark_room_viewer(
|
||||
image_path: str | None,
|
||||
count_label: str = "1 Source Linked",
|
||||
*,
|
||||
container_height: str = "500px",
|
||||
) -> None:
|
||||
"""Render a plain responsive image that fills available width."""
|
||||
del count_label
|
||||
|
||||
if image_path:
|
||||
ui.image(image_path).classes("w-full rounded-sm block").style("height: auto;")
|
||||
return
|
||||
|
||||
with ui.column().classes(
|
||||
"w-full items-center justify-center border ui-border-viewer ui-bg-viewer-overlay-soft rounded-sm p-8"
|
||||
).style(f"min-height: {container_height};"):
|
||||
ui.label("No source media available for inspection.").classes("ui-text-muted text-xs italic")
|
||||
@@ -0,0 +1,62 @@
|
||||
"""File-backed storage helpers for the homepage content."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
HOME_PAGE_DIR = Path(__file__).resolve().parents[3] / "data" / "homepage"
|
||||
HOME_PAGE_MARKDOWN_PATH = HOME_PAGE_DIR / "homepage.md"
|
||||
SUPPORTED_IMAGE_SUFFIXES = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tif", ".tiff"}
|
||||
|
||||
|
||||
def ensure_homepage_storage() -> None:
|
||||
"""Create the homepage storage directory when needed."""
|
||||
HOME_PAGE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def read_homepage_markdown() -> str:
|
||||
"""Read the saved homepage markdown text."""
|
||||
ensure_homepage_storage()
|
||||
if not HOME_PAGE_MARKDOWN_PATH.exists():
|
||||
return ""
|
||||
return HOME_PAGE_MARKDOWN_PATH.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def save_homepage_markdown(markdown_text: str) -> None:
|
||||
"""Persist the homepage markdown text."""
|
||||
ensure_homepage_storage()
|
||||
HOME_PAGE_MARKDOWN_PATH.write_text(markdown_text, encoding="utf-8")
|
||||
|
||||
|
||||
def store_homepage_image(*, filename: str, file_bytes: bytes) -> Path:
|
||||
"""Persist an uploaded homepage image in the shared homepage folder."""
|
||||
ensure_homepage_storage()
|
||||
|
||||
safe_name = Path(filename).name
|
||||
if not safe_name:
|
||||
msg = "Homepage image filename is required"
|
||||
raise ValueError(msg)
|
||||
|
||||
stored_path = HOME_PAGE_DIR / safe_name
|
||||
stored_path.write_bytes(file_bytes)
|
||||
return stored_path
|
||||
|
||||
|
||||
def list_homepage_images() -> list[Path]:
|
||||
"""List stored homepage images in the order they were last updated."""
|
||||
ensure_homepage_storage()
|
||||
|
||||
image_paths = [
|
||||
path
|
||||
for path in HOME_PAGE_DIR.iterdir()
|
||||
if path.is_file() and path.suffix.lower() in SUPPORTED_IMAGE_SUFFIXES
|
||||
]
|
||||
return sorted(image_paths, key=lambda path: (path.stat().st_mtime, path.name))
|
||||
|
||||
|
||||
def latest_homepage_image() -> Path | None:
|
||||
"""Return the most recently updated homepage image, if one exists."""
|
||||
image_paths = list_homepage_images()
|
||||
if not image_paths:
|
||||
return None
|
||||
return image_paths[-1]
|
||||
@@ -0,0 +1,490 @@
|
||||
"""Documents list and detail page registration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Request
|
||||
from fastapi.responses import RedirectResponse
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.db.models import Document, DocumentPerson, DocumentPersonRole
|
||||
from transcription.errors import ErrorCategory
|
||||
from transcription.services.documents import (
|
||||
DocumentDeleteBlockedError,
|
||||
DocumentError,
|
||||
DocumentService,
|
||||
)
|
||||
from transcription.ui.components.app_shell import render_navigation_header
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.data_display import archival_badge, metadata_row
|
||||
from transcription.ui.components.error_presenter import show_error
|
||||
from transcription.ui.components.primitives import (
|
||||
destructive_button,
|
||||
render_empty_state,
|
||||
section_header_row,
|
||||
)
|
||||
from transcription.ui.components.table.documents import DocumentTableRow, render_documents_table
|
||||
from transcription.ui.components.viewers import dark_room_viewer
|
||||
from transcription.ui.theme import page_header
|
||||
|
||||
from ...db.session import SessionFactoryDep
|
||||
|
||||
CREATE_NEW_PERSON_OPTION = "__create_new_person__"
|
||||
|
||||
|
||||
def register_page() -> None:
|
||||
"""Register documents list and detail routes."""
|
||||
|
||||
@ui.page("/documents/new")
|
||||
async def document_create_page(request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
document_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/documents")
|
||||
|
||||
with ui.column().classes("w-full max-w-4xl mx-auto p-4 gap-4"):
|
||||
page_header("Create Document", subtitle="Document name is required.")
|
||||
|
||||
people = sorted(await document_service.list_people(), key=lambda item: item.full_name.casefold())
|
||||
form = _render_document_form_fields(people=people)
|
||||
|
||||
requested_doc_id = request.query_params.get("document_id")
|
||||
return_to = request.query_params.get("return_to")
|
||||
|
||||
async def submit_create() -> None:
|
||||
candidate_name = (form["name"].value or "").strip()
|
||||
if not candidate_name:
|
||||
ui.notify("Document name is required.", type="warning")
|
||||
return
|
||||
|
||||
parsed_date = _parse_iso_date(form["date"].value)
|
||||
if form["date"].value and parsed_date is None:
|
||||
ui.notify("Exact date must use YYYY-MM-DD.", type="warning")
|
||||
return
|
||||
|
||||
candidate = Document(
|
||||
name=candidate_name,
|
||||
document_type=(form["type"].value or "").strip() or None,
|
||||
document_date=parsed_date,
|
||||
document_date_raw=(form["date_raw"].value or "").strip() or None,
|
||||
location_created=(form["location"].value or "").strip() or None,
|
||||
notes=(form["notes"].value or "").strip() or None,
|
||||
archive_identifier=(form["archive"].value or "").strip() or None,
|
||||
)
|
||||
|
||||
try:
|
||||
created = await document_service.create_document(candidate)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Create failed", operation="documents.create")
|
||||
return
|
||||
|
||||
selected_author = (form["author"].value or "").strip()
|
||||
if selected_author == CREATE_NEW_PERSON_OPTION:
|
||||
ui.navigate.to("/people/new")
|
||||
return
|
||||
if selected_author:
|
||||
parsed_author_id = _parse_uuid(selected_author)
|
||||
if parsed_author_id is None:
|
||||
ui.notify("Selected author is invalid.", type="warning")
|
||||
return
|
||||
|
||||
try:
|
||||
await document_service.create_document_person(
|
||||
DocumentPerson(
|
||||
document_id=created.id,
|
||||
person_id=parsed_author_id,
|
||||
role=DocumentPersonRole.AUTHOR,
|
||||
)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Author link failed", operation="documents.create.link_author")
|
||||
return
|
||||
|
||||
ui.notify("Document created", type="positive")
|
||||
if return_to == "jobs_new":
|
||||
ui.navigate.to(f"/jobs/new?document_id={created.id}")
|
||||
return
|
||||
ui.navigate.to(f"/documents/{created.id}")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
ui.button("Save document", on_click=submit_create, icon="save").classes("ui-btn-primary")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to("/documents"), icon="arrow_back").props("flat")
|
||||
|
||||
@ui.page("/documents")
|
||||
async def documents_page(session_factory: SessionFactoryDep) -> None:
|
||||
document_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/documents")
|
||||
|
||||
with ui.column().classes("w-full max-w-7xl mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header("Archival Documents")
|
||||
ui.button(
|
||||
"Create new document",
|
||||
on_click=lambda: ui.navigate.to("/documents/new"),
|
||||
icon="note_add",
|
||||
).classes("ui-btn-primary")
|
||||
|
||||
try:
|
||||
documents = sorted(
|
||||
await document_service.list_documents(),
|
||||
key=lambda item: item.created_at,
|
||||
reverse=True,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="documents.list")
|
||||
return
|
||||
|
||||
rows = [
|
||||
DocumentTableRow(
|
||||
id=doc.id,
|
||||
name=doc.name,
|
||||
document_type=doc.document_type or "",
|
||||
archive_identifier=doc.archive_identifier or "",
|
||||
created_at=doc.created_at.strftime("%b %d, %Y"),
|
||||
)
|
||||
for doc in documents
|
||||
]
|
||||
render_documents_table(rows)
|
||||
|
||||
@ui.page("/documents/{document_id}")
|
||||
async def document_detail_page(document_id: str, session_factory: SessionFactoryDep) -> None:
|
||||
document_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/documents")
|
||||
|
||||
parsed_doc_id = _parse_uuid(document_id)
|
||||
if parsed_doc_id is None:
|
||||
ui.label("Invalid document id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
document = await document_service.read_document_detail(document_id=parsed_doc_id)
|
||||
except DocumentError:
|
||||
ui.label("Document not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="documents.read")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-[1800px] mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header(document.name, subtitle=f"Type: {document.document_type or 'Unspecified'} | ID: {document.id}")
|
||||
|
||||
with ui.row().classes("items-center gap-2"):
|
||||
ui.button(
|
||||
"Edit Document",
|
||||
on_click=lambda: ui.navigate.to(f"/documents/{document.id}/edit"),
|
||||
icon="edit",
|
||||
).classes("ui-btn-primary text-xs")
|
||||
destructive_button(
|
||||
"Delete",
|
||||
on_click=lambda: ui.navigate.to(f"/documents/{document.id}/delete"),
|
||||
icon="delete",
|
||||
extra_classes="text-xs",
|
||||
)
|
||||
|
||||
with ui.grid().classes("w-full grid-cols-12 gap-4"):
|
||||
_render_bento_viewer_zone(document)
|
||||
_render_bento_metadata_zone(document)
|
||||
_render_bento_relations_zone(document)
|
||||
|
||||
@ui.page("/documents/{document_id}/jobs")
|
||||
async def document_jobs_page(document_id: str, session_factory: SessionFactoryDep) -> None:
|
||||
document_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/documents")
|
||||
|
||||
parsed_doc_id = _parse_uuid(document_id)
|
||||
if parsed_doc_id is None:
|
||||
ui.label("Invalid document id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
document = await document_service.read_document_detail(document_id=parsed_doc_id)
|
||||
except DocumentError:
|
||||
ui.label("Document not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="documents.jobs")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-4xl mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header(f"Jobs for {document.name}")
|
||||
with ui.row().classes("gap-2"):
|
||||
ui.button("Back to Document", on_click=lambda: ui.navigate.to(f"/documents/{document.id}"), icon="arrow_back").props("flat")
|
||||
ui.button("Create Job", on_click=lambda: ui.navigate.to(f"/jobs/new?document_id={document.id}"), icon="add").classes("ui-btn-primary")
|
||||
|
||||
if not document.jobs:
|
||||
with archival_card(extra_classes="p-6 text-center"):
|
||||
render_empty_state("No transcription processing jobs created yet.")
|
||||
return
|
||||
|
||||
for job in sorted(document.jobs, key=lambda item: item.date_created, reverse=True):
|
||||
with archival_card(extra_classes="p-3"):
|
||||
with ui.row().classes("w-full items-center justify-between"):
|
||||
with ui.row().classes("items-center gap-2"):
|
||||
archival_badge(job.status.value)
|
||||
ui.label(f"Job ID: {job.id}").classes("text-xs font-mono ui-text-primary")
|
||||
ui.button("Open Job", on_click=lambda _=None, jid=job.id: ui.navigate.to(f"/jobs/{jid}"), icon="open_in_new").props("flat dense").classes("text-xs ui-link-primary")
|
||||
|
||||
@ui.page("/documents/{document_id}/sources")
|
||||
async def document_sources_page(document_id: str, session_factory: SessionFactoryDep) -> RedirectResponse:
|
||||
_ = session_factory
|
||||
return RedirectResponse(url=f"/sources?document_id={document_id}")
|
||||
|
||||
@ui.page("/documents/{document_id}/edit")
|
||||
async def document_edit_page(document_id: str, session_factory: SessionFactoryDep) -> None:
|
||||
document_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/documents")
|
||||
|
||||
parsed_doc_id = _parse_uuid(document_id)
|
||||
if parsed_doc_id is None:
|
||||
ui.label("Invalid document id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
document = await document_service.read_document_detail(document_id=parsed_doc_id)
|
||||
except DocumentError:
|
||||
ui.label("Document not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="documents.edit.read")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-4xl mx-auto p-4 gap-4"):
|
||||
page_header("Edit Document Record", subtitle="Document name and document type are required.")
|
||||
|
||||
people = sorted(await document_service.list_people(), key=lambda item: item.full_name.casefold())
|
||||
existing_author = next((link for link in document.document_people if link.role == DocumentPersonRole.AUTHOR), None)
|
||||
form = _render_document_form_fields(document=document, people=people, existing_author_id=existing_author.person_id if existing_author else None)
|
||||
|
||||
async def submit_edit() -> None:
|
||||
candidate_name = (form["name"].value or "").strip()
|
||||
candidate_type = (form["type"].value or "").strip()
|
||||
if not candidate_name:
|
||||
ui.notify("Document name is required.", type="warning")
|
||||
return
|
||||
if not candidate_type:
|
||||
ui.notify("Document type is required.", type="warning")
|
||||
return
|
||||
|
||||
parsed_date = _parse_iso_date(form["date"].value)
|
||||
if form["date"].value and parsed_date is None:
|
||||
ui.notify("Exact date must use YYYY-MM-DD.", type="warning")
|
||||
return
|
||||
|
||||
candidate = Document(
|
||||
id=document.id,
|
||||
name=candidate_name,
|
||||
document_type=candidate_type,
|
||||
document_date=parsed_date,
|
||||
document_date_raw=(form["date_raw"].value or "").strip() or None,
|
||||
location_created=(form["location"].value or "").strip() or None,
|
||||
notes=(form["notes"].value or "").strip() or None,
|
||||
archive_identifier=(form["archive"].value or "").strip() or None,
|
||||
created_at=document.created_at,
|
||||
updated_at=document.updated_at,
|
||||
)
|
||||
|
||||
try:
|
||||
await document_service.update_document(candidate)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Save failed", operation="documents.edit.save")
|
||||
return
|
||||
|
||||
selected_author = (form["author"].value or "").strip()
|
||||
if selected_author == CREATE_NEW_PERSON_OPTION:
|
||||
ui.navigate.to("/people/new")
|
||||
return
|
||||
|
||||
existing_author_links = [link for link in document.document_people if link.role == DocumentPersonRole.AUTHOR]
|
||||
try:
|
||||
if not selected_author:
|
||||
for link in existing_author_links:
|
||||
await document_service.delete_document_person(link)
|
||||
else:
|
||||
selected_author_id = UUID(selected_author)
|
||||
if not any(link.person_id == selected_author_id for link in existing_author_links):
|
||||
for link in existing_author_links:
|
||||
await document_service.delete_document_person(link)
|
||||
await document_service.create_document_person(
|
||||
DocumentPerson(document_id=document.id, person_id=selected_author_id, role=DocumentPersonRole.AUTHOR)
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Author update failed", operation="documents.edit.link_author")
|
||||
return
|
||||
|
||||
ui.notify("Document updated", type="positive")
|
||||
ui.navigate.to(f"/documents/{document.id}")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
ui.button("Save changes", on_click=submit_edit, icon="save").classes("ui-btn-primary")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to(f"/documents/{document.id}"), icon="arrow_back").props("flat")
|
||||
|
||||
@ui.page("/documents/{document_id}/delete")
|
||||
async def document_delete_page(document_id: str, session_factory: SessionFactoryDep) -> None:
|
||||
document_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/documents")
|
||||
|
||||
parsed_doc_id = _parse_uuid(document_id)
|
||||
if parsed_doc_id is None:
|
||||
ui.label("Invalid document id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
document = await document_service.read_document_detail(document_id=parsed_doc_id)
|
||||
except DocumentError:
|
||||
ui.label("Document not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="documents.delete.read")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-xl mx-auto p-4 gap-4"):
|
||||
page_header("Delete Document")
|
||||
|
||||
with archival_card(extra_classes="gap-2"):
|
||||
ui.label(f"Document: {document.name}").classes("text-sm font-semibold ui-text-primary")
|
||||
|
||||
if document.sources or document.jobs:
|
||||
ui.label("Delete is blocked because related records exist.").classes("text-xs ui-text-danger font-bold mt-2")
|
||||
deps = [cat for cat, present in [("Sources", bool(document.sources)), ("Jobs", bool(document.jobs))] if present]
|
||||
ui.label(f"Dependencies present: {', '.join(deps)}").classes("text-xs ui-text-muted")
|
||||
ui.label("Remove related records first, then retry deletion.").classes("text-xs ui-text-muted italic")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-4"):
|
||||
ui.button("Back to Document", on_click=lambda: ui.navigate.to(f"/documents/{document.id}"), icon="arrow_back").classes("ui-btn-primary text-xs")
|
||||
ui.button("Go to Jobs", on_click=lambda: ui.navigate.to("/jobs"), icon="work_history").props("flat text-xs")
|
||||
return
|
||||
|
||||
ui.label("This action permanently deletes the document.").classes("text-xs ui-text-danger font-medium")
|
||||
|
||||
async def submit_delete() -> None:
|
||||
try:
|
||||
await document_service.delete_document(document)
|
||||
except DocumentDeleteBlockedError as exc:
|
||||
ui.notify(exc.message, type="warning")
|
||||
ui.navigate.to(f"/documents/{document.id}/delete")
|
||||
return
|
||||
except DocumentError as exc:
|
||||
if exc.category == ErrorCategory.NOT_FOUND:
|
||||
ui.notify("Document not found.", type="warning")
|
||||
ui.navigate.to("/documents")
|
||||
return
|
||||
show_error(exc, title="Delete failed", operation="documents.delete")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Delete failed", operation="documents.delete")
|
||||
return
|
||||
|
||||
ui.notify("Document deleted", type="positive")
|
||||
ui.navigate.to("/documents")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
destructive_button("Delete document permanently", on_click=submit_delete, icon="delete_forever", variant="solid")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to(f"/documents/{document.id}"), icon="arrow_back").props("flat")
|
||||
|
||||
|
||||
# --- Helper Sub-Components ---
|
||||
|
||||
|
||||
def _render_document_form_fields(
|
||||
*, document: Document | None = None, people: list[Any], existing_author_id: UUID | None = None
|
||||
) -> dict[str, Any]:
|
||||
with archival_card(extra_classes="gap-3"):
|
||||
name_input = ui.input(label="Document name", value=document.name if document else "").props("outlined").classes("w-full ui-form-surface")
|
||||
type_input = ui.input(label="Document type", value=document.document_type if document and document.document_type else "").props("outlined").classes("w-full ui-form-surface")
|
||||
|
||||
with ui.row().classes("w-full gap-3 grid grid-cols-1 md:grid-cols-2"):
|
||||
date_input = ui.input(
|
||||
label="Exact date (YYYY-MM-DD)",
|
||||
value=document.document_date.isoformat() if document and document.document_date else "",
|
||||
).props('outlined type="date"').classes("ui-form-surface")
|
||||
date_raw_input = ui.input(label="Approximate date", value=document.document_date_raw if document and document.document_date_raw else "").props("outlined").classes("ui-form-surface")
|
||||
|
||||
location_input = ui.input(label="Document location", value=document.location_created if document and document.location_created else "").props("outlined").classes("w-full ui-form-surface")
|
||||
archive_input = ui.input(label="Archive identifier", value=document.archive_identifier if document and document.archive_identifier else "").props("outlined").classes("w-full ui-form-surface")
|
||||
notes_input = ui.textarea(label="Notes", value=document.notes if document and document.notes else "").props("outlined autogrow").classes("w-full ui-form-surface")
|
||||
|
||||
author_options = {"": "No author", CREATE_NEW_PERSON_OPTION: "Create new item"} | {str(p.id): p.full_name for p in people}
|
||||
author_select = ui.select(author_options, label="Author (Person)", value=str(existing_author_id) if existing_author_id else "").props("outlined").classes("w-full ui-form-surface")
|
||||
|
||||
return {
|
||||
"name": name_input,
|
||||
"type": type_input,
|
||||
"date": date_input,
|
||||
"date_raw": date_raw_input,
|
||||
"location": location_input,
|
||||
"archive": archive_input,
|
||||
"notes": notes_input,
|
||||
"author": author_select,
|
||||
}
|
||||
|
||||
|
||||
def _render_bento_viewer_zone(document: Document) -> None:
|
||||
with ui.column().classes("col-span-12 lg:col-span-4"):
|
||||
source_path = document.sources[0].file_path if document.sources else None
|
||||
dark_room_viewer(source_path, count_label=f"{len(document.sources)} Source(s) Linked")
|
||||
with ui.row().classes("w-full justify-between items-center mt-2"):
|
||||
ui.button("View All Sources", on_click=lambda: ui.navigate.to(f"/sources?document_id={document.id}"), icon="description").props("flat dense text-xs").classes("ui-link-primary")
|
||||
ui.button("+ Add Source", on_click=lambda: ui.navigate.to(f"/jobs/new?document_id={document.id}"), icon="add").classes("ui-btn-primary text-xs")
|
||||
|
||||
|
||||
def _render_bento_metadata_zone(document: Document) -> None:
|
||||
author_link = next((item for item in document.document_people if item.role == DocumentPersonRole.AUTHOR and item.person is not None), None)
|
||||
|
||||
with ui.column().classes("col-span-12 lg:col-span-4 gap-4"):
|
||||
with archival_card(title="Archival Metadata"):
|
||||
metadata_row("Author:", author_link.person.full_name if author_link and author_link.person else "Not set")
|
||||
metadata_row("Exact Date:", document.document_date.isoformat() if document.document_date else "Not set")
|
||||
metadata_row("Approx. Date:", document.document_date_raw or "Not set")
|
||||
metadata_row("Location Created:", document.location_created or "Not set")
|
||||
metadata_row("Archive Identifier:", document.archive_identifier or "Not set")
|
||||
|
||||
with ui.column().classes("w-full mt-2"):
|
||||
ui.label("Archival Notes:").classes("ui-text-muted text-xs mb-1")
|
||||
ui.label(document.notes or "No notes added.").classes("p-2 ui-note-box text-xs")
|
||||
|
||||
with archival_card(title="System Logistics"):
|
||||
ui.label(f"Created: {document.created_at.isoformat()}").classes("text-[11px] ui-text-muted")
|
||||
ui.label(f"Updated: {document.updated_at.isoformat()}").classes("text-[11px] ui-text-muted")
|
||||
|
||||
|
||||
def _render_bento_relations_zone(document: Document) -> None:
|
||||
with ui.column().classes("col-span-12 lg:col-span-4 gap-4"):
|
||||
with archival_card(title="Related People"):
|
||||
if not document.document_people:
|
||||
render_empty_state("No linked people yet.", italic=True)
|
||||
else:
|
||||
with ui.column().classes("w-full gap-2"):
|
||||
for link in document.document_people:
|
||||
person_label = link.person.full_name if link.person is not None else "Unknown person"
|
||||
with ui.row().classes("w-full justify-between items-center ui-row-surface p-2"):
|
||||
ui.label(person_label).classes("text-xs font-semibold ui-text-primary")
|
||||
archival_badge(link.role.value)
|
||||
|
||||
with archival_card(title="Pipeline Jobs"):
|
||||
with ui.row().classes("w-full justify-between items-center mb-2"):
|
||||
ui.label(f"{len(document.jobs)} Active Jobs").classes("text-xs ui-link-primary font-bold")
|
||||
|
||||
with ui.row().classes("w-full gap-2 mt-2"):
|
||||
ui.button("View Jobs", on_click=lambda: ui.navigate.to(f"/documents/{document.id}/jobs"), icon="work_history").props("flat dense text-xs").classes("ui-link-primary")
|
||||
ui.button("+ Add Job", on_click=lambda: ui.navigate.to(f"/jobs/new?document_id={document.id}"), icon="add").classes("ui-btn-primary text-xs")
|
||||
|
||||
|
||||
def _parse_uuid(value: str | None) -> UUID | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_iso_date(value: str | None) -> date | None:
|
||||
candidate = (value or "").strip()
|
||||
if not candidate:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(candidate)
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Homepage registration and handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.ui.components.app_shell import render_navigation_header
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.primitives import render_empty_state
|
||||
from transcription.ui.components.primitives import section_header_row
|
||||
from transcription.ui.components.viewers import dark_room_viewer
|
||||
from transcription.ui.homepage_store import latest_homepage_image
|
||||
from transcription.ui.homepage_store import read_homepage_markdown
|
||||
from transcription.ui.homepage_store import save_homepage_markdown
|
||||
from transcription.ui.homepage_store import store_homepage_image
|
||||
from transcription.ui.theme import page_header
|
||||
|
||||
|
||||
def _render_homepage_view(*, markdown_text: str, image_path) -> None:
|
||||
with ui.grid().classes("w-full grid-cols-12 gap-4"):
|
||||
with ui.column().classes("col-span-12 lg:col-span-4"):
|
||||
dark_room_viewer(str(image_path) if image_path else None, count_label="Homepage Image")
|
||||
|
||||
with ui.column().classes("col-span-12 lg:col-span-5 gap-4"), archival_card(title="Home Text"):
|
||||
if markdown_text:
|
||||
ui.markdown(markdown_text)
|
||||
else:
|
||||
render_empty_state("No homepage text saved yet.")
|
||||
|
||||
with ui.column().classes("col-span-12 lg:col-span-3"):
|
||||
ui.element("div")
|
||||
|
||||
|
||||
def _render_homepage_editor(*, render_image_panel, markdown_input, on_upload) -> None:
|
||||
with ui.grid().classes("w-full grid-cols-12 gap-4"):
|
||||
with ui.column().classes("col-span-12 lg:col-span-4 gap-4"):
|
||||
with archival_card(title="Homepage Image"):
|
||||
ui.upload(on_upload=on_upload, auto_upload=True, label="Upload image").props(
|
||||
'accept=".jpg,.jpeg,.png,.gif,.webp,.bmp,.tif,.tiff"'
|
||||
).classes("w-full")
|
||||
render_image_panel()
|
||||
|
||||
with ui.column().classes("col-span-12 lg:col-span-5 gap-4"), archival_card(title="Home Text"):
|
||||
markdown_input[0] = ui.textarea(
|
||||
label="Homepage markdown",
|
||||
value=read_homepage_markdown(),
|
||||
).props("outlined autogrow").classes("w-full")
|
||||
|
||||
with ui.column().classes("col-span-12 lg:col-span-3"):
|
||||
ui.element("div")
|
||||
|
||||
|
||||
def register_page() -> None:
|
||||
"""Register the homepage routes."""
|
||||
|
||||
@ui.page("/homepage", title="VibeScribe Home")
|
||||
def homepage_page() -> None:
|
||||
render_navigation_header(current_path="/homepage")
|
||||
|
||||
with ui.column().classes("w-full max-w-[1800px] mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header("Home")
|
||||
ui.button(
|
||||
"Edit Home Page",
|
||||
on_click=lambda: ui.navigate.to("/homepage/edit"),
|
||||
icon="edit",
|
||||
).classes("ui-btn-primary text-xs")
|
||||
|
||||
_render_homepage_view(
|
||||
markdown_text=read_homepage_markdown().strip(),
|
||||
image_path=latest_homepage_image(),
|
||||
)
|
||||
|
||||
@ui.page("/homepage/edit", title="Edit Homepage")
|
||||
def homepage_edit_page() -> None:
|
||||
render_navigation_header(current_path="/homepage")
|
||||
|
||||
preview_image = [latest_homepage_image()]
|
||||
markdown_input = [None]
|
||||
|
||||
@ui.refreshable
|
||||
def render_image_panel() -> None:
|
||||
dark_room_viewer(str(preview_image[0]) if preview_image[0] else None, count_label="Homepage Image")
|
||||
|
||||
async def on_upload(event) -> None:
|
||||
payload = await event.file.read()
|
||||
preview_image[0] = store_homepage_image(filename=event.file.name, file_bytes=payload)
|
||||
ui.notify(f"Uploaded {event.file.name}", type="positive")
|
||||
render_image_panel.refresh()
|
||||
|
||||
async def save_homepage() -> None:
|
||||
save_homepage_markdown((markdown_input[0].value if markdown_input[0] is not None else "") or "")
|
||||
ui.notify("Homepage saved", type="positive")
|
||||
ui.navigate.to("/homepage")
|
||||
|
||||
with ui.column().classes("w-full max-w-[1800px] mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header("Edit Home Page")
|
||||
with ui.row().classes("items-center gap-2"):
|
||||
ui.button("Save", on_click=save_homepage, icon="save").classes("ui-btn-primary text-xs")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to("/homepage"), icon="close").props("flat")
|
||||
|
||||
_render_homepage_editor(
|
||||
render_image_panel=render_image_panel,
|
||||
markdown_input=markdown_input,
|
||||
on_upload=on_upload,
|
||||
)
|
||||
@@ -2,161 +2,452 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Request
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.app_state import resolve_session_factory
|
||||
from transcription.models import Job
|
||||
from transcription.models import JobStatus
|
||||
from transcription.models import Source
|
||||
from transcription.services.jobs import JobService
|
||||
from transcription.services.transcription import TranscriptionService
|
||||
from transcription.db.models import Job, JobSourceStatus, JobStatus
|
||||
from transcription.db.session import session_scope
|
||||
from transcription.services.documents import DocumentService
|
||||
from transcription.services.jobs import (
|
||||
JobCancelBlockedError,
|
||||
JobDeleteBlockedError,
|
||||
JobResubmitBlockedError,
|
||||
JobService,
|
||||
)
|
||||
from transcription.services.store import create_job_for_document
|
||||
from transcription.ui.components.app_shell import render_navigation_header
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.data_display import archival_badge, metadata_row
|
||||
from transcription.ui.components.error_presenter import show_error
|
||||
from transcription.ui.components.table.jobs import render_jobs_table
|
||||
from transcription.ui.components.primitives import (
|
||||
destructive_button,
|
||||
render_empty_state,
|
||||
section_header_row,
|
||||
)
|
||||
from transcription.ui.components.table.jobs import JobTableRow, render_jobs_table
|
||||
from transcription.ui.theme import page_header
|
||||
from transcription.worker import resolve_worker_notifier
|
||||
|
||||
from ..components.document_panzoom import render_document_panzoom
|
||||
from ..components.table.jobs import JobTableRow
|
||||
from ..components.transcript import render_original_transcription_card
|
||||
from ..components.transcript import render_revision_row
|
||||
from ...db.session import SessionFactoryDep
|
||||
|
||||
|
||||
def register_page() -> None: # noqa: PLR0915
|
||||
"""Register jobs list and detail routes."""
|
||||
|
||||
@ui.page("/jobs")
|
||||
async def jobs_page(request: Request) -> None:
|
||||
session_factory = resolve_session_factory(request.app.state)
|
||||
async def jobs_page(session_factory: SessionFactoryDep) -> None:
|
||||
jobs_service = JobService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/jobs")
|
||||
|
||||
@ui.refreshable
|
||||
async def render_table() -> None:
|
||||
jobs = [
|
||||
JobTableRow(
|
||||
id=job.id,
|
||||
status=job.status.value,
|
||||
filename=job.filename,
|
||||
retry_count=job.retry_count,
|
||||
date_created=job.date_created.isoformat(),
|
||||
date_updated=job.date_updated.isoformat(),
|
||||
)
|
||||
for job in await jobs_service.list_jobs()
|
||||
]
|
||||
render_jobs_table(jobs)
|
||||
with ui.column().classes("w-full max-w-7xl mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header("Transcription Pipeline Jobs")
|
||||
with ui.row().classes("items-center gap-2"):
|
||||
ui.button("Create job", on_click=lambda: ui.navigate.to("/jobs/new"), icon="add").classes(
|
||||
"ui-btn-primary"
|
||||
)
|
||||
ui.button("Refresh", on_click=lambda: render_table.refresh(), icon="refresh").props("flat")
|
||||
|
||||
ui.button("Refresh", on_click=render_table.refresh, icon="refresh")
|
||||
await render_table()
|
||||
@ui.refreshable
|
||||
async def render_table() -> None:
|
||||
jobs = [
|
||||
JobTableRow(
|
||||
id=job.id,
|
||||
status=job.status.value,
|
||||
filename=job.filename,
|
||||
retry_count=job.retry_count,
|
||||
date_created=job.date_created.isoformat(),
|
||||
date_updated=job.date_updated.isoformat(),
|
||||
)
|
||||
for job in await jobs_service.list_jobs()
|
||||
]
|
||||
render_jobs_table(jobs)
|
||||
|
||||
await render_table()
|
||||
|
||||
@ui.page("/jobs/new")
|
||||
async def job_create_page(request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
documents_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/jobs")
|
||||
|
||||
with ui.column().classes("w-full max-w-4xl mx-auto p-4 gap-4"):
|
||||
page_header("Create Processing Job", subtitle="Queue source files for AI transcription and entity processing.")
|
||||
|
||||
documents = await documents_service.list_documents()
|
||||
if not documents:
|
||||
_render_no_documents_card()
|
||||
return
|
||||
|
||||
uploaded_files: list[tuple[str, bytes]] = []
|
||||
|
||||
with archival_card(extra_classes="gap-3"):
|
||||
document_options = {str(doc.id): doc.name for doc in documents}
|
||||
document_select = ui.select(document_options, label="Target Document").props("outlined").classes("w-full ui-form-surface")
|
||||
|
||||
requested_document_id = request.query_params.get("document_id")
|
||||
if requested_document_id in document_options:
|
||||
document_select.value = requested_document_id
|
||||
|
||||
with ui.row().classes("w-full gap-3 grid grid-cols-1 md:grid-cols-2"):
|
||||
provider_input = ui.input(label="Provider").props("outlined").classes("ui-form-surface")
|
||||
model_input = ui.input(label="Model").props("outlined").classes("ui-form-surface")
|
||||
|
||||
_render_upload_section(uploaded_files)
|
||||
|
||||
async def submit_create() -> None:
|
||||
if not document_select.value:
|
||||
ui.notify("Document is required.", type="warning")
|
||||
return
|
||||
if not uploaded_files:
|
||||
ui.notify("At least one source file is required.", type="warning")
|
||||
return
|
||||
|
||||
try:
|
||||
document_id = UUID(str(document_select.value))
|
||||
except ValueError:
|
||||
ui.notify("Selected document id is invalid.", type="warning")
|
||||
return
|
||||
|
||||
try:
|
||||
async with session_scope(session_factory=session_factory) as session:
|
||||
result = await create_job_for_document(
|
||||
document_id=document_id,
|
||||
uploads=uploaded_files,
|
||||
provider=(provider_input.value or None),
|
||||
model=(model_input.value or None),
|
||||
session=session,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Create job failed", operation="jobs.create")
|
||||
return
|
||||
|
||||
resolve_worker_notifier(request.app.state).notify()
|
||||
ui.notify(f"Created job {result.job_id}", type="positive")
|
||||
ui.navigate.to(f"/jobs/{result.job_id}")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
ui.button("Submit for transcription", on_click=submit_create, icon="play_arrow").classes("ui-btn-primary")
|
||||
ui.button("Back to Jobs", on_click=lambda: ui.navigate.to("/jobs"), icon="arrow_back").props("flat")
|
||||
|
||||
@ui.page("/jobs/{job_id}")
|
||||
async def job_detail_page(job_id: str, request: Request) -> None: # noqa: PLR0915
|
||||
session_factory = resolve_session_factory(request.app.state)
|
||||
async def job_detail_page(job_id: str, request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
jobs_service = JobService(session_factory=session_factory)
|
||||
transcription_service = TranscriptionService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/jobs")
|
||||
|
||||
try:
|
||||
parsed_job_id = UUID(job_id)
|
||||
except ValueError:
|
||||
ui.label("Invalid job id").classes("text-h6 text-negative")
|
||||
parsed_job_id = _parse_uuid(job_id)
|
||||
if parsed_job_id is None:
|
||||
ui.label("Invalid job id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
job = await jobs_service.read_job(job_id=parsed_job_id)
|
||||
except ValueError:
|
||||
ui.label("Job not found").classes("text-h6 text-negative")
|
||||
ui.label("Job not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
source = _resolve_primary_source(job)
|
||||
with ui.column().classes("w-full max-w-4xl mx-auto p-4 gap-4"):
|
||||
_render_job_detail_header(job)
|
||||
|
||||
with ui.splitter(value=30).classes("w-full h-[calc(100vh-64px)]") as splitter:
|
||||
with splitter.before, ui.column(align_items="stretch").classes("w-full h-full p-4 gap-3"):
|
||||
if source is not None:
|
||||
render_document_panzoom(source=source)
|
||||
else:
|
||||
ui.label("No source preview is available for this job.").classes("text-body2 text-grey-3")
|
||||
with splitter.after, ui.column(align_items="stretch").classes("w-full h-full p-4 gap-3"):
|
||||
with ui.row():
|
||||
ui.button(icon="arrow_back", on_click=ui.navigate.back)
|
||||
with ui.row().classes("w-full items-center justify-between"):
|
||||
ui.label(f"{job.id}").classes("text-h6 text-weight-bold")
|
||||
match job.status:
|
||||
case JobStatus.TRANSCRIBED:
|
||||
ui.chip(job.status.value.upper(), color="green", text_color="white").props("outline")
|
||||
case _:
|
||||
ui.label(f"{job.status.value}").classes("text-subtitle1 text-weight-medium")
|
||||
with ui.grid().classes("w-full grid-cols-1 md:grid-cols-2 gap-4"):
|
||||
_render_job_logistics(job)
|
||||
_render_job_document_links(job)
|
||||
|
||||
render_original_transcription_card(job=job)
|
||||
@ui.page("/jobs/{job_id}/cancel")
|
||||
async def job_cancel_page(job_id: str, request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
jobs_service = JobService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/jobs")
|
||||
|
||||
async def delete_revision_by_id(revision_id: UUID) -> None:
|
||||
try:
|
||||
revision = await transcription_service.read_revision(revision_id=revision_id)
|
||||
await transcription_service.delete_revision(revision)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Delete failed", operation="jobs.delete_revision")
|
||||
return
|
||||
parsed_job_id = _parse_uuid(job_id)
|
||||
if parsed_job_id is None:
|
||||
ui.label("Invalid job id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
ui.notify("Deleted revision", type="positive")
|
||||
await render_revision_panel.refresh()
|
||||
try:
|
||||
job = await jobs_service.read_job(job_id=parsed_job_id)
|
||||
except ValueError:
|
||||
ui.label("Job not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
@ui.refreshable
|
||||
async def render_revision_panel() -> None:
|
||||
refreshed_job = await jobs_service.read_job(job_id=parsed_job_id)
|
||||
refreshed_source = _resolve_primary_source(refreshed_job)
|
||||
if refreshed_source is None:
|
||||
ui.label("No source is available for revision editing.").classes("text-body2 text-grey-3")
|
||||
return
|
||||
with ui.column().classes("w-full max-w-xl mx-auto p-4 gap-4"):
|
||||
page_header("Cancel Processing Job")
|
||||
|
||||
current_revision = refreshed_source.revision
|
||||
default_revision_text = (
|
||||
current_revision.text if current_revision is not None else (refreshed_job.text or "")
|
||||
with archival_card(extra_classes="gap-2"):
|
||||
ui.label(f"Job ID: {job.id}").classes("text-sm font-semibold font-mono ui-text-primary")
|
||||
metadata_row("Current Status:", job.status.value)
|
||||
ui.label("Cancel stops processing and marks remaining non-transcribed sources as failed.").classes(
|
||||
"text-xs ui-text-muted"
|
||||
)
|
||||
|
||||
async def submit_cancel() -> None:
|
||||
try:
|
||||
await jobs_service.cancel_job(job_id=job.id)
|
||||
except JobCancelBlockedError as exc:
|
||||
ui.notify(exc.message, type="warning")
|
||||
return
|
||||
except ValueError:
|
||||
ui.notify("Job not found.", type="warning")
|
||||
ui.navigate.to("/jobs")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Cancel job failed", operation="jobs.cancel")
|
||||
return
|
||||
|
||||
resolve_worker_notifier(request.app.state).notify()
|
||||
ui.notify("Job cancelled", type="positive")
|
||||
ui.navigate.to(f"/jobs/{job.id}")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
destructive_button("Cancel job", on_click=submit_cancel, icon="stop_circle", variant="solid")
|
||||
ui.button("Back to Job", on_click=lambda: ui.navigate.to(f"/jobs/{job.id}"), icon="arrow_back").props("flat")
|
||||
|
||||
@ui.page("/jobs/{job_id}/resubmit")
|
||||
async def job_resubmit_page(job_id: str, request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
jobs_service = JobService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/jobs")
|
||||
|
||||
parsed_job_id = _parse_uuid(job_id)
|
||||
if parsed_job_id is None:
|
||||
ui.label("Invalid job id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
job = await jobs_service.read_job(job_id=parsed_job_id)
|
||||
except ValueError:
|
||||
ui.label("Job not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
failed_count = sum(1 for js in job.job_sources if js.status == JobSourceStatus.FAILED)
|
||||
|
||||
with ui.column().classes("w-full max-w-xl mx-auto p-4 gap-4"):
|
||||
page_header("Resubmit Job")
|
||||
|
||||
with archival_card(extra_classes="gap-2"):
|
||||
ui.label(f"Job ID: {job.id}").classes("text-sm font-semibold font-mono ui-text-primary")
|
||||
metadata_row("Current Status:", job.status.value)
|
||||
metadata_row("Failed Sources:", str(failed_count))
|
||||
ui.label(
|
||||
"Resubmit queues only failed linked sources. New results overwrite prior page-level results."
|
||||
).classes("text-xs ui-text-muted")
|
||||
|
||||
async def submit_resubmit() -> None:
|
||||
try:
|
||||
resubmitted_count = await jobs_service.resubmit_failed_sources(job_id=job.id)
|
||||
except JobResubmitBlockedError as exc:
|
||||
ui.notify(exc.message, type="warning")
|
||||
return
|
||||
except ValueError:
|
||||
ui.notify("Job not found.", type="warning")
|
||||
ui.navigate.to("/jobs")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Resubmit failed", operation="jobs.resubmit")
|
||||
return
|
||||
|
||||
resolve_worker_notifier(request.app.state).notify()
|
||||
ui.notify(f"Resubmitted {resubmitted_count} source(s)", type="positive")
|
||||
ui.navigate.to(f"/jobs/{job.id}")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
ui.button("Resubmit now", on_click=submit_resubmit, icon="replay").classes("ui-btn-primary")
|
||||
ui.button("Back to Job", on_click=lambda: ui.navigate.to(f"/jobs/{job.id}"), icon="arrow_back").props("flat")
|
||||
|
||||
@ui.page("/jobs/{job_id}/delete")
|
||||
async def job_delete_page(job_id: str, session_factory: SessionFactoryDep) -> None:
|
||||
jobs_service = JobService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/jobs")
|
||||
|
||||
parsed_job_id = _parse_uuid(job_id)
|
||||
if parsed_job_id is None:
|
||||
ui.label("Invalid job id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
job = await jobs_service.read_job(job_id=parsed_job_id)
|
||||
except ValueError:
|
||||
ui.label("Job not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-xl mx-auto p-4 gap-4"):
|
||||
page_header("Delete Processing Job")
|
||||
|
||||
with archival_card(extra_classes="gap-2"):
|
||||
ui.label(f"Job ID: {job.id}").classes("text-sm font-semibold font-mono ui-text-primary")
|
||||
|
||||
if job.status == JobStatus.PROCESSING:
|
||||
ui.label("Delete is blocked while the job is processing.").classes("text-xs ui-text-danger font-bold mt-2")
|
||||
ui.label("Wait for processing to complete, then retry delete.").classes("text-xs ui-text-muted italic")
|
||||
with ui.row().classes("w-full items-center gap-2 mt-4"):
|
||||
ui.button("Back to Job", on_click=lambda: ui.navigate.to(f"/jobs/{job.id}"), icon="arrow_back").classes(
|
||||
"ui-btn-primary text-xs"
|
||||
)
|
||||
ui.button("Back to Jobs", on_click=lambda: ui.navigate.to("/jobs"), icon="work_history").props(
|
||||
"flat text-xs"
|
||||
)
|
||||
return
|
||||
|
||||
ui.label("This action permanently deletes the job.").classes("text-xs ui-text-danger font-medium")
|
||||
if job.job_sources:
|
||||
ui.label("Related JobSource links will be removed as part of delete.").classes("text-xs ui-text-muted")
|
||||
|
||||
async def submit_delete() -> None:
|
||||
try:
|
||||
await jobs_service.delete_job_with_guardrails(job_id=job.id)
|
||||
except JobDeleteBlockedError as exc:
|
||||
ui.notify(exc.message, type="warning")
|
||||
return
|
||||
except ValueError:
|
||||
ui.notify("Job not found.", type="warning")
|
||||
ui.navigate.to("/jobs")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Delete job failed", operation="jobs.delete")
|
||||
return
|
||||
|
||||
ui.notify("Job deleted", type="positive")
|
||||
ui.navigate.to("/jobs")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
destructive_button("Delete job permanently", on_click=submit_delete, icon="delete_forever", variant="solid")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to(f"/jobs/{job.id}"), icon="arrow_back").props("flat")
|
||||
|
||||
|
||||
# --- Helper Sub-Components ---
|
||||
|
||||
|
||||
def _render_no_documents_card() -> None:
|
||||
with archival_card(extra_classes="p-6 text-center"):
|
||||
render_empty_state(
|
||||
"No documents available. Create a Document before creating a Job.",
|
||||
extra_classes="ui-text-danger font-medium mb-4",
|
||||
)
|
||||
with ui.row().classes("justify-center gap-2"):
|
||||
ui.button(
|
||||
"Create document",
|
||||
on_click=lambda: ui.navigate.to("/documents/new?return_to=jobs_new"),
|
||||
icon="note_add",
|
||||
).classes("ui-btn-primary")
|
||||
ui.button("Back to Jobs", on_click=lambda: ui.navigate.to("/jobs"), icon="arrow_back").props("flat")
|
||||
|
||||
|
||||
def _render_upload_section(uploaded_files: list[tuple[str, bytes]]) -> None:
|
||||
with archival_card(title="Source Files"):
|
||||
ui.label(
|
||||
"Files are processed alphabetically by original filename. Use leading numbers such as 001, 002, 003 to control order."
|
||||
).classes("text-xs ui-text-muted mb-2")
|
||||
|
||||
@ui.refreshable
|
||||
def render_upload_list() -> None:
|
||||
if not uploaded_files:
|
||||
render_empty_state("No files uploaded yet.", italic=True)
|
||||
return
|
||||
|
||||
def remove_file(index: int) -> None:
|
||||
if 0 <= index < len(uploaded_files):
|
||||
removed_name, _ = uploaded_files.pop(index)
|
||||
ui.notify(f"Removed {removed_name}", type="info")
|
||||
render_upload_list.refresh()
|
||||
|
||||
def clear_files() -> None:
|
||||
uploaded_files.clear()
|
||||
ui.notify("Cleared queued files", type="info")
|
||||
render_upload_list.refresh()
|
||||
|
||||
ordered_uploads = sorted(
|
||||
enumerate(uploaded_files),
|
||||
key=lambda item: Path(item[1][0]).name.casefold(),
|
||||
)
|
||||
|
||||
with ui.column().classes("gap-1 w-full mt-2"):
|
||||
for index, (filename, _) in ordered_uploads:
|
||||
with ui.row().classes("w-full items-center justify-between ui-row-surface p-2"):
|
||||
ui.label(Path(filename).name).classes("text-xs font-mono ui-text-primary")
|
||||
ui.button(icon="delete", on_click=lambda idx=index: remove_file(idx)).props(
|
||||
"flat round dense color=negative text-xs"
|
||||
)
|
||||
|
||||
with ui.row().classes("w-full justify-end mt-2"):
|
||||
ui.button("Clear files", on_click=clear_files, icon="clear_all").props("flat dense").classes(
|
||||
"text-xs ui-text-danger"
|
||||
)
|
||||
|
||||
ui.label("Revision Editor").classes("text-subtitle1 text-weight-medium")
|
||||
editor = ui.textarea(label="Revision text", value=default_revision_text).props("autogrow outlined")
|
||||
editor.classes("w-full")
|
||||
async def on_upload(event) -> None:
|
||||
payload = await event.file.read()
|
||||
uploaded_files.append((event.file.name, payload))
|
||||
ui.notify(f"Added {event.file.name}", type="positive")
|
||||
render_upload_list.refresh()
|
||||
|
||||
async def save_revision() -> None:
|
||||
candidate = (editor.value or "").strip()
|
||||
if not candidate:
|
||||
ui.notify("Revision text is required.", type="warning")
|
||||
return
|
||||
ui.upload(
|
||||
on_upload=on_upload,
|
||||
auto_upload=True,
|
||||
label="Select source files or a folder",
|
||||
).props('accept=".jpg,.jpeg,.png,.tif,.tiff,.pdf" webkitdirectory directory multiple').classes("w-full")
|
||||
|
||||
try:
|
||||
await transcription_service.upsert_revision_for_source(
|
||||
source_id=refreshed_source.id,
|
||||
text=candidate,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Save failed", operation="jobs.save_revision")
|
||||
return
|
||||
|
||||
ui.notify("Revision saved", type="positive")
|
||||
await render_revision_panel.refresh()
|
||||
|
||||
with ui.row().classes("w-full justify-end"):
|
||||
ui.button(
|
||||
"Create revision" if current_revision is None else "Update revision",
|
||||
on_click=save_revision,
|
||||
icon="save",
|
||||
).props('unelevated color="primary"')
|
||||
|
||||
if current_revision is None:
|
||||
ui.label("No revision exists for this source.").classes("text-body2 text-grey-3")
|
||||
return
|
||||
|
||||
render_revision_row(
|
||||
revision=current_revision,
|
||||
initially_expanded=True,
|
||||
on_delete=lambda _revision, rid=current_revision.id: delete_revision_by_id(rid),
|
||||
)
|
||||
|
||||
await render_revision_panel()
|
||||
render_upload_list()
|
||||
|
||||
|
||||
def _resolve_primary_source(job: Job) -> Source | None:
|
||||
if not job.sources:
|
||||
def _render_job_detail_header(job: Job) -> None:
|
||||
with section_header_row(classes="justify-between items-center"):
|
||||
page_header(f"Job Record: {job.id}")
|
||||
with ui.row().classes("items-center gap-2"):
|
||||
archival_badge(job.status.value.upper())
|
||||
|
||||
if job.status in {JobStatus.QUEUED, JobStatus.PROCESSING}:
|
||||
destructive_button(
|
||||
"Cancel",
|
||||
on_click=lambda: ui.navigate.to(f"/jobs/{job.id}/cancel"),
|
||||
icon="stop_circle",
|
||||
extra_classes="text-xs",
|
||||
)
|
||||
|
||||
if job.status != JobStatus.TRANSCRIBED:
|
||||
ui.button("Resubmit", on_click=lambda: ui.navigate.to(f"/jobs/{job.id}/resubmit"), icon="replay").props(
|
||||
"outlined"
|
||||
).classes("text-xs")
|
||||
|
||||
destructive_button(
|
||||
"Delete Job",
|
||||
on_click=lambda: ui.navigate.to(f"/jobs/{job.id}/delete"),
|
||||
icon="delete",
|
||||
extra_classes="text-xs",
|
||||
)
|
||||
|
||||
|
||||
def _render_job_logistics(job: Job) -> None:
|
||||
with archival_card(title="Execution Logistics"):
|
||||
metadata_row("Provider:", job.provider or "pending")
|
||||
metadata_row("Model:", job.model or "pending")
|
||||
metadata_row("Prompt:", _latest_prompt_name(job) or "pending")
|
||||
metadata_row("Retry Count:", str(job.retry_count))
|
||||
metadata_row("Last Updated:", job.date_updated.isoformat())
|
||||
|
||||
|
||||
def _render_job_document_links(job: Job) -> None:
|
||||
with archival_card(title="Document Links"):
|
||||
ui.label("Navigate to related archival records:").classes("text-xs ui-text-muted mb-3")
|
||||
with ui.column().classes("w-full gap-2"):
|
||||
ui.button(
|
||||
"View Linked Document",
|
||||
on_click=lambda: ui.navigate.to(f"/documents/{job.document_id}"),
|
||||
icon="description",
|
||||
).classes("ui-btn-primary text-xs w-full")
|
||||
ui.button(
|
||||
"View Linked Sources",
|
||||
on_click=lambda: ui.navigate.to(f"/sources?job_id={job.id}"),
|
||||
icon="description",
|
||||
).props("flat text-xs").classes("ui-link-primary w-full")
|
||||
|
||||
|
||||
def _parse_uuid(value: str | None) -> UUID | None:
|
||||
if not value:
|
||||
return None
|
||||
return job.sources[0]
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _latest_prompt_name(job: Job) -> str | None:
|
||||
return job.prompt_name
|
||||
@@ -0,0 +1,514 @@
|
||||
"""People list and detail page registration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import Request
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.config import Settings, get_settings
|
||||
from transcription.db.models import Person
|
||||
from transcription.errors import ErrorCategory
|
||||
from transcription.services.documents import DocumentError, DocumentService
|
||||
from transcription.services.store import UploadError, store_person_portrait
|
||||
from transcription.ui.components.app_shell import render_navigation_header
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.data_display import metadata_row
|
||||
from transcription.ui.components.error_presenter import show_error
|
||||
from transcription.ui.components.primitives import (
|
||||
destructive_button,
|
||||
render_empty_state,
|
||||
section_header_row,
|
||||
)
|
||||
from transcription.ui.components.table.people import PersonTableRow, render_people_table
|
||||
from transcription.ui.components.viewers import dark_room_viewer
|
||||
from transcription.ui.theme import page_header
|
||||
|
||||
from ...db.session import SessionFactoryDep
|
||||
|
||||
|
||||
def register_page() -> None: # noqa: PLR0915
|
||||
"""Register people list and CRUD routes."""
|
||||
|
||||
@ui.page("/people")
|
||||
async def people_page(session_factory: SessionFactoryDep) -> None:
|
||||
people_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/people")
|
||||
|
||||
with ui.column().classes("w-full max-w-7xl mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header("Archival Entities: People")
|
||||
ui.button(
|
||||
"Create new person",
|
||||
on_click=lambda: ui.navigate.to("/people/new"),
|
||||
icon="person_add",
|
||||
).classes("ui-btn-primary")
|
||||
|
||||
try:
|
||||
people = sorted(
|
||||
await people_service.list_people(),
|
||||
key=lambda item: item.created_at,
|
||||
reverse=True,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="people.list")
|
||||
return
|
||||
|
||||
rows = [
|
||||
PersonTableRow(
|
||||
id=person.id,
|
||||
full_name=person.full_name,
|
||||
display_name=person.display_name or "",
|
||||
maiden_name=person.maiden_name or "",
|
||||
birth_date=person.birth_date.isoformat() if person.birth_date else "",
|
||||
)
|
||||
for person in people
|
||||
]
|
||||
render_people_table(rows)
|
||||
|
||||
@ui.page("/people/new")
|
||||
async def person_create_page(request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
people_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/people")
|
||||
draft_person_id = uuid4()
|
||||
|
||||
with ui.column().classes("w-full max-w-4xl mx-auto p-4 gap-4"):
|
||||
page_header("Create Person Record", subtitle="Full name is required.")
|
||||
|
||||
form = _render_person_form_fields(
|
||||
request=request,
|
||||
person_id=draft_person_id,
|
||||
)
|
||||
|
||||
async def submit_create() -> None:
|
||||
full_name = (form["full_name"].value or "").strip()
|
||||
if not full_name:
|
||||
ui.notify("Full name is required.", type="warning")
|
||||
return
|
||||
|
||||
birth_date = _parse_iso_date(form["birth_date"].value)
|
||||
death_date = _parse_iso_date(form["death_date"].value)
|
||||
|
||||
candidate = Person(
|
||||
id=draft_person_id,
|
||||
full_name=full_name,
|
||||
display_name=(form["display_name"].value or "").strip() or None,
|
||||
maiden_name=(form["maiden_name"].value or "").strip() or None,
|
||||
birth_date=birth_date,
|
||||
birth_date_raw=(form["birth_date_raw"].value or "").strip() or None,
|
||||
birth_place=(form["birth_place"].value or "").strip() or None,
|
||||
death_date=death_date,
|
||||
death_date_raw=(form["death_date_raw"].value or "").strip() or None,
|
||||
death_place=(form["death_place"].value or "").strip() or None,
|
||||
biography=(form["biography"].value or "").strip() or None,
|
||||
portrait_path=(form["portrait_path"].value or "").strip() or None,
|
||||
)
|
||||
|
||||
try:
|
||||
created = await people_service.create_person(candidate)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Create failed", operation="people.create")
|
||||
return
|
||||
|
||||
ui.notify("Person created", type="positive")
|
||||
ui.navigate.to(f"/people/{created.id}")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
ui.button("Save person", on_click=submit_create, icon="save").classes("ui-btn-primary")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to("/people"), icon="arrow_back").props("flat")
|
||||
|
||||
@ui.page("/people/{person_id}")
|
||||
async def person_detail_page(person_id: str, request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
people_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/people")
|
||||
|
||||
parsed_person_id = _parse_uuid(person_id)
|
||||
if parsed_person_id is None:
|
||||
ui.label("Invalid person id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
person = await people_service.read_person_detail(parsed_person_id)
|
||||
except DocumentError:
|
||||
ui.label("Person not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="people.read")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-[1800px] mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header(person.full_name, subtitle=f"Person ID: {person.id}")
|
||||
|
||||
with ui.row().classes("items-center gap-2"):
|
||||
ui.button(
|
||||
"Edit Person",
|
||||
on_click=lambda: ui.navigate.to(f"/people/{person.id}/edit"),
|
||||
icon="edit",
|
||||
).classes("ui-btn-primary text-xs")
|
||||
destructive_button(
|
||||
"Delete",
|
||||
on_click=lambda: ui.navigate.to(f"/people/{person.id}/delete"),
|
||||
icon="delete",
|
||||
extra_classes="text-xs",
|
||||
)
|
||||
|
||||
with ui.grid().classes("w-full grid-cols-12 gap-4"):
|
||||
_render_person_portrait_zone(
|
||||
person,
|
||||
settings=_resolve_runtime_settings(request),
|
||||
request=request,
|
||||
)
|
||||
_render_person_biographical_zone(person)
|
||||
_render_person_biography_zone(person)
|
||||
|
||||
@ui.page("/people/{person_id}/edit")
|
||||
async def person_edit_page(person_id: str, request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
people_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/people")
|
||||
|
||||
parsed_person_id = _parse_uuid(person_id)
|
||||
if parsed_person_id is None:
|
||||
ui.label("Invalid person id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
person = await people_service.read_person_detail(parsed_person_id)
|
||||
except DocumentError:
|
||||
ui.label("Person not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="people.edit.read")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-4xl mx-auto p-4 gap-4"):
|
||||
page_header("Edit Person Record", subtitle="Full name is required.")
|
||||
|
||||
form = _render_person_form_fields(
|
||||
request=request,
|
||||
person=person,
|
||||
person_id=person.id,
|
||||
)
|
||||
|
||||
async def submit_edit() -> None:
|
||||
full_name = (form["full_name"].value or "").strip()
|
||||
if not full_name:
|
||||
ui.notify("Full name is required.", type="warning")
|
||||
return
|
||||
|
||||
birth_date = _parse_iso_date(form["birth_date"].value)
|
||||
death_date = _parse_iso_date(form["death_date"].value)
|
||||
|
||||
candidate = Person(
|
||||
id=person.id,
|
||||
full_name=full_name,
|
||||
display_name=(form["display_name"].value or "").strip() or None,
|
||||
maiden_name=(form["maiden_name"].value or "").strip() or None,
|
||||
birth_date=birth_date,
|
||||
birth_date_raw=(form["birth_date_raw"].value or "").strip() or None,
|
||||
birth_place=(form["birth_place"].value or "").strip() or None,
|
||||
death_date=death_date,
|
||||
death_date_raw=(form["death_date_raw"].value or "").strip() or None,
|
||||
death_place=(form["death_place"].value or "").strip() or None,
|
||||
biography=(form["biography"].value or "").strip() or None,
|
||||
portrait_path=(form["portrait_path"].value or "").strip() or None,
|
||||
metadata_=person.metadata_,
|
||||
created_at=person.created_at,
|
||||
updated_at=person.updated_at,
|
||||
)
|
||||
|
||||
try:
|
||||
await people_service.update_person(candidate)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Save failed", operation="people.edit.save")
|
||||
return
|
||||
|
||||
ui.notify("Person updated", type="positive")
|
||||
ui.navigate.to(f"/people/{person.id}")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
ui.button("Save changes", on_click=submit_edit, icon="save").classes("ui-btn-primary")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to(f"/people/{person.id}"), icon="arrow_back").props("flat")
|
||||
|
||||
@ui.page("/people/{person_id}/delete")
|
||||
async def person_delete_page(person_id: str, session_factory: SessionFactoryDep) -> None:
|
||||
people_service = DocumentService(session_factory=session_factory)
|
||||
render_navigation_header(current_path="/people")
|
||||
|
||||
parsed_person_id = _parse_uuid(person_id)
|
||||
if parsed_person_id is None:
|
||||
ui.label("Invalid person id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
person = await people_service.read_person_detail(parsed_person_id)
|
||||
except DocumentError:
|
||||
ui.label("Person not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="people.delete.read")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-xl mx-auto p-4 gap-4"):
|
||||
page_header("Delete Person Record")
|
||||
|
||||
with archival_card(extra_classes="gap-2"):
|
||||
ui.label(f"Person: {person.full_name}").classes("text-sm font-semibold ui-text-primary")
|
||||
|
||||
if person.document_people:
|
||||
ui.label(
|
||||
f"This will also remove {len(person.document_people)} linked document relationship(s)."
|
||||
).classes("text-xs ui-text-danger font-bold mt-2")
|
||||
|
||||
ui.label("This action permanently deletes the person record.").classes("text-xs ui-text-danger font-medium")
|
||||
|
||||
async def submit_delete() -> None:
|
||||
try:
|
||||
await people_service.delete_person(person)
|
||||
except DocumentError as exc:
|
||||
if exc.category == ErrorCategory.NOT_FOUND:
|
||||
ui.notify("Person not found.", type="warning")
|
||||
ui.navigate.to("/people")
|
||||
return
|
||||
show_error(exc, title="Delete failed", operation="people.delete")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Delete failed", operation="people.delete")
|
||||
return
|
||||
|
||||
ui.notify("Person deleted", type="positive")
|
||||
ui.navigate.to("/people")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
destructive_button("Delete person permanently", on_click=submit_delete, icon="delete_forever", variant="solid")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to(f"/people/{person.id}"), icon="arrow_back").props("flat")
|
||||
|
||||
|
||||
# --- Helper Sub-Components & Form Builders ---
|
||||
|
||||
|
||||
def _render_person_form_fields(
|
||||
*,
|
||||
request: Request,
|
||||
person: Person | None = None,
|
||||
person_id: UUID,
|
||||
) -> dict[str, Any]:
|
||||
with archival_card(extra_classes="gap-3"):
|
||||
with ui.row().classes("w-full gap-3 grid grid-cols-1 md:grid-cols-3"):
|
||||
full_name_input = ui.input(label="Full name", value=person.full_name if person else "").props("outlined").classes("ui-form-surface")
|
||||
display_name_input = ui.input(label="Display name", value=person.display_name if person and person.display_name else "").props("outlined").classes("ui-form-surface")
|
||||
maiden_name_input = ui.input(label="Maiden name", value=person.maiden_name if person and person.maiden_name else "").props("outlined").classes("ui-form-surface")
|
||||
|
||||
with ui.row().classes("w-full gap-3 grid grid-cols-1 md:grid-cols-3"):
|
||||
birth_date_input = ui.input(
|
||||
label="Birth date (YYYY-MM-DD)",
|
||||
value=person.birth_date.isoformat() if person and person.birth_date else "",
|
||||
).props('outlined type="date"').classes("ui-form-surface")
|
||||
birth_date_raw_input = ui.input(label="Birth date (approximate)", value=person.birth_date_raw if person and person.birth_date_raw else "").props("outlined").classes("ui-form-surface")
|
||||
birth_place_input = ui.input(label="Birth place", value=person.birth_place if person and person.birth_place else "").props("outlined").classes("ui-form-surface")
|
||||
|
||||
with ui.row().classes("w-full gap-3 grid grid-cols-1 md:grid-cols-3"):
|
||||
death_date_input = ui.input(
|
||||
label="Death date (YYYY-MM-DD)",
|
||||
value=person.death_date.isoformat() if person and person.death_date else "",
|
||||
).props('outlined type="date"').classes("ui-form-surface")
|
||||
death_date_raw_input = ui.input(label="Death date (approximate)", value=person.death_date_raw if person and person.death_date_raw else "").props("outlined").classes("ui-form-surface")
|
||||
death_place_input = ui.input(label="Death place", value=person.death_place if person and person.death_place else "").props("outlined").classes("ui-form-surface")
|
||||
|
||||
biography_input = ui.textarea(label="Biography", value=person.biography if person and person.biography else "").props("outlined autogrow").classes("w-full ui-form-surface")
|
||||
portrait_path_input = ui.input(label="Portrait path", value=person.portrait_path if person and person.portrait_path else "").props("outlined").classes("w-full ui-form-surface")
|
||||
|
||||
_bind_portrait_file_picker(
|
||||
portrait_path_input,
|
||||
settings=_resolve_runtime_settings(request),
|
||||
person_id=person_id,
|
||||
)
|
||||
|
||||
return {
|
||||
"full_name": full_name_input,
|
||||
"display_name": display_name_input,
|
||||
"maiden_name": maiden_name_input,
|
||||
"birth_date": birth_date_input,
|
||||
"birth_date_raw": birth_date_raw_input,
|
||||
"birth_place": birth_place_input,
|
||||
"death_date": death_date_input,
|
||||
"death_date_raw": death_date_raw_input,
|
||||
"death_place": death_place_input,
|
||||
"biography": biography_input,
|
||||
"portrait_path": portrait_path_input,
|
||||
}
|
||||
|
||||
|
||||
def _render_person_portrait_zone(person: Person, *, settings: Settings, request: Request) -> None:
|
||||
portrait_src = _resolve_portrait_src(person.portrait_path, settings=settings, request=request)
|
||||
with ui.column().classes("col-span-12 lg:col-span-4"):
|
||||
dark_room_viewer(portrait_src, count_label="Portrait Media")
|
||||
|
||||
|
||||
def _render_person_biographical_zone(person: Person) -> None:
|
||||
with ui.column().classes("col-span-12 lg:col-span-4 gap-4"):
|
||||
with archival_card(title="Biographical Record"):
|
||||
metadata_row("Full Name:", person.full_name)
|
||||
metadata_row("Display Name:", person.display_name or "Not set")
|
||||
metadata_row("Maiden Name:", person.maiden_name or "Not set")
|
||||
metadata_row("Birth Date:", person.birth_date.isoformat() if person.birth_date else "Not set")
|
||||
metadata_row("Approx. Birth Date:", person.birth_date_raw or "Not set")
|
||||
metadata_row("Birth Place:", person.birth_place or "Not set")
|
||||
metadata_row("Death Date:", person.death_date.isoformat() if person.death_date else "Not set")
|
||||
metadata_row("Approx. Death Date:", person.death_date_raw or "Not set")
|
||||
metadata_row("Death Place:", person.death_place or "Not set")
|
||||
|
||||
with archival_card(title="System Logistics"):
|
||||
ui.label(f"Created: {person.created_at.isoformat()}").classes("text-[11px] ui-text-muted")
|
||||
ui.label(f"Updated: {person.updated_at.isoformat()}").classes("text-[11px] ui-text-muted")
|
||||
|
||||
|
||||
def _render_person_biography_zone(person: Person) -> None:
|
||||
with ui.column().classes("col-span-12 lg:col-span-4 gap-4"):
|
||||
with archival_card(title="Biography"):
|
||||
ui.label(person.biography or "No biography recorded.").classes("p-2 ui-note-box text-xs w-full")
|
||||
|
||||
with archival_card(title="Linked Documents"):
|
||||
if not person.document_people:
|
||||
render_empty_state("No linked documents yet.", italic=True)
|
||||
render_empty_state("Link this person from a Document workflow.")
|
||||
else:
|
||||
with ui.column().classes("w-full gap-2"):
|
||||
for link in person.document_people:
|
||||
doc = link.document
|
||||
if doc is None:
|
||||
continue
|
||||
with ui.row().classes("w-full justify-between items-center ui-row-surface p-2"):
|
||||
with ui.column().classes("gap-0"):
|
||||
ui.label(doc.name).classes("text-xs font-semibold ui-text-primary")
|
||||
ui.label(f"Role: {link.role.value}").classes("text-[10px] ui-text-muted")
|
||||
ui.button(
|
||||
"Open",
|
||||
on_click=lambda _=None, doc_id=doc.id: ui.navigate.to(f"/documents/{doc_id}"),
|
||||
icon="open_in_new",
|
||||
).props("flat dense text-xs").classes("ui-link-primary")
|
||||
|
||||
|
||||
# --- Utilities & Input Binding Helpers ---
|
||||
|
||||
|
||||
def _bind_portrait_file_picker(portrait_path_input: ui.input, *, settings: Settings, person_id: UUID) -> None:
|
||||
async def on_portrait_selected(event) -> None:
|
||||
payload = await event.file.read()
|
||||
try:
|
||||
stored_path = store_person_portrait(
|
||||
person_id=person_id,
|
||||
filename=event.file.name,
|
||||
file_bytes=payload,
|
||||
settings=settings,
|
||||
)
|
||||
except UploadError as exc:
|
||||
ui.notify(str(exc), type="negative")
|
||||
return
|
||||
except Exception: # noqa: BLE001
|
||||
ui.notify("Unable to store portrait image.", type="negative")
|
||||
return
|
||||
|
||||
try:
|
||||
relative_path = stored_path.resolve().relative_to(settings.upload_dir.resolve()).as_posix()
|
||||
except ValueError:
|
||||
relative_path = stored_path.name
|
||||
|
||||
portrait_path_input.value = relative_path
|
||||
ui.notify("Portrait uploaded.", type="positive")
|
||||
|
||||
ui.upload(
|
||||
on_upload=on_portrait_selected,
|
||||
auto_upload=True,
|
||||
label="Choose portrait file",
|
||||
).props('accept=".jpg,.jpeg,.png,.gif,.webp,.bmp,.tif,.tiff"').classes("w-full")
|
||||
portrait_dir = settings.upload_dir / "persons" / str(person_id)
|
||||
ui.label(f"Portraits are stored under {portrait_dir}.").classes("text-xs ui-text-muted")
|
||||
|
||||
|
||||
def _resolve_portrait_src(path: str | None, *, settings: Settings, request: Request) -> str | None:
|
||||
candidate = (path or "").strip()
|
||||
if not candidate:
|
||||
return None
|
||||
|
||||
normalized = candidate.replace("\\", "/")
|
||||
lowered = normalized.casefold()
|
||||
if lowered.startswith(("http://", "https://", "data:")):
|
||||
return normalized
|
||||
if normalized.startswith("/uploads/"):
|
||||
return _to_absolute_upload_url(normalized, request=request)
|
||||
|
||||
upload_dir = settings.upload_dir.resolve()
|
||||
path_obj = Path(candidate)
|
||||
|
||||
if path_obj.is_absolute():
|
||||
absolute_candidates = [path_obj.resolve()]
|
||||
else:
|
||||
absolute_candidates = [
|
||||
(Path.cwd() / path_obj).resolve(),
|
||||
(upload_dir / path_obj).resolve(),
|
||||
]
|
||||
|
||||
for absolute_candidate in absolute_candidates:
|
||||
try:
|
||||
relative = absolute_candidate.relative_to(upload_dir).as_posix()
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(relative)}", request=request)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
upload_name = upload_dir.name.casefold()
|
||||
normalized_parts = Path(normalized).parts
|
||||
lowered_parts = [part.casefold() for part in normalized_parts]
|
||||
if upload_name in lowered_parts:
|
||||
idx = lowered_parts.index(upload_name)
|
||||
relative = Path(*normalized_parts[idx + 1 :]).as_posix()
|
||||
if relative:
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(relative)}", request=request)
|
||||
|
||||
if lowered.startswith("uploads/"):
|
||||
return _to_absolute_upload_url(f"/{normalized}", request=request)
|
||||
if lowered.startswith("data/"):
|
||||
relative = normalized.split("/", 1)[1] if "/" in normalized else ""
|
||||
if relative:
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(relative)}", request=request)
|
||||
if lowered.startswith(("documents/", "persons/")):
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(normalized)}", request=request)
|
||||
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(path_obj.name)}", request=request)
|
||||
|
||||
|
||||
def _to_absolute_upload_url(path: str, *, request: Request) -> str:
|
||||
base = str(request.base_url).rstrip("/")
|
||||
normalized_path = path if path.startswith("/") else f"/{path}"
|
||||
return f"{base}{normalized_path}"
|
||||
|
||||
|
||||
def _resolve_runtime_settings(request: Request) -> Settings:
|
||||
app_settings = getattr(request.app.state, "settings", None)
|
||||
if isinstance(app_settings, Settings):
|
||||
return app_settings
|
||||
return get_settings()
|
||||
|
||||
|
||||
def _parse_uuid(value: str | None) -> UUID | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_iso_date(value: str | None) -> date | None:
|
||||
candidate = (value or "").strip()
|
||||
if not candidate:
|
||||
return None
|
||||
try:
|
||||
return date.fromisoformat(candidate)
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -0,0 +1,457 @@
|
||||
"""Sources list and detail page registration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Request
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.config import Settings, get_settings
|
||||
from transcription.db.models import JobSource, Source
|
||||
from transcription.services.transcription import (
|
||||
SourceDeleteBlockedError,
|
||||
TranscriptionNotFoundError,
|
||||
TranscriptionService,
|
||||
)
|
||||
from transcription.ui.components.app_shell import render_navigation_header
|
||||
from transcription.ui.components.cards import archival_card
|
||||
from transcription.ui.components.data_display import archival_badge, metadata_row
|
||||
from transcription.ui.components.error_presenter import show_error
|
||||
from transcription.ui.components.primitives import destructive_button, render_empty_state, section_header_row
|
||||
from transcription.ui.components.table.sources import SourceTableRow, render_sources_table
|
||||
from transcription.ui.components.viewers import dark_room_viewer
|
||||
from transcription.ui.theme import page_header
|
||||
|
||||
from ...db.session import SessionFactoryDep
|
||||
|
||||
|
||||
def register_page() -> None:
|
||||
"""Register sources list, detail, and deletion routes."""
|
||||
|
||||
@ui.page("/sources")
|
||||
async def sources_page(
|
||||
session_factory: SessionFactoryDep,
|
||||
document_id: str | None = None,
|
||||
job_id: str | None = None,
|
||||
) -> None:
|
||||
sources_service = TranscriptionService(session_factory=session_factory)
|
||||
parsed_doc_id = _parse_uuid(document_id)
|
||||
parsed_job_id = _parse_uuid(job_id)
|
||||
|
||||
header_title = "Source Asset Records"
|
||||
if parsed_doc_id is not None:
|
||||
header_title = "Sources for Document"
|
||||
elif parsed_job_id is not None:
|
||||
header_title = "Sources for Job"
|
||||
|
||||
try:
|
||||
sources = await sources_service.list_sources_detail(document_id=parsed_doc_id, job_id=parsed_job_id)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="sources.list")
|
||||
return
|
||||
|
||||
render_navigation_header(current_path="/sources")
|
||||
|
||||
with ui.column().classes("w-full max-w-7xl mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header(header_title)
|
||||
if parsed_doc_id is not None:
|
||||
ui.button(
|
||||
"Back to Document",
|
||||
on_click=lambda: ui.navigate.to(f"/documents/{parsed_doc_id}"),
|
||||
icon="arrow_back",
|
||||
).props("flat")
|
||||
elif parsed_job_id is not None:
|
||||
ui.button(
|
||||
"Back to Job",
|
||||
on_click=lambda: ui.navigate.to(f"/jobs/{parsed_job_id}"),
|
||||
icon="arrow_back",
|
||||
).props("flat")
|
||||
else:
|
||||
ui.button(
|
||||
"Create Job",
|
||||
on_click=lambda: ui.navigate.to("/jobs/new"),
|
||||
icon="add",
|
||||
).classes("ui-btn-primary")
|
||||
|
||||
rows = [
|
||||
SourceTableRow(
|
||||
id=source.id,
|
||||
page_number=source.page_number,
|
||||
upload_name=source.upload_name,
|
||||
filename=source.filename,
|
||||
document_id=source.document_id,
|
||||
document_name=source.document_name,
|
||||
job_source_status=source.latest_status.value if source.latest_status else "unprocessed",
|
||||
job_source_error_detail=source.latest_error_detail,
|
||||
)
|
||||
for source in sorted(sources, key=lambda item: (item.page_number, item.upload_name.casefold()))
|
||||
]
|
||||
render_sources_table(rows)
|
||||
|
||||
if parsed_doc_id is None and parsed_job_id is None:
|
||||
ui.label("Open a source row to inspect AI output and add human revisions.").classes("text-xs ui-text-muted")
|
||||
|
||||
@ui.page("/sources/{source_id}")
|
||||
async def source_detail_page(source_id: str, request: Request, session_factory: SessionFactoryDep) -> None:
|
||||
sources_service = TranscriptionService(session_factory=session_factory)
|
||||
parsed_source_id = _parse_uuid(source_id)
|
||||
|
||||
render_navigation_header(current_path="/sources")
|
||||
|
||||
if parsed_source_id is None:
|
||||
ui.label("Invalid source id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
source = await sources_service.read_source_detail(parsed_source_id)
|
||||
except TranscriptionNotFoundError:
|
||||
ui.label("Source not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="sources.read")
|
||||
return
|
||||
|
||||
latest_job_source = _latest_job_source(source)
|
||||
original_transcription = _resolve_original_transcription(source=source, latest_job_source=latest_job_source)
|
||||
|
||||
with ui.column().classes("w-full max-w-[1800px] mx-auto p-4 gap-4"):
|
||||
with section_header_row():
|
||||
page_header(
|
||||
f"Source Page {source.page_number}: {source.upload_name}",
|
||||
subtitle=f"Source ID: {source.id}",
|
||||
)
|
||||
with ui.row().classes("items-center gap-2"):
|
||||
ui.button(
|
||||
"Back to Sources",
|
||||
on_click=lambda: ui.navigate.to("/sources"),
|
||||
icon="arrow_back",
|
||||
).props("flat")
|
||||
destructive_button(
|
||||
"Delete Source",
|
||||
on_click=lambda: ui.navigate.to(f"/sources/{source.id}/delete"),
|
||||
icon="delete",
|
||||
extra_classes="text-xs",
|
||||
)
|
||||
|
||||
with ui.grid().classes("w-full grid-cols-12 gap-4"):
|
||||
_render_source_viewer_zone(
|
||||
source,
|
||||
settings=_resolve_runtime_settings(request),
|
||||
request=request,
|
||||
)
|
||||
_render_source_transcription_column(
|
||||
source=source,
|
||||
original_transcription=original_transcription,
|
||||
latest_job_source=latest_job_source,
|
||||
sources_service=sources_service,
|
||||
)
|
||||
_render_source_metadata_column(source=source, latest_job_source=latest_job_source)
|
||||
|
||||
@ui.page("/sources/{source_id}/delete")
|
||||
async def source_delete_page(source_id: str, session_factory: SessionFactoryDep) -> None:
|
||||
sources_service = TranscriptionService(session_factory=session_factory)
|
||||
parsed_source_id = _parse_uuid(source_id)
|
||||
|
||||
render_navigation_header(current_path="/sources")
|
||||
|
||||
if parsed_source_id is None:
|
||||
ui.label("Invalid source id").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
|
||||
try:
|
||||
source = await sources_service.read_source_detail(parsed_source_id)
|
||||
except TranscriptionNotFoundError:
|
||||
ui.label("Source not found").classes("text-h6 ui-text-danger p-4")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Load failed", operation="sources.delete.read")
|
||||
return
|
||||
|
||||
with ui.column().classes("w-full max-w-xl mx-auto p-4 gap-4"):
|
||||
page_header("Delete Source Record")
|
||||
|
||||
with archival_card(extra_classes="gap-2"):
|
||||
ui.label(f"Source: {source.upload_name}").classes("text-sm font-semibold ui-text-primary")
|
||||
|
||||
if source.job_sources:
|
||||
ui.label("Delete is only available for unlinked sources.").classes("text-xs ui-text-danger font-bold mt-2")
|
||||
ui.label("Open the related job record and remove job links first.").classes("text-xs ui-text-muted italic")
|
||||
with ui.row().classes("w-full items-center gap-2 mt-4"):
|
||||
ui.button(
|
||||
"Back to Source",
|
||||
on_click=lambda: ui.navigate.to(f"/sources/{source.id}"),
|
||||
icon="arrow_back",
|
||||
).classes("ui-btn-primary text-xs")
|
||||
ui.button(
|
||||
"Go to Jobs",
|
||||
on_click=lambda: ui.navigate.to("/jobs"),
|
||||
icon="work_history",
|
||||
).props("flat text-xs")
|
||||
return
|
||||
|
||||
ui.label("This action permanently deletes the source record.").classes("text-xs ui-text-danger font-medium")
|
||||
|
||||
async def submit_delete() -> None:
|
||||
try:
|
||||
await sources_service.delete_unlinked_source(source_id=source.id)
|
||||
except SourceDeleteBlockedError as exc:
|
||||
ui.notify(exc.message, type="warning")
|
||||
return
|
||||
except TranscriptionNotFoundError:
|
||||
ui.notify("Source not found.", type="warning")
|
||||
ui.navigate.to("/sources")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Delete failed", operation="sources.delete")
|
||||
return
|
||||
|
||||
ui.notify("Source deleted", type="positive")
|
||||
ui.navigate.to("/sources")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
destructive_button("Delete source permanently", on_click=submit_delete, icon="delete_forever", variant="solid")
|
||||
ui.button("Cancel", on_click=lambda: ui.navigate.to(f"/sources/{source.id}"), icon="arrow_back").props("flat")
|
||||
|
||||
|
||||
def _render_source_viewer_zone(source: Source, *, settings: Settings, request: Request) -> None:
|
||||
with ui.column().classes("col-span-12 lg:col-span-4"):
|
||||
dark_room_viewer(
|
||||
_resolve_source_media_src(source.file_path, settings=settings, request=request),
|
||||
count_label=f"Page {source.page_number}",
|
||||
)
|
||||
|
||||
|
||||
def _render_source_transcription_column(
|
||||
*,
|
||||
source: Source,
|
||||
original_transcription: str | None,
|
||||
latest_job_source: JobSource | None,
|
||||
sources_service: TranscriptionService,
|
||||
) -> None:
|
||||
with ui.column().classes("col-span-12 lg:col-span-4 gap-4"):
|
||||
_render_source_transcription_zone(
|
||||
source=source,
|
||||
original_transcription=original_transcription,
|
||||
latest_job_source=latest_job_source,
|
||||
sources_service=sources_service,
|
||||
)
|
||||
|
||||
|
||||
def _render_source_metadata_column(*, source: Source, latest_job_source: JobSource | None) -> None:
|
||||
with ui.column().classes("col-span-12 lg:col-span-4 gap-4"):
|
||||
_render_source_metadata_zone(source)
|
||||
_render_source_job_metadata_zone(latest_job_source)
|
||||
_render_source_revision_logistics_zone(source)
|
||||
|
||||
|
||||
def _render_source_metadata_zone(source: Source) -> None:
|
||||
with archival_card(title="Source Metadata"):
|
||||
metadata_row("Upload Name:", source.upload_name)
|
||||
metadata_row("Stored Filename:", source.filename)
|
||||
metadata_row("Page Number:", str(source.page_number))
|
||||
metadata_row("Document Name:", source.document_name or "Not set")
|
||||
metadata_row("Document ID:", str(source.document_id))
|
||||
metadata_row("Stored Path:", source.file_path)
|
||||
|
||||
|
||||
def _render_source_job_metadata_zone(latest_job_source: JobSource | None) -> None:
|
||||
with archival_card(title="SourceJob Metadata"):
|
||||
if latest_job_source is None:
|
||||
render_empty_state("No job execution metadata available yet.", italic=True)
|
||||
return
|
||||
|
||||
status = latest_job_source.status.value
|
||||
with ui.row().classes("w-full justify-between items-center mb-2"):
|
||||
ui.label("Latest Status").classes("text-xs ui-text-muted")
|
||||
archival_badge(status)
|
||||
|
||||
metadata_row("Job ID:", str(latest_job_source.job_id))
|
||||
metadata_row("Executed:", latest_job_source.executed_at.isoformat())
|
||||
metadata_row(
|
||||
"Provider:",
|
||||
latest_job_source.job.provider if latest_job_source.job and latest_job_source.job.provider else "unknown",
|
||||
)
|
||||
metadata_row(
|
||||
"Model:",
|
||||
latest_job_source.job.model if latest_job_source.job and latest_job_source.job.model else "unknown",
|
||||
)
|
||||
metadata_row(
|
||||
"Prompt:",
|
||||
latest_job_source.job.prompt_name if latest_job_source.job and latest_job_source.job.prompt_name else "unknown",
|
||||
)
|
||||
|
||||
if latest_job_source.error_detail:
|
||||
with ui.column().classes("w-full mt-2"):
|
||||
ui.label("Failure Detail:").classes("ui-text-muted text-xs mb-1")
|
||||
ui.label(latest_job_source.error_detail).classes("p-2 ui-note-box text-xs")
|
||||
|
||||
|
||||
def _render_source_revision_logistics_zone(source: Source) -> None:
|
||||
with archival_card(title="Revision Logistics"):
|
||||
metadata_row("Revised:", "Yes" if source.revised_text else "No")
|
||||
metadata_row(
|
||||
"Last Revised:",
|
||||
source.date_revised.isoformat() if source.date_revised is not None else "Not revised",
|
||||
)
|
||||
metadata_row("Uploaded:", source.date_uploaded.isoformat())
|
||||
|
||||
|
||||
def _render_source_transcription_zone(
|
||||
*,
|
||||
source: Source,
|
||||
original_transcription: str | None,
|
||||
latest_job_source: JobSource | None,
|
||||
sources_service: TranscriptionService,
|
||||
) -> None:
|
||||
with archival_card(title="Transcription Text"):
|
||||
if original_transcription:
|
||||
ui.label(original_transcription).classes("p-2 ui-note-box text-xs whitespace-pre-wrap")
|
||||
else:
|
||||
render_empty_state("No transcription text available yet.", italic=True)
|
||||
|
||||
with archival_card(title="Editable Revision"):
|
||||
seed_revision = source.revised_text if source.revised_text is not None else (original_transcription or "")
|
||||
revision_input = ui.textarea(
|
||||
label="Revised transcription",
|
||||
value=seed_revision,
|
||||
).props("outlined autogrow").classes("w-full ui-form-surface")
|
||||
|
||||
save_state = ui.label(
|
||||
f"Last saved: {source.date_revised.isoformat()}"
|
||||
if source.date_revised is not None
|
||||
else "No revision saved yet."
|
||||
).classes("text-xs ui-text-muted")
|
||||
|
||||
async def submit_revision() -> None:
|
||||
revised_text = (revision_input.value or "").strip()
|
||||
if not revised_text:
|
||||
ui.notify("Revised transcription cannot be empty.", type="warning")
|
||||
return
|
||||
|
||||
try:
|
||||
updated = await sources_service.upsert_revision_for_source(
|
||||
source_id=source.id,
|
||||
text=revised_text,
|
||||
)
|
||||
except TranscriptionNotFoundError:
|
||||
ui.notify("Source not found.", type="warning")
|
||||
ui.navigate.to("/sources")
|
||||
return
|
||||
except Exception as exc: # noqa: BLE001
|
||||
show_error(exc, title="Save failed", operation="sources.revision.save")
|
||||
return
|
||||
|
||||
source.revised_text = updated.revised_text
|
||||
source.date_revised = updated.date_revised
|
||||
save_state.text = (
|
||||
f"Last saved: {updated.date_revised.isoformat()}" if updated.date_revised is not None else "Revision saved."
|
||||
)
|
||||
ui.notify("Revision saved", type="positive")
|
||||
|
||||
with ui.row().classes("w-full items-center gap-2 mt-2"):
|
||||
ui.button("Save revision", on_click=submit_revision, icon="save").classes("ui-btn-primary")
|
||||
ui.button("Reset", on_click=lambda: _reset_revision_text(revision_input, source, original_transcription), icon="refresh").props("flat")
|
||||
|
||||
if latest_job_source is not None and latest_job_source.status.value == "failed":
|
||||
ui.label("Source has a failed job execution. Save a human revision to preserve corrected text.").classes(
|
||||
"text-xs ui-text-muted italic"
|
||||
)
|
||||
|
||||
|
||||
def _reset_revision_text(revision_input: ui.textarea, source: Source, original_transcription: str | None) -> None:
|
||||
fallback_text = source.revised_text if source.revised_text is not None else (original_transcription or "")
|
||||
revision_input.value = fallback_text
|
||||
|
||||
|
||||
def _latest_job_source(source: Source) -> JobSource | None:
|
||||
if not source.job_sources:
|
||||
return None
|
||||
return max(source.job_sources, key=lambda item: item.executed_at)
|
||||
|
||||
|
||||
def _resolve_original_transcription(*, source: Source, latest_job_source: JobSource | None) -> str | None:
|
||||
if latest_job_source is not None and latest_job_source.raw_transcription:
|
||||
return latest_job_source.raw_transcription
|
||||
return source.raw_transcription
|
||||
|
||||
|
||||
def _resolve_source_media_src(path: str | None, *, settings: Settings, request: Request) -> str | None:
|
||||
candidate = (path or "").strip()
|
||||
if not candidate:
|
||||
return None
|
||||
|
||||
normalized = candidate.replace("\\", "/")
|
||||
lowered = normalized.casefold()
|
||||
|
||||
if lowered.startswith(("http://", "https://", "data:")):
|
||||
return normalized
|
||||
if normalized.startswith("/uploads/"):
|
||||
return _to_absolute_upload_url(normalized, request=request)
|
||||
|
||||
upload_dir = settings.upload_dir.resolve()
|
||||
path_obj = Path(candidate)
|
||||
|
||||
# Case 1: absolute filesystem path
|
||||
if path_obj.is_absolute():
|
||||
absolute_candidates = [path_obj.resolve()]
|
||||
else:
|
||||
# Case 2: relative path that may already include data root name (e.g. data/documents/...)
|
||||
absolute_candidates = [
|
||||
(Path.cwd() / path_obj).resolve(),
|
||||
(upload_dir / path_obj).resolve(),
|
||||
]
|
||||
|
||||
for absolute_candidate in absolute_candidates:
|
||||
try:
|
||||
relative = absolute_candidate.relative_to(upload_dir).as_posix()
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(relative)}", request=request)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
# Fallback: if path contains upload-dir folder name, strip through that segment.
|
||||
upload_name = upload_dir.name.casefold()
|
||||
normalized_parts = Path(normalized).parts
|
||||
lowered_parts = [part.casefold() for part in normalized_parts]
|
||||
if upload_name in lowered_parts:
|
||||
idx = lowered_parts.index(upload_name)
|
||||
relative = Path(*normalized_parts[idx + 1 :]).as_posix()
|
||||
if relative:
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(relative)}", request=request)
|
||||
|
||||
# Final fallback: treat as already relative to upload root.
|
||||
if lowered.startswith("uploads/"):
|
||||
return _to_absolute_upload_url(f"/{normalized}", request=request)
|
||||
if lowered.startswith("data/"):
|
||||
relative = normalized.split("/", 1)[1] if "/" in normalized else ""
|
||||
if relative:
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(relative)}", request=request)
|
||||
if lowered.startswith("documents/") or lowered.startswith("persons/"):
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(normalized)}", request=request)
|
||||
|
||||
return _to_absolute_upload_url(f"/uploads/{quote(path_obj.name)}", request=request)
|
||||
|
||||
|
||||
def _to_absolute_upload_url(path: str, *, request: Request) -> str:
|
||||
base = str(request.base_url).rstrip("/")
|
||||
normalized_path = path if path.startswith("/") else f"/{path}"
|
||||
return f"{base}{normalized_path}"
|
||||
|
||||
|
||||
def _resolve_runtime_settings(request: Request) -> Settings:
|
||||
app_settings = getattr(request.app.state, "settings", None)
|
||||
if isinstance(app_settings, Settings):
|
||||
return app_settings
|
||||
return get_settings()
|
||||
|
||||
|
||||
def _parse_uuid(value: str | None) -> UUID | None:
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
return None
|
||||
@@ -1,33 +0,0 @@
|
||||
"""Upload page registration and handlers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import Request
|
||||
from nicegui import ui
|
||||
|
||||
from transcription.app_state import resolve_session_factory
|
||||
from transcription.db import get_session
|
||||
from transcription.services.store import create_upload_job
|
||||
from transcription.ui.components.app_shell import render_navigation_header
|
||||
from transcription.ui.components.upload import render_upload_widget
|
||||
from transcription.worker import resolve_worker_notifier
|
||||
|
||||
|
||||
def register_page() -> None:
|
||||
"""Register the upload page route."""
|
||||
|
||||
@ui.page("/upload", title="Upload Document")
|
||||
def upload_page(request: Request) -> None:
|
||||
render_navigation_header(current_path="/upload")
|
||||
session_factory = resolve_session_factory(request.app.state)
|
||||
|
||||
async def submit_upload(filename: str, file_bytes: bytes):
|
||||
async with get_session(session_factory=session_factory) as session:
|
||||
return await create_upload_job(
|
||||
filename=filename,
|
||||
file_bytes=file_bytes,
|
||||
session=session,
|
||||
)
|
||||
|
||||
notify_worker = resolve_worker_notifier(request.app.state)
|
||||
render_upload_widget(submitter=submit_upload, notifier=notify_worker)
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Package resource helpers for UI presentation assets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import cache
|
||||
from importlib.resources import files
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
|
||||
@cache
|
||||
def read_css(relative_path: str) -> str:
|
||||
"""Read and cache a CSS resource relative to ``ui/static``."""
|
||||
resource_path = PurePosixPath(relative_path)
|
||||
if resource_path.is_absolute() or ".." in resource_path.parts or resource_path.suffix != ".css":
|
||||
msg = f"Invalid CSS resource path: {relative_path}"
|
||||
raise ValueError(msg)
|
||||
|
||||
resource = files("transcription.ui").joinpath("static", *resource_path.parts)
|
||||
return resource.read_text(encoding="utf-8")
|
||||
@@ -1,30 +0,0 @@
|
||||
:root {
|
||||
/* Soft blue-night palette tokens */
|
||||
--ctp-rosewater: #f2dde5;
|
||||
--ctp-flamingo: #edcfd8;
|
||||
--ctp-pink: #dcc7de;
|
||||
--ctp-mauve: #a9bde5;
|
||||
--ctp-red: #d98a9a;
|
||||
--ctp-maroon: #d39aa5;
|
||||
--ctp-peach: #d7af8c;
|
||||
--ctp-yellow: #e2c083;
|
||||
--ctp-green: #86c8ad;
|
||||
--ctp-teal: #77bfbe;
|
||||
--ctp-sky: #7ebdda;
|
||||
--ctp-sapphire: #74aed0;
|
||||
--ctp-blue: #92b5f5;
|
||||
--ctp-lavender: #6f97e8;
|
||||
--ctp-text: #d8e2f5;
|
||||
--ctp-subtext1: #bfcae0;
|
||||
--ctp-subtext0: #a9b6cf;
|
||||
--ctp-overlay2: #95a3bf;
|
||||
--ctp-overlay1: #7c8ca9;
|
||||
--ctp-overlay0: #657490;
|
||||
--ctp-surface2: #4d5f7c;
|
||||
--ctp-surface1: #394a65;
|
||||
--ctp-surface0: #2a3954;
|
||||
--ctp-base: #1f2b42;
|
||||
--ctp-mantle: #1a2538;
|
||||
--ctp-crust: #141e30;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
:root {
|
||||
--palette-carbon-black: #1c2321;
|
||||
--palette-cool-steel: #7d98a1;
|
||||
--palette-blue-slate: #5e6572;
|
||||
--palette-powder-blue: #a9b4c2;
|
||||
--palette-platinum: #eef1ef;
|
||||
|
||||
--theme-text: var(--palette-carbon-black);
|
||||
--theme-text-muted: var(--palette-blue-slate);
|
||||
--theme-page: var(--palette-platinum);
|
||||
--theme-surface: color-mix(in srgb, var(--palette-platinum) 88%, var(--palette-powder-blue));
|
||||
--theme-surface-raised: var(--palette-platinum);
|
||||
--theme-surface-muted: color-mix(in srgb, var(--palette-platinum) 68%, var(--palette-powder-blue));
|
||||
--theme-border: var(--palette-powder-blue);
|
||||
--theme-primary: var(--palette-blue-slate);
|
||||
--theme-primary-hover: var(--palette-carbon-black);
|
||||
--theme-secondary: var(--palette-cool-steel);
|
||||
--theme-danger: var(--palette-carbon-black);
|
||||
--theme-focus: var(--palette-cool-steel);
|
||||
--theme-inverse-text: var(--palette-platinum);
|
||||
--theme-viewer: var(--palette-carbon-black);
|
||||
--theme-viewer-border: var(--palette-blue-slate);
|
||||
--theme-viewer-muted: var(--palette-powder-blue);
|
||||
--theme-shadow: 0 10px 28px color-mix(in srgb, var(--palette-carbon-black) 14%, transparent);
|
||||
|
||||
--q-primary: var(--palette-blue-slate);
|
||||
--q-secondary: var(--palette-cool-steel);
|
||||
--q-accent: var(--palette-powder-blue);
|
||||
--q-dark: var(--palette-carbon-black);
|
||||
--q-dark-page: var(--palette-carbon-black);
|
||||
--q-positive: var(--palette-cool-steel);
|
||||
--q-negative: var(--palette-carbon-black);
|
||||
--q-info: var(--palette-cool-steel);
|
||||
--q-warning: var(--palette-powder-blue);
|
||||
}
|
||||
|
||||
body,
|
||||
.q-layout,
|
||||
.q-page-container {
|
||||
color: var(--theme-text);
|
||||
background: var(--theme-page);
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: "Aptos", "Trebuchet MS", sans-serif;
|
||||
}
|
||||
|
||||
.q-card,
|
||||
.vibe-card {
|
||||
border: 1px solid var(--theme-border);
|
||||
color: var(--theme-text);
|
||||
background: var(--theme-surface-raised);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.vibe-card--error {
|
||||
border-color: var(--palette-carbon-black);
|
||||
color: var(--theme-inverse-text);
|
||||
background: var(--palette-carbon-black);
|
||||
}
|
||||
|
||||
.vibe-text-muted {
|
||||
color: var(--theme-text-muted);
|
||||
}
|
||||
|
||||
.vibe-separator {
|
||||
background: var(--theme-border);
|
||||
}
|
||||
|
||||
.vibe-status {
|
||||
border: 1px solid currentColor;
|
||||
}
|
||||
|
||||
.vibe-status--queued {
|
||||
color: var(--palette-blue-slate);
|
||||
background: var(--palette-platinum);
|
||||
}
|
||||
|
||||
.vibe-status--processing {
|
||||
color: var(--palette-carbon-black);
|
||||
background: var(--palette-powder-blue);
|
||||
}
|
||||
|
||||
.vibe-status--transcribed {
|
||||
color: var(--palette-carbon-black);
|
||||
background: var(--palette-cool-steel);
|
||||
}
|
||||
|
||||
.vibe-status--failed {
|
||||
color: var(--palette-platinum);
|
||||
background: var(--palette-carbon-black);
|
||||
}
|
||||
|
||||
.vibe-status--default {
|
||||
color: var(--palette-blue-slate);
|
||||
background: var(--theme-surface-muted);
|
||||
}
|
||||
|
||||
button:focus-visible,
|
||||
a:focus-visible,
|
||||
textarea:focus-visible,
|
||||
input:focus-visible,
|
||||
[tabindex="0"]:focus-visible {
|
||||
outline: 3px solid var(--theme-focus);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* Semantic utility classes for incremental migration away from inline hex styles. */
|
||||
.ui-text-primary {
|
||||
color: var(--theme-text);
|
||||
}
|
||||
|
||||
.ui-text-muted {
|
||||
color: var(--theme-text-muted);
|
||||
}
|
||||
|
||||
.ui-text-inverse {
|
||||
color: var(--theme-inverse-text);
|
||||
}
|
||||
|
||||
.ui-bg-page {
|
||||
background: var(--theme-page);
|
||||
}
|
||||
|
||||
.ui-bg-surface {
|
||||
background: var(--theme-surface);
|
||||
}
|
||||
|
||||
.ui-bg-surface-raised {
|
||||
background: var(--theme-surface-raised);
|
||||
}
|
||||
|
||||
.ui-bg-surface-muted {
|
||||
background: var(--theme-surface-muted);
|
||||
}
|
||||
|
||||
.ui-bg-viewer {
|
||||
background: var(--theme-viewer);
|
||||
}
|
||||
|
||||
.ui-bg-viewer-overlay {
|
||||
background: color-mix(in srgb, var(--theme-viewer) 50%, transparent);
|
||||
}
|
||||
|
||||
.ui-bg-viewer-overlay-soft {
|
||||
background: color-mix(in srgb, var(--theme-viewer) 40%, transparent);
|
||||
}
|
||||
|
||||
.ui-border-subtle {
|
||||
border-color: var(--theme-border);
|
||||
}
|
||||
|
||||
.ui-border-viewer {
|
||||
border-color: var(--theme-viewer-border);
|
||||
}
|
||||
|
||||
.ui-header-divider {
|
||||
border-bottom: 1px solid var(--theme-border);
|
||||
}
|
||||
|
||||
.ui-card-surface {
|
||||
border: 1px solid var(--theme-border);
|
||||
color: var(--theme-text);
|
||||
background: var(--theme-surface-raised);
|
||||
border-radius: 0.125rem;
|
||||
}
|
||||
|
||||
.ui-row-surface {
|
||||
border: 1px solid var(--theme-border);
|
||||
color: var(--theme-text);
|
||||
background: var(--theme-surface);
|
||||
border-radius: 0.125rem;
|
||||
}
|
||||
|
||||
.ui-note-box {
|
||||
border: 1px solid var(--theme-border);
|
||||
color: var(--theme-text);
|
||||
background: var(--theme-surface);
|
||||
border-radius: 0.125rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.ui-btn-primary {
|
||||
color: var(--theme-inverse-text);
|
||||
background: var(--theme-primary);
|
||||
}
|
||||
|
||||
.ui-btn-primary:hover {
|
||||
background: var(--theme-primary-hover);
|
||||
}
|
||||
|
||||
.ui-btn-secondary {
|
||||
color: var(--theme-primary);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.ui-btn-secondary:hover {
|
||||
color: var(--theme-primary-hover);
|
||||
}
|
||||
|
||||
.ui-link-primary {
|
||||
color: var(--theme-primary);
|
||||
}
|
||||
|
||||
.ui-link-primary:hover {
|
||||
color: var(--theme-primary-hover);
|
||||
}
|
||||
|
||||
.ui-text-accent {
|
||||
color: var(--theme-secondary);
|
||||
}
|
||||
|
||||
.ui-text-danger {
|
||||
color: var(--theme-danger);
|
||||
}
|
||||
|
||||
.ui-form-surface .q-field__control {
|
||||
background: var(--theme-surface-raised);
|
||||
}
|
||||
|
||||
.ui-form-surface .q-field__native,
|
||||
.ui-form-surface .q-field__input {
|
||||
color: var(--theme-text);
|
||||
}
|
||||
|
||||
.ui-form-surface .q-field__marginal {
|
||||
color: var(--theme-text-muted);
|
||||
}
|
||||
|
||||
.ui-page-header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.ui-page-title {
|
||||
color: var(--theme-text);
|
||||
font-family: "Iowan Old Style", "Palatino Linotype", "Book Antiqua", Palatino, serif;
|
||||
font-size: 1.75rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.ui-page-subtitle {
|
||||
color: var(--theme-text-muted);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
/* Table Archival Theme Bridge */
|
||||
.ui-table {
|
||||
border: 1px solid var(--theme-border);
|
||||
color: var(--theme-text);
|
||||
background: var(--theme-surface-raised);
|
||||
border-radius: 0.125rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.ui-table .q-table {
|
||||
color: var(--theme-text);
|
||||
}
|
||||
|
||||
.ui-table .q-table th,
|
||||
.ui-table-header {
|
||||
color: var(--theme-inverse-text) !important;
|
||||
background-color: var(--theme-primary) !important;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.ui-table .q-table td {
|
||||
border-bottom: 1px solid var(--theme-border) !important;
|
||||
color: var(--theme-text);
|
||||
}
|
||||
|
||||
.ui-table .q-table tbody tr:hover {
|
||||
background-color: var(--theme-surface) !important;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.ui-table-body {
|
||||
color: var(--theme-text);
|
||||
}
|
||||
|
||||
/* App Shell */
|
||||
.app-shell {
|
||||
min-height: 64px;
|
||||
padding: 0.75rem 2rem;
|
||||
border-bottom: 1px solid var(--theme-border);
|
||||
color: var(--theme-text);
|
||||
background: var(--theme-surface-raised);
|
||||
}
|
||||
|
||||
.app-shell__inner {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(180px, 1fr) auto minmax(180px, 1fr);
|
||||
align-items: center;
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.app-shell__brand,
|
||||
.app-shell__actions {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.app-shell__brand {
|
||||
gap: 0.75rem;
|
||||
color: var(--theme-text);
|
||||
font-family: Georgia, serif;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.app-shell__brand-mark {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--theme-inverse-text);
|
||||
background: transparent;
|
||||
font-family: "Trebuchet MS", sans-serif;
|
||||
font-size: 0.72rem;
|
||||
}
|
||||
|
||||
.app-shell__nav {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.app-shell__nav-item {
|
||||
min-height: 40px;
|
||||
color: var(--theme-text-muted);
|
||||
}
|
||||
|
||||
.app-shell__nav-item--active {
|
||||
color: var(--theme-primary-hover);
|
||||
border-bottom: 3px solid var(--theme-primary);
|
||||
}
|
||||
|
||||
.app-shell__actions {
|
||||
justify-content: flex-end;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.app-shell__save-state {
|
||||
color: var(--theme-text-muted);
|
||||
font-size: 0.82rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.app-shell {
|
||||
padding-inline: 0.75rem;
|
||||
}
|
||||
|
||||
.app-shell__inner {
|
||||
grid-template-columns: 1fr auto;
|
||||
}
|
||||
|
||||
.app-shell__nav {
|
||||
grid-column: 1 / -1;
|
||||
grid-row: 2;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.app-shell__brand-name,
|
||||
.app-shell__save-state {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user