From 339a3293855c8786a7b5f195e19d86e7252eb8fc Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Sat, 21 Nov 2026 01:05:59 +0530 Subject: [PATCH 1/2] feat(api): add settings and first-run bootstrap --- docs/ARCHITECTURE.md | 3 +- docs/TASKS.md | 6 +- src/tts/__main__.py | 109 +++++++++++++- src/tts/api/__init__.py | 10 +- src/tts/api/dependencies.py | 60 ++++++++ src/tts/api/routes/generations.py | 35 +---- src/tts/api/routes/health.py | 4 +- src/tts/api/routes/settings.py | 89 +++++++++++ src/tts/api/routes/voices.py | 6 +- src/tts/api/schemas.py | 2 + src/tts/app.py | 25 +++- .../integration/test_api_generations_flow.py | 2 - tests/unit/test_api_generations_routes.py | 3 +- tests/unit/test_api_settings.py | 139 ++++++++++++++++++ tests/unit/test_api_uploads.py | 2 +- tests/unit/test_api_voices.py | 2 +- tests/unit/test_cli.py | 97 ++++++++++++ tests/unit/test_errors.py | 6 +- 18 files changed, 539 insertions(+), 61 deletions(-) create mode 100644 src/tts/api/dependencies.py create mode 100644 src/tts/api/routes/settings.py create mode 100644 tests/unit/test_api_settings.py create mode 100644 tests/unit/test_cli.py diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 25a3092..ca766c7 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -181,6 +181,7 @@ tts/ │ ├── api/ │ │ ├── __init__.py # ROUTERS list (append-only registry) │ │ ├── errors.py # AppError exception + error envelope + codes +│ │ ├── dependencies.py # app-scoped DAL and jobs construction │ │ ├── schemas.py # pydantic request/response models (mirrors §9) │ │ └── routes/ │ │ ├── health.py # GET /api/health @@ -716,7 +717,7 @@ Format: **ID** — description · files · deps · spec refs · acceptance crite **P2 (parallel after P1; each route file has one owner)** - **T2.1** — Uploads + voices routes: `api/routes/uploads.py`, `api/routes/voices.py`. Deps: T0.3, T1.1. Refs: §9.2. AC: upload happy path returns text identical to file bytes decoded; `.pdf` → 415 with the accepted-types message; >2 MB → 413; non-UTF-8/16 → 415; preview endpoint returns valid WAV; empty store → 409 `NO_VOICES_INSTALLED`. - **T2.2** — Generations routes: `api/routes/generations.py` (all endpoints of §9.2 for this resource incl. audio, subtitles, events, cancel, delete). Deps: T0.3, T1.6. Refs: §9.2, §10. AC: full integration — create returns 202; SSE replays state on reconnect; out-of-range rate → 422 `OUT_OF_RANGE` with details; empty text → 422 `EMPTY_INPUT`; unknown id → 404; audio/subtitles before success → 409 `GENERATION_NOT_READY`; bad format → 400; `Content-Disposition` naming matches the §9.2 rule; delete of a running job → 409. -- **T2.3** — Settings route + first-run bootstrap: `api/routes/settings.py`; `jobs/manager.py:bootstrap` (online-once default-voice download with offline fallback of §10.4). Deps: T0.3, T1.6. Refs: §9.2 settings, §10.4. AC: GET seeds defaults lazily; PUT partial update persists only given keys; unknown voice in PUT → 422; bootstrap with no network leaves app serving and health reporting 0 voices. +- **T2.3** — Settings route + first-run bootstrap: `api/routes/settings.py`, shared app services in `api/dependencies.py`, `api/__init__.py` router registration, `api/schemas.py`, `api/routes/{health,voices,generations}.py`, `app.py` lifespan, and `__main__.py` CLI. Reuse `jobs/manager.py:bootstrap` (online-once default-voice download with offline fallback of §10.4). Deps: T0.3, T1.6. Refs: §9.2 settings, §9.3 CLI, §10.4. AC: GET seeds defaults lazily; PUT partial update persists only given keys; unknown voice in PUT → 422; persisted default is reflected by health and voice-list responses; `tts` serves the local app and installs voices; bootstrap with no network leaves app serving and health reporting 0 voices. **P3 (parallel with P2; frontend runs in mock mode)** - **T3.1** — App shell + input + voice + generate: `App.tsx`, `ErrorBanner`, `InputPanel`, `VoicePanel`, `GenerateBar` + context wiring (context itself was created in T0.5; T3.1 is its only further editor). Deps: T0.5. Refs: §12. AC: paste + upload render text; unsupported file shows accepted-types message without generating (AC3); empty-text generate shows validation message without a request (AC4); sliders clamp into §9.2 ranges and show numeric values (AC6); generate button disabled with explanation when 0 voices; voice preview plays. diff --git a/docs/TASKS.md b/docs/TASKS.md index d41fac6..8467ea9 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -30,7 +30,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| _(empty — next up: T2.3 on branch `arch/tts/t2.3`, pending review)_ | | | | | +| T2.3 | Settings route + first-run bootstrap | `arch/tts/t2.3` | 196 unit + 16 integration; Ruff; strict mypy; 34 Vitest; ESLint; TypeScript; Prettier (CRLF); Vite build; `git diff --check` | doing | ## Remaining @@ -47,7 +47,6 @@ _All P1 tasks done._ | ID | Task | Files | Deps | Acceptance criteria (summary) | |---|---|---|---|---| | T2.1 | Uploads + voices routes | `src/tts/api/routes/uploads.py`, `voices.py` | T0.3, T1.1 | Upload validation, preview WAV, no-voice response | -| T2.3 | Settings route + first-run bootstrap | `src/tts/api/routes/settings.py`, `src/tts/jobs/manager.py` | T0.3, T1.6 | Lazy defaults, partial persistence, invalid voice rejection, offline startup | ### P3 — UI against contracts @@ -115,7 +114,7 @@ _All P1 tasks done._ - T1.6 decision: a generation that renders **no audio at all** fails with `ENGINE_ERROR` ("The speech engine produced no audio for this text.") instead of succeeding with a valid but empty WAV that no player can use (§1 "degrade honestly"). The API still rejects empty input with 422 `EMPTY_INPUT`, so this only guards text that the engine renders as silence. - T1.6 test layout: unit and integration test files use distinct basenames (`tests/unit/test_jobs_manager.py`, `tests/unit/test_jobs_sse.py`, `tests/integration/test_jobs_pipeline.py`) because a bare `pytest` run fails when `tests/unit` and `tests/integration` share a basename and neither directory is a package (see the T1.2 note). - T1.6 environment note: the integration suite renders with the real voice but keeps the database and the audio in a `tmp_path`; the manager points the voice store at its own data directory, so the fixture calls `ensure_data_dirs()` again with the real settings afterwards. `pytest` needs `--basetemp .venv/ptmp-*` on this machine (the default system temp directory is inaccessible — see the T0.2 note). -- T2.1 decisions: both routes call `voices.store.ensure_data_dirs(settings)` lazily (idempotent) so they work before T2.3 wires startup bootstrap — T2.3 keeps its own startup call. `GET /api/voices` returns `settings.default_voice_id` (config `TTS_DEFAULT_VOICE`) as `defaultVoiceId`; T2.3 owns the persisted settings, so it should decide whether to source this field from `dal.get_settings()` instead — frozen downstream for T2.3/T3.1. The `.txt` extension check is case-insensitive; content-type accepts `text/*` and `application/octet-stream` per §9.2. Missing form field maps to the skeleton's 422 `OUT_OF_RANGE` with `{field, reason}` (T0.3 note), not a custom code. `file: Annotated[UploadFile, File(...)]` is used instead of a default value to satisfy Ruff B008. +- T2.1 decisions: both routes call `voices.store.ensure_data_dirs(settings)` lazily (idempotent) so they work before T2.3 wires startup bootstrap — T2.3 keeps its own startup call. `GET /api/voices` originally returned `settings.default_voice_id`; T2.3 resolves this to the persisted DAL default so the response follows `PUT /api/settings`. The `.txt` extension check is case-insensitive; content-type accepts `text/*` and `application/octet-stream` per §9.2. Missing form field maps to the skeleton's 422 `OUT_OF_RANGE` with `{field, reason}` (T0.3 note), not a custom code. `file: Annotated[UploadFile, File(...)]` is used instead of a default value to satisfy Ruff B008. - T2.1 shared file: appended `uploads.router` and `voices.router` to `ROUTERS` in `src/tts/api/__init__.py` (§14.4 append-only registry). Dependent tasks: T2.2, T2.3 add their own router entries. - T2.1 test layout: unit tests `tests/unit/test_api_uploads.py` and `tests/unit/test_api_voices.py`, integration test `tests/integration/test_api_voices_preview.py` (unique basenames; see the T1.2 note). Preview error paths are unit-tested with monkeypatched `store.preview_wav`; the real-engine WAV check is integration-only. - T2.2 decisions: `app.state` had only `settings`, so the route lazily attaches `dal` (`Dal(settings.data_dir, history_limit=settings.history_limit)`) and `jobs` (`JobManager`) under a lock; injected instances win. **T2.3 owns startup wiring** and should reuse these `app.state` entries (and close them at shutdown) rather than creating duplicates. Omitted `voiceId`/`rate`/`volume` come from `dal.seed_settings(settings.default_voice_id)` + `get_settings()` (§8.2 lazy seeding is idempotent, so this does not conflict with T2.3). Empty-store is checked before unknown-voice, per the T1.6 contract, so the no-voice remedy wins. An already-`cancelling` row answers 200 `status: cancelled` while jobs still reports `cancelling` (T1.6 ambiguity). `text` is null only for `queued`/`running`/`cancelling`; failed/cancelled rows expose the full input (§9.2 wording). A succeeded row whose audio path is missing/outside `data_dir/generations` answers 409 `GENERATION_NOT_READY` (§9.1 has no specific code for that inconsistent state). `sourceType` is always `"text"` because the §9.2 request body has no `sourceType` field; uploaded text is generated only after the user reviews it in the input view. @@ -123,3 +122,4 @@ _All P1 tasks done._ - T2.2 shared file: appended `generations.router` to `ROUTERS` in `src/tts/api/__init__.py` (§14.4 append-only). Dependent task: T2.3 adds its own `settings.router` entry. - T2.2 SSE: sends `RETRY_LINE` once, then `subscriber.events()` frames until the terminal event; `Cache-Control: no-cache` and `X-Accel-Buffering: no` mitigate R6. No explicit unsubscribe on client disconnect — the manager closes the subscriber queue at the terminal event, so no stream registration leaks. Unknown ids (malformed or well-formed) are 404 before the stream opens. - T2.2 test layout: `tests/unit/test_api_generations_routes.py` and `tests/integration/test_api_generations_flow.py` (unique basenames; see the T1.2 note). Unit tests use a fake job manager with a real DAL so no engine is imported; the integration test runs a real generation against `en_US-lessac-medium` and verifies SSE replay, detail, WAV, SRT/VTT, and delete. +- T2.3 scope resolution: expanded §14.2 to include app lifespan/service wiring, CLI serving and voice installation, and persisted default-voice responses in health and voice-list routes; the tracker note had assigned startup wiring to T2.3 while the original owned-file list omitted it. `jobs.manager.bootstrap` already existed from T1.6 and is reused. Unit tests disable automatic bootstrap except for the explicit offline-startup case. On this Windows checkout, `npm run format:check` assumes LF while tracked frontend files are checked out as CRLF (`core.autocrlf=true`); `npm run format:check -- --end-of-line crlf` passes without changing files. diff --git a/src/tts/__main__.py b/src/tts/__main__.py index dc36a73..c8bc1ce 100644 --- a/src/tts/__main__.py +++ b/src/tts/__main__.py @@ -1,23 +1,116 @@ -"""Command-line entry points for tts.""" +"""Command-line entry points for running tts and installing Piper voices.""" from __future__ import annotations import argparse +import ipaddress +import socket +import sys +import webbrowser +from dataclasses import replace + +import uvicorn from tts import __version__ +from tts.app import create_app +from tts.config import Settings, configure_logging +from tts.voices.store import ensure_data_dirs, install_voice -def main() -> None: - """Print the installed application version.""" +class _BrowserServer(uvicorn.Server): + """Open the browser only after uvicorn has bound and started serving.""" + + def __init__(self, config: uvicorn.Config, browser_url: str, open_browser: bool) -> None: + super().__init__(config) + self._browser_url = browser_url + self._open_browser = open_browser + + async def startup(self, sockets: list[socket.socket] | None = None) -> None: + await super().startup(sockets=sockets) + if self.started and self._open_browser: + webbrowser.open(self._browser_url) + + +def _is_loopback_host(host: str) -> bool: + """Accept localhost names and literal loopback IP addresses.""" + if host.lower() == "localhost": + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +def _browser_host(host: str) -> str: + """Use a browser-reachable host when uvicorn binds to every interface.""" + if host in {"0.0.0.0", "::"}: + return "127.0.0.1" + return host + + +def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="tts") parser.add_argument("--version", action="version", version=__version__) - parser.parse_args() - print(f"tts {__version__}") + parser.add_argument("--host", help="bind address (default: TTS_HOST or 127.0.0.1)") + parser.add_argument("--port", type=int, help="port (default: TTS_PORT or 8321)") + parser.add_argument("--no-open", action="store_true", help="do not open a browser") + parser.add_argument( + "--i-know-this-is-lan", + action="store_true", + help="allow binding to a non-loopback address", + ) + commands = parser.add_subparsers(dest="command") + add_voice_parser = commands.add_parser("add-voice", help="download a Piper voice") + add_voice_parser.add_argument("name", help="Piper voice name to install") + return parser + + +def _serve(args: argparse.Namespace, parser: argparse.ArgumentParser) -> None: + settings = Settings.load() + host = args.host or settings.host + port = args.port if args.port is not None else settings.port + if not _is_loopback_host(host) and not args.i_know_this_is_lan: + parser.error( + "refusing a non-loopback bind; pass --i-know-this-is-lan to expose tts on your LAN" + ) + + settings = replace(settings, host=host, port=port) + configure_logging(settings) + browser_host = _browser_host(host) + if ":" in browser_host: + browser_host = f"[{browser_host}]" + url = f"http://{browser_host}:{port}" + config = uvicorn.Config(create_app(settings), host=host, port=port, log_config=None) + _BrowserServer(config, url, open_browser=not args.no_open).run() + + +def _install(name: str) -> None: + settings = Settings.load() + ensure_data_dirs(settings) + try: + voice_id = install_voice(name) + except Exception as error: + print(f"Could not install voice {name!r}: {error}", file=sys.stderr) + raise SystemExit(1) from error + print(voice_id) + + +def main() -> None: + """Start the local web application or run the ``add-voice`` subcommand.""" + parser = _parser() + args = parser.parse_args() + if args.command == "add-voice": + _install(args.name) + return + _serve(args, parser) def add_voice() -> None: - """Provide the voice-install command entry point.""" + """Entry point retained for the standalone ``tts.add-voice`` script.""" parser = argparse.ArgumentParser(prog="tts.add-voice") parser.add_argument("name", help="Piper voice name to install") - parser.parse_args() - parser.error("voice installation is not available until the voice store is initialized") + _install(parser.parse_args().name) + + +if __name__ == "__main__": + main() diff --git a/src/tts/api/__init__.py b/src/tts/api/__init__.py index 4851a9f..8f13b62 100644 --- a/src/tts/api/__init__.py +++ b/src/tts/api/__init__.py @@ -8,6 +8,12 @@ from fastapi import APIRouter -from tts.api.routes import generations, health, uploads, voices +from tts.api.routes import generations, health, settings, uploads, voices -ROUTERS: list[APIRouter] = [health.router, uploads.router, voices.router, generations.router] +ROUTERS: list[APIRouter] = [ + health.router, + uploads.router, + voices.router, + generations.router, + settings.router, +] diff --git a/src/tts/api/dependencies.py b/src/tts/api/dependencies.py new file mode 100644 index 0000000..695e1b0 --- /dev/null +++ b/src/tts/api/dependencies.py @@ -0,0 +1,60 @@ +"""App-scoped service construction shared by API routes and lifespan.""" + +from __future__ import annotations + +import threading +from typing import cast + +from fastapi import FastAPI, Request + +from tts.config import Settings +from tts.history.dal import Dal +from tts.jobs.manager import JobManager + +_INIT_LOCK = threading.Lock() + + +def initialize_services(app: FastAPI) -> tuple[Dal, JobManager]: + """Create missing app-scoped services while preserving injected instances.""" + with _INIT_LOCK: + settings: Settings = app.state.settings + dal = getattr(app.state, "dal", None) + if dal is None: + dal = Dal(settings.data_dir, history_limit=settings.history_limit) + app.state.dal = dal + + jobs = getattr(app.state, "jobs", None) + if jobs is None: + jobs = JobManager(dal, settings) + app.state.jobs = jobs + return cast(Dal, dal), cast(JobManager, jobs) + + +def get_dal(request: Request) -> Dal: + """Return the app's shared DAL, creating services if a route runs standalone.""" + dal = getattr(request.app.state, "dal", None) + if dal is None: + dal, _ = initialize_services(request.app) + return cast(Dal, dal) + + +def get_jobs(request: Request) -> JobManager: + """Return the app's shared job manager.""" + jobs = getattr(request.app.state, "jobs", None) + if jobs is None: + _, jobs = initialize_services(request.app) + return cast(JobManager, jobs) + + +def close_services(app: FastAPI) -> None: + """Stop app-scoped services in dependency order.""" + jobs = getattr(app.state, "jobs", None) + dal = getattr(app.state, "dal", None) + close_jobs = getattr(jobs, "close", None) + close_dal = getattr(dal, "close", None) + try: + if callable(close_jobs): + close_jobs() + finally: + if callable(close_dal): + close_dal() diff --git a/src/tts/api/routes/generations.py b/src/tts/api/routes/generations.py index 94c20dd..8475e88 100644 --- a/src/tts/api/routes/generations.py +++ b/src/tts/api/routes/generations.py @@ -11,7 +11,6 @@ import json import logging import re -import threading from collections.abc import Iterator from datetime import UTC, datetime from pathlib import Path @@ -20,6 +19,7 @@ from fastapi import APIRouter, Query, Request from fastapi.responses import FileResponse, PlainTextResponse, Response, StreamingResponse +from tts.api.dependencies import get_dal, get_jobs from tts.api.errors import AppError from tts.api.schemas import ( CueSchema, @@ -59,42 +59,17 @@ ) _RATE_RANGE = (0.5, 2.0) _VOLUME_RANGE = (0.0, 1.0) -_INIT_LOCK = threading.Lock() -"""Guards the lazy creation of app-scoped DAL and job manager (see §14.2 T2.3).""" - - # -- app-scoped services ----------------------------------------------------- def _dal(request: Request) -> Dal: - """Return the app's DAL, creating it from settings on first use. - - T2.3 owns startup wiring, so this route stays self-contained until then by - attaching the shared services to ``app.state`` lazily. An injected - ``app.state.dal`` (tests, later startup code) always wins. - """ - dal = getattr(request.app.state, "dal", None) - if dal is None: - with _INIT_LOCK: - dal = getattr(request.app.state, "dal", None) - if dal is None: - settings: Settings = request.app.state.settings - dal = Dal(settings.data_dir, history_limit=settings.history_limit) - request.app.state.dal = dal - return cast(Dal, dal) + """Return the shared application DAL.""" + return get_dal(request) def _jobs(request: Request) -> JobManager: - """Return the app's job manager, creating it from settings on first use.""" - jobs = getattr(request.app.state, "jobs", None) - if jobs is None: - with _INIT_LOCK: - jobs = getattr(request.app.state, "jobs", None) - if jobs is None: - settings: Settings = request.app.state.settings - jobs = JobManager(_dal(request), settings) - request.app.state.jobs = jobs - return cast(JobManager, jobs) + """Return the shared application job manager.""" + return get_jobs(request) # -- small helpers ----------------------------------------------------------- diff --git a/src/tts/api/routes/health.py b/src/tts/api/routes/health.py index 14b4576..6279f82 100644 --- a/src/tts/api/routes/health.py +++ b/src/tts/api/routes/health.py @@ -7,6 +7,7 @@ from fastapi import APIRouter, Request from tts import __version__ +from tts.api.dependencies import get_dal from tts.api.schemas import HealthResponse from tts.config import Settings @@ -25,8 +26,9 @@ def _count_installed_voices(voices_dir: Path) -> int: def get_health(request: Request) -> HealthResponse: """Return process health plus the voice count used by the no-voice UI.""" settings: Settings = request.app.state.settings + default_settings = get_dal(request).seed_settings(settings.default_voice_id) return HealthResponse( version=__version__, voices_installed=_count_installed_voices(settings.data_dir / "voices"), - default_voice_id=settings.default_voice_id, + default_voice_id=str(default_settings["defaultVoiceId"]), ) diff --git a/src/tts/api/routes/settings.py b/src/tts/api/routes/settings.py new file mode 100644 index 0000000..952672e --- /dev/null +++ b/src/tts/api/routes/settings.py @@ -0,0 +1,89 @@ +"""Persisted speech settings endpoints (ARCHITECTURE.md section 9.2).""" + +from __future__ import annotations + +from typing import Any + +from fastapi import APIRouter, Request + +from tts.api.dependencies import get_dal +from tts.api.errors import AppError +from tts.api.schemas import SettingsPatch, SettingsResponse +from tts.config import Settings +from tts.voices import store + +router = APIRouter(tags=["settings"]) + +_RATE_RANGE = (0.5, 2.0) +_VOLUME_RANGE = (0.0, 1.0) + + +def _current_settings(request: Request) -> dict[str, Any]: + """Seed and return the complete settings object, preserving stored values.""" + settings: Settings = request.app.state.settings + store.ensure_data_dirs(settings) + return get_dal(request).seed_settings(settings.default_voice_id) + + +def _response(values: dict[str, Any]) -> SettingsResponse: + return SettingsResponse( + default_voice_id=str(values["defaultVoiceId"]), + rate=float(values["rate"]), + volume=float(values["volume"]), + ) + + +@router.get("/settings", response_model=SettingsResponse, summary="Read speech settings") +def read_settings(request: Request) -> SettingsResponse: + """Return persisted settings, seeding defaults on first read.""" + return _response(_current_settings(request)) + + +@router.put("/settings", response_model=SettingsResponse, summary="Update speech settings") +def update_settings(payload: SettingsPatch, request: Request) -> SettingsResponse: + """Validate and persist only the settings fields supplied by the caller.""" + settings: Settings = request.app.state.settings + store.ensure_data_dirs(settings) + patch: dict[str, str | float | None] = payload.model_dump( + by_alias=True, + exclude_unset=True, + ) + + for field, value in patch.items(): + if value is None: + raise AppError( + "OUT_OF_RANGE", + 422, + f"{field} cannot be null.", + {"field": field, "reason": "a value is required"}, + ) + + if "defaultVoiceId" in patch: + voice_id = str(patch["defaultVoiceId"]) + if voice_id not in {voice.id for voice in store.list_voices()}: + raise AppError( + "VOICE_NOT_FOUND", + 422, + f"Voice {voice_id!r} is not installed.", + ) + + for field, limits in (("rate", _RATE_RANGE), ("volume", _VOLUME_RANGE)): + if field not in patch: + continue + raw_value = payload.rate if field == "rate" else payload.volume + assert raw_value is not None + value = float(raw_value) + minimum, maximum = limits + if not minimum <= value <= maximum: + label = "Rate" if field == "rate" else "Volume" + raise AppError( + "OUT_OF_RANGE", + 422, + f"{label} must be between {minimum} and {maximum}.", + {"field": field, "min": minimum, "max": maximum, "value": value}, + ) + patch[field] = value + + dal = get_dal(request) + dal.seed_settings(settings.default_voice_id) + return _response(dal.put_settings(patch)) diff --git a/src/tts/api/routes/voices.py b/src/tts/api/routes/voices.py index 430c4b5..a189403 100644 --- a/src/tts/api/routes/voices.py +++ b/src/tts/api/routes/voices.py @@ -6,6 +6,7 @@ from fastapi import APIRouter, Request, Response +from tts.api.dependencies import get_dal from tts.api.errors import AppError from tts.api.schemas import Voice, VoiceList, VoicePreviewRequest from tts.config import Settings @@ -30,9 +31,10 @@ def _settings(request: Request) -> Settings: @router.get("/voices", response_model=VoiceList, summary="List installed voices") def list_installed_voices(request: Request) -> VoiceList: - """List local voices sorted by language then id, with the configured default.""" + """List local voices sorted by language then id, with the persisted default.""" settings = _settings(request) voices = store.list_voices() + default_settings = get_dal(request).seed_settings(settings.default_voice_id) return VoiceList( items=[ Voice( @@ -45,7 +47,7 @@ def list_installed_voices(request: Request) -> VoiceList: for voice in voices ], total=len(voices), - default_voice_id=settings.default_voice_id, + default_voice_id=str(default_settings["defaultVoiceId"]), ) diff --git a/src/tts/api/schemas.py b/src/tts/api/schemas.py index 93d9dd4..7fdf457 100644 --- a/src/tts/api/schemas.py +++ b/src/tts/api/schemas.py @@ -170,6 +170,8 @@ class SettingsResponse(ContractModel): class SettingsPatch(ContractModel): + model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True, extra="forbid") + default_voice_id: str | None = None rate: float | None = None volume: float | None = None diff --git a/src/tts/app.py b/src/tts/app.py index e00a6dd..00c2032 100644 --- a/src/tts/app.py +++ b/src/tts/app.py @@ -15,19 +15,29 @@ from tts import __version__ from tts.api import ROUTERS +from tts.api.dependencies import close_services, initialize_services from tts.api.errors import AppError, error_envelope from tts.config import Settings +from tts.jobs.manager import bootstrap +from tts.voices.store import ensure_data_dirs logger = logging.getLogger(__name__) @asynccontextmanager async def _lifespan(app: FastAPI) -> AsyncIterator[None]: - """Startup hook placeholder; later tasks attach bootstrap work here.""" + """Initialize app services and tolerate an unavailable first-run download.""" settings: Settings = app.state.settings logger.info("tts %s starting on %s:%s", __version__, settings.host, settings.port) - yield - logger.info("tts stopped") + ensure_data_dirs(settings) + dal, _ = initialize_services(app) + try: + if app.state.bootstrap_on_startup: + bootstrap(settings, dal) + yield + finally: + close_services(app) + logger.info("tts stopped") def _frontend_dist_dir() -> Path | None: @@ -89,10 +99,15 @@ async def _handle_http_exception(request: Request, exc: Exception) -> JSONRespon ) -def create_app(settings: Settings | None = None) -> FastAPI: - """Build the application; tests may inject explicit settings.""" +def create_app( + settings: Settings | None = None, + *, + bootstrap_on_startup: bool = True, +) -> FastAPI: + """Build the application; tests may inject settings and control bootstrap.""" app = FastAPI(title="tts", version=__version__, lifespan=_lifespan) app.state.settings = settings if settings is not None else Settings.load() + app.state.bootstrap_on_startup = bootstrap_on_startup for router in ROUTERS: app.include_router(router, prefix="/api") diff --git a/tests/integration/test_api_generations_flow.py b/tests/integration/test_api_generations_flow.py index 998962d..7d5fb99 100644 --- a/tests/integration/test_api_generations_flow.py +++ b/tests/integration/test_api_generations_flow.py @@ -51,8 +51,6 @@ def env(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Any]: app.state.jobs = jobs with TestClient(app) as client: yield client, dal, jobs - jobs.close() - dal.close() def test_create_stream_detail_media_and_delete(env: Any) -> None: diff --git a/tests/unit/test_api_generations_routes.py b/tests/unit/test_api_generations_routes.py index 6b2d040..3a3f54e 100644 --- a/tests/unit/test_api_generations_routes.py +++ b/tests/unit/test_api_generations_routes.py @@ -62,7 +62,7 @@ class Env: def _app(settings: Settings, dal: Dal, jobs: FakeJobs) -> FastAPI: - app = create_app(settings) + app = create_app(settings, bootstrap_on_startup=False) app.state.dal = dal app.state.jobs = jobs return app @@ -86,7 +86,6 @@ def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any: app = _app(settings, dal, jobs) with TestClient(app) as client: yield Env(client=client, app=app, dal=dal, jobs=jobs, settings=settings) - dal.close() def _succeeded_row(env: Env, text: str = "Hello world this is a test") -> tuple[str, Path]: diff --git a/tests/unit/test_api_settings.py b/tests/unit/test_api_settings.py new file mode 100644 index 0000000..55e4695 --- /dev/null +++ b/tests/unit/test_api_settings.py @@ -0,0 +1,139 @@ +"""Tests for settings persistence and first-run bootstrap.""" + +from __future__ import annotations + +import shutil +from pathlib import Path + +import pytest +from fastapi.testclient import TestClient + +from tts.app import create_app +from tts.config import Settings + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "voices" +DEFAULT_VOICE_ID = "de_DE-thorsten-low" +OTHER_VOICE_ID = "en_US-alpha-medium" + + +def _settings(tmp_path: Path) -> Settings: + return Settings( + host="127.0.0.1", + port=8321, + data_dir=tmp_path, + max_input_chars=50_000, + history_limit=20, + log_level="INFO", + default_voice_id=DEFAULT_VOICE_ID, + ) + + +def _install_fixture(voices_dir: Path, voice_id: str) -> None: + shutil.copyfile(FIXTURES / f"{voice_id}.onnx.json", voices_dir / f"{voice_id}.onnx.json") + (voices_dir / f"{voice_id}.onnx").touch() + + +def test_settings_seed_lazily_and_partial_updates_persist(tmp_path: Path) -> None: + voices_dir = tmp_path / "voices" + voices_dir.mkdir() + _install_fixture(voices_dir, DEFAULT_VOICE_ID) + _install_fixture(voices_dir, OTHER_VOICE_ID) + app = create_app(_settings(tmp_path), bootstrap_on_startup=False) + + with TestClient(app) as client: + seeded = client.get("/api/settings") + assert seeded.status_code == 200 + assert seeded.json() == { + "defaultVoiceId": DEFAULT_VOICE_ID, + "rate": 1.0, + "volume": 1.0, + } + + updated = client.put("/api/settings", json={"rate": 1.4}) + assert updated.status_code == 200 + assert updated.json() == { + "defaultVoiceId": DEFAULT_VOICE_ID, + "rate": 1.4, + "volume": 1.0, + } + + updated_voice = client.put("/api/settings", json={"defaultVoiceId": OTHER_VOICE_ID}) + assert updated_voice.status_code == 200 + assert updated_voice.json() == { + "defaultVoiceId": OTHER_VOICE_ID, + "rate": 1.4, + "volume": 1.0, + } + assert client.get("/api/settings").json() == updated_voice.json() + assert client.get("/api/health").json()["defaultVoiceId"] == OTHER_VOICE_ID + assert client.get("/api/voices").json()["defaultVoiceId"] == OTHER_VOICE_ID + + with TestClient(create_app(_settings(tmp_path), bootstrap_on_startup=False)) as reopened: + assert reopened.get("/api/settings").json() == updated_voice.json() + + +def test_settings_update_rejects_unknown_voice_without_persisting(tmp_path: Path) -> None: + voices_dir = tmp_path / "voices" + voices_dir.mkdir() + _install_fixture(voices_dir, DEFAULT_VOICE_ID) + + with TestClient(create_app(_settings(tmp_path), bootstrap_on_startup=False)) as client: + response = client.put("/api/settings", json={"defaultVoiceId": "en_US-missing"}) + + assert response.status_code == 422 + assert response.json()["error"]["code"] == "VOICE_NOT_FOUND" + assert client.get("/api/settings").json()["defaultVoiceId"] == DEFAULT_VOICE_ID + + +@pytest.mark.parametrize( + ("patch", "field", "minimum", "maximum"), + [ + ({"rate": 0.49}, "rate", 0.5, 2.0), + ({"rate": 2.01}, "rate", 0.5, 2.0), + ({"volume": -0.01}, "volume", 0.0, 1.0), + ({"volume": 1.01}, "volume", 0.0, 1.0), + ], +) +def test_settings_update_rejects_out_of_range_values( + tmp_path: Path, + patch: dict[str, float], + field: str, + minimum: float, + maximum: float, +) -> None: + with TestClient(create_app(_settings(tmp_path), bootstrap_on_startup=False)) as client: + response = client.put("/api/settings", json=patch) + + assert response.status_code == 422 + assert response.json()["error"]["code"] == "OUT_OF_RANGE" + assert response.json()["error"]["details"]["field"] == field + assert response.json()["error"]["details"]["min"] == minimum + assert response.json()["error"]["details"]["max"] == maximum + + +def test_settings_update_rejects_extra_and_null_values(tmp_path: Path) -> None: + with TestClient(create_app(_settings(tmp_path), bootstrap_on_startup=False)) as client: + extra = client.put("/api/settings", json={"unknown": 1}) + null_rate = client.put("/api/settings", json={"rate": None}) + + assert extra.status_code == 422 + assert extra.json()["error"]["code"] == "OUT_OF_RANGE" + assert null_rate.status_code == 422 + assert null_rate.json()["error"]["code"] == "OUT_OF_RANGE" + + +def test_offline_first_run_keeps_app_serving_without_voices( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail_install(name: str) -> str: + raise OSError("network unavailable") + + monkeypatch.setattr("tts.jobs.manager.install_voice", fail_install) + with TestClient(create_app(_settings(tmp_path))) as client: + health = client.get("/api/health") + + assert health.status_code == 200 + assert health.json()["status"] == "ok" + assert health.json()["voicesInstalled"] == 0 + assert health.json()["defaultVoiceId"] == DEFAULT_VOICE_ID diff --git a/tests/unit/test_api_uploads.py b/tests/unit/test_api_uploads.py index dbf4bbc..94f0def 100644 --- a/tests/unit/test_api_uploads.py +++ b/tests/unit/test_api_uploads.py @@ -25,7 +25,7 @@ def _settings(tmp_path: Path) -> Settings: def _client(tmp_path: Path) -> TestClient: - return TestClient(create_app(_settings(tmp_path))) + return TestClient(create_app(_settings(tmp_path), bootstrap_on_startup=False)) def test_upload_returns_decoded_text_and_size(tmp_path: Path) -> None: diff --git a/tests/unit/test_api_voices.py b/tests/unit/test_api_voices.py index 7d28db8..4c3d264 100644 --- a/tests/unit/test_api_voices.py +++ b/tests/unit/test_api_voices.py @@ -31,7 +31,7 @@ def _settings(tmp_path: Path) -> Settings: def _client(tmp_path: Path) -> TestClient: settings = _settings(tmp_path) store.ensure_data_dirs(settings) - return TestClient(create_app(settings)) + return TestClient(create_app(settings, bootstrap_on_startup=False)) def _install_fixtures(voices_dir: Path, *names: str) -> None: diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py new file mode 100644 index 0000000..d6b750c --- /dev/null +++ b/tests/unit/test_cli.py @@ -0,0 +1,97 @@ +"""Tests for the local server and voice-install CLI commands.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import pytest + +from tts import __main__ as cli +from tts.config import Settings + + +def _settings(tmp_path: Path) -> Settings: + return Settings( + host="127.0.0.1", + port=8321, + data_dir=tmp_path, + max_input_chars=50_000, + history_limit=20, + log_level="INFO", + default_voice_id="en_US-lessac-medium", + ) + + +def test_main_starts_loopback_server_and_opens_browser( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + calls: dict[str, object] = {} + monkeypatch.setattr(cli.Settings, "load", lambda: _settings(tmp_path)) + monkeypatch.setattr(cli, "configure_logging", lambda settings: None) + + def run(server: cli._BrowserServer) -> None: + calls.update( + { + "host": server.config.host, + "port": server.config.port, + "url": server._browser_url, + "open_browser": server._open_browser, + } + ) + + monkeypatch.setattr(cli._BrowserServer, "run", run) + monkeypatch.setattr("sys.argv", ["tts", "--port", "9000"]) + + cli.main() + + assert calls["url"] == "http://127.0.0.1:9000" + assert calls["host"] == "127.0.0.1" + assert calls["port"] == 9000 + assert calls["open_browser"] is True + + +def test_browser_opens_after_server_startup(monkeypatch: pytest.MonkeyPatch) -> None: + calls: list[str] = [] + + async def start_server(server: cli.uvicorn.Server, sockets: object = None) -> None: + server.started = True + + monkeypatch.setattr(cli.uvicorn.Server, "startup", start_server) + monkeypatch.setattr(cli.webbrowser, "open", lambda url: calls.append(url)) + server = cli._BrowserServer(cli.uvicorn.Config("app"), "http://127.0.0.1:8321", True) + + asyncio.run(server.startup()) + + assert calls == ["http://127.0.0.1:8321"] + + +def test_main_refuses_non_loopback_binding_without_override( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(cli.Settings, "load", lambda: _settings(tmp_path)) + monkeypatch.setattr("sys.argv", ["tts", "--host", "0.0.0.0", "--no-open"]) + + with pytest.raises(SystemExit) as error: + cli.main() + + assert error.value.code == 2 + + +def test_add_voice_initializes_store_and_prints_voice_id( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + calls: list[str] = [] + monkeypatch.setattr(cli.Settings, "load", lambda: _settings(tmp_path)) + monkeypatch.setattr(cli, "ensure_data_dirs", lambda settings: tmp_path / "voices") + monkeypatch.setattr(cli, "install_voice", lambda name: calls.append(name) or name) + monkeypatch.setattr("sys.argv", ["tts", "add-voice", "de_DE-thorsten-medium"]) + + cli.main() + + assert calls == ["de_DE-thorsten-medium"] + assert capsys.readouterr().out == "de_DE-thorsten-medium\n" diff --git a/tests/unit/test_errors.py b/tests/unit/test_errors.py index aeefa07..52b2d0a 100644 --- a/tests/unit/test_errors.py +++ b/tests/unit/test_errors.py @@ -53,7 +53,7 @@ def _echo(payload: VoicePreviewRequest) -> VoicePreviewRequest: def test_health_body_matches_contract(tmp_path: Path) -> None: - with TestClient(create_app(_settings(tmp_path))) as client: + with TestClient(create_app(_settings(tmp_path), bootstrap_on_startup=False)) as client: response = client.get("/api/health") assert response.status_code == 200 @@ -73,14 +73,14 @@ def test_health_counts_voice_models_in_the_store(tmp_path: Path) -> None: (voices_dir / "de_DE-thorsten-medium.onnx").write_bytes(b"") (voices_dir / "en_US-lessac-medium.onnx.json").write_text("{}", encoding="utf-8") - with TestClient(create_app(_settings(tmp_path))) as client: + with TestClient(create_app(_settings(tmp_path), bootstrap_on_startup=False)) as client: response = client.get("/api/health") assert response.json()["voicesInstalled"] == 2 def test_unknown_route_returns_not_found_envelope(tmp_path: Path) -> None: - with TestClient(create_app(_settings(tmp_path))) as client: + with TestClient(create_app(_settings(tmp_path), bootstrap_on_startup=False)) as client: response = client.get("/api/does-not-exist") assert response.status_code == 404 From 330a76a09042b6990cc2ed16c8de5437d141c101 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Sat, 21 Nov 2026 01:06:49 +0530 Subject: [PATCH 2/2] chore(tasks): record t2.3 pull request --- docs/TASKS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/TASKS.md b/docs/TASKS.md index 8467ea9..d8d40e2 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -30,7 +30,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| T2.3 | Settings route + first-run bootstrap | `arch/tts/t2.3` | 196 unit + 16 integration; Ruff; strict mypy; 34 Vitest; ESLint; TypeScript; Prettier (CRLF); Vite build; `git diff --check` | doing | +| T2.3 | Settings route + first-run bootstrap | `arch/tts/t2.3` | PR [#16](https://github.com/prateekchaplot/tts/pull/16); 196 unit + 16 integration; Ruff; strict mypy; 34 Vitest; ESLint; TypeScript; Prettier (CRLF); Vite build; `git diff --check` | doing | ## Remaining