Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions docs/TASKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` | 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

Expand All @@ -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

Expand Down Expand Up @@ -115,11 +114,12 @@ _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.
- T2.2 download naming: §9.2 fixes the character set `[a-z0-9-]` but not the word separator, so words are joined with `-` (e.g. `hello-world-this-is-a-test_20261120-190445.wav`). Frozen downstream for T3.2's `DownloadBar` contract.
- 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.
109 changes: 101 additions & 8 deletions src/tts/__main__.py
Original file line number Diff line number Diff line change
@@ -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()
10 changes: 8 additions & 2 deletions src/tts/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
]
60 changes: 60 additions & 0 deletions src/tts/api/dependencies.py
Original file line number Diff line number Diff line change
@@ -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()
35 changes: 5 additions & 30 deletions src/tts/api/routes/generations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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 -----------------------------------------------------------
Expand Down
4 changes: 3 additions & 1 deletion src/tts/api/routes/health.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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"]),
)
Loading