From 711c807a92aae17588efe0d3db7cea0ae77121ec Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Fri, 20 Nov 2026 23:03:58 +0530 Subject: [PATCH 1/3] feat(api): add uploads and voices routes --- src/tts/api/__init__.py | 4 +- src/tts/api/routes/uploads.py | 53 +++++++ src/tts/api/routes/voices.py | 75 ++++++++++ tests/integration/test_api_voices_preview.py | 60 ++++++++ tests/unit/test_api_uploads.py | 137 +++++++++++++++++++ tests/unit/test_api_voices.py | 127 +++++++++++++++++ 6 files changed, 454 insertions(+), 2 deletions(-) create mode 100644 src/tts/api/routes/uploads.py create mode 100644 src/tts/api/routes/voices.py create mode 100644 tests/integration/test_api_voices_preview.py create mode 100644 tests/unit/test_api_uploads.py create mode 100644 tests/unit/test_api_voices.py diff --git a/src/tts/api/__init__.py b/src/tts/api/__init__.py index e364338..608bb2c 100644 --- a/src/tts/api/__init__.py +++ b/src/tts/api/__init__.py @@ -8,6 +8,6 @@ from fastapi import APIRouter -from tts.api.routes import health +from tts.api.routes import health, uploads, voices -ROUTERS: list[APIRouter] = [health.router] +ROUTERS: list[APIRouter] = [health.router, uploads.router, voices.router] diff --git a/src/tts/api/routes/uploads.py b/src/tts/api/routes/uploads.py new file mode 100644 index 0000000..f02731f --- /dev/null +++ b/src/tts/api/routes/uploads.py @@ -0,0 +1,53 @@ +"""Plain-text upload endpoint (ARCHITECTURE.md section 9.2).""" + +from __future__ import annotations + +from typing import Annotated + +from fastapi import APIRouter, File, UploadFile + +from tts.api.errors import AppError +from tts.api.schemas import UploadResponse + +router = APIRouter(tags=["uploads"]) + +MAX_UPLOAD_BYTES = 2 * 1024 * 1024 +ACCEPTED_TYPES_MESSAGE = "only plain-text .txt files are accepted" + + +def _content_type_allowed(content_type: str | None) -> bool: + if content_type is None: + return False + normalized = content_type.lower() + return normalized.startswith("text/") or normalized == "application/octet-stream" + + +def _decode(data: bytes) -> str: + if data.startswith((b"\xff\xfe", b"\xfe\xff")): + return data.decode("utf-16") + return data.decode("utf-8-sig") + + +@router.post("/uploads", response_model=UploadResponse, summary="Read a plain-text file") +def upload_file(file: Annotated[UploadFile, File(...)]) -> UploadResponse: + """Decode an uploaded .txt file for review; generation is a separate step.""" + filename = file.filename or "" + if not filename.lower().endswith(".txt") or not _content_type_allowed(file.content_type): + raise AppError( + "UNSUPPORTED_FILE_TYPE", 415, f"Unsupported file type; {ACCEPTED_TYPES_MESSAGE}." + ) + + data = file.file.read(MAX_UPLOAD_BYTES + 1) + if len(data) > MAX_UPLOAD_BYTES: + raise AppError("FILE_TOO_LARGE", 413, "The file is larger than the 2 MB limit.") + + try: + text = _decode(data) + except UnicodeDecodeError as error: + raise AppError( + "DECODE_FAILED", + 415, + "The file could not be decoded as UTF-8 or UTF-16 text.", + ) from error + + return UploadResponse(text=text, filename=filename, size_bytes=len(data)) diff --git a/src/tts/api/routes/voices.py b/src/tts/api/routes/voices.py new file mode 100644 index 0000000..430c4b5 --- /dev/null +++ b/src/tts/api/routes/voices.py @@ -0,0 +1,75 @@ +"""Voice listing and preview endpoints (ARCHITECTURE.md section 9.2).""" + +from __future__ import annotations + +import logging + +from fastapi import APIRouter, Request, Response + +from tts.api.errors import AppError +from tts.api.schemas import Voice, VoiceList, VoicePreviewRequest +from tts.config import Settings +from tts.voices import store + +logger = logging.getLogger(__name__) + +router = APIRouter(tags=["voices"]) + +NO_VOICES_MESSAGE = ( + "No voices are installed. Run `tts add-voice en_US-lessac-medium` " + "(needs internet once), then reload." +) + + +def _settings(request: Request) -> Settings: + """Initialize the voice store for this app's settings (idempotent).""" + settings: Settings = request.app.state.settings + store.ensure_data_dirs(settings) + return 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.""" + settings = _settings(request) + voices = store.list_voices() + return VoiceList( + items=[ + Voice( + id=voice.id, + name=voice.name, + language=voice.language, + gender=voice.gender, + sample_rate=voice.sample_rate, + ) + for voice in voices + ], + total=len(voices), + default_voice_id=settings.default_voice_id, + ) + + +@router.post("/voices/preview", summary="Preview a voice") +def preview_voice(payload: VoicePreviewRequest, request: Request) -> Response: + """Render the fixed preview phrase as WAV in the requested voice.""" + _settings(request) + if not store.list_voices(): + raise AppError("NO_VOICES_INSTALLED", 409, NO_VOICES_MESSAGE) + + try: + wav = store.preview_wav(payload.voice_id) + except store.VoiceNotFoundError as error: + raise AppError( + "VOICE_NOT_FOUND", + 422, + f"Voice {payload.voice_id!r} is not installed.", + ) from error + except Exception as error: + logger.exception("Voice preview failed for %s", payload.voice_id) + raise AppError( + "ENGINE_ERROR", + 500, + "The speech engine could not render a preview.", + ) from error + + return Response(content=wav, media_type="audio/wav") diff --git a/tests/integration/test_api_voices_preview.py b/tests/integration/test_api_voices_preview.py new file mode 100644 index 0000000..b0bab60 --- /dev/null +++ b/tests/integration/test_api_voices_preview.py @@ -0,0 +1,60 @@ +"""Integration tests for voice routes against a real Piper voice.""" + +from __future__ import annotations + +import io +import wave +from collections.abc import Iterator + +import pytest +from fastapi.testclient import TestClient + +from tts.app import create_app +from tts.config import Settings +from tts.voices.store import ensure_data_dirs, list_voices + +pytestmark = pytest.mark.integration + +DEFAULT_VOICE_ID = "en_US-lessac-medium" + + +@pytest.fixture(scope="module") +def client() -> Iterator[TestClient]: + settings = Settings.load() + voices_dir = ensure_data_dirs(settings) + installed = {voice.id for voice in list_voices()} + if DEFAULT_VOICE_ID not in installed: + pytest.skip( + f"{DEFAULT_VOICE_ID} is not installed; run: python -m piper.download_voices " + f"{DEFAULT_VOICE_ID} --download-dir {voices_dir}" + ) + with TestClient(create_app(settings)) as test_client: + yield test_client + + +def test_list_voices_includes_the_real_voice(client: TestClient) -> None: + response = client.get("/api/voices") + + assert response.status_code == 200 + body = response.json() + match = next(item for item in body["items"] if item["id"] == DEFAULT_VOICE_ID) + assert match["language"] == "en_US" + assert match["sampleRate"] == 22_050 + assert match["gender"] is None + + +def test_preview_returns_a_short_valid_pcm_wav(client: TestClient) -> None: + response = client.post("/api/voices/preview", json={"voiceId": DEFAULT_VOICE_ID}) + + assert response.status_code == 200 + assert response.headers["content-type"] == "audio/wav" + data = response.content + assert data.startswith(b"RIFF") + assert data[8:12] == b"WAVE" + with wave.open(io.BytesIO(data), "rb") as wav_file: + assert wav_file.getnchannels() == 1 + assert wav_file.getsampwidth() == 2 + assert wav_file.getframerate() == 22_050 + duration_seconds = wav_file.getnframes() / wav_file.getframerate() + + assert 0.0 < duration_seconds <= 5.0 diff --git a/tests/unit/test_api_uploads.py b/tests/unit/test_api_uploads.py new file mode 100644 index 0000000..dbf4bbc --- /dev/null +++ b/tests/unit/test_api_uploads.py @@ -0,0 +1,137 @@ +"""Unit tests for the plain-text upload endpoint.""" + +from __future__ import annotations + +from pathlib import Path + +from fastapi.testclient import TestClient + +from tts.app import create_app +from tts.config import Settings + +MAX_UPLOAD_BYTES = 2 * 1024 * 1024 + + +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 _client(tmp_path: Path) -> TestClient: + return TestClient(create_app(_settings(tmp_path))) + + +def test_upload_returns_decoded_text_and_size(tmp_path: Path) -> None: + data = b"Hello world.\nSecond line." + + with _client(tmp_path) as client: + response = client.post( + "/api/uploads", + files={"file": ("notes.txt", data, "text/plain")}, + ) + + assert response.status_code == 200 + assert response.json() == { + "text": "Hello world.\nSecond line.", + "filename": "notes.txt", + "sizeBytes": len(data), + } + + +def test_upload_strips_utf8_bom(tmp_path: Path) -> None: + data = b"\xef\xbb\xbfHallo Welt" + + with _client(tmp_path) as client: + response = client.post( + "/api/uploads", + files={"file": ("notes.txt", data, "text/plain")}, + ) + + assert response.status_code == 200 + assert response.json()["text"] == "Hallo Welt" + assert response.json()["sizeBytes"] == len(data) + + +def test_upload_decodes_utf16_with_bom(tmp_path: Path) -> None: + data = "Héllo wörld".encode("utf-16") + + with _client(tmp_path) as client: + response = client.post( + "/api/uploads", + files={"file": ("notes.txt", data, "text/plain")}, + ) + + assert response.status_code == 200 + assert response.json()["text"] == "Héllo wörld" + + +def test_unsupported_extension_rejected_with_accepted_types(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.post( + "/api/uploads", + files={"file": ("notes.pdf", b"%PDF-1.4", "application/pdf")}, + ) + + assert response.status_code == 415 + body = response.json()["error"] + assert body["code"] == "UNSUPPORTED_FILE_TYPE" + assert "only plain-text .txt files are accepted" in body["message"] + + +def test_unsupported_content_type_rejected(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.post( + "/api/uploads", + files={"file": ("notes.txt", b"hello", "application/pdf")}, + ) + + assert response.status_code == 415 + assert response.json()["error"]["code"] == "UNSUPPORTED_FILE_TYPE" + + +def test_octet_stream_content_type_is_accepted(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.post( + "/api/uploads", + files={"file": ("notes.txt", b"hello", "application/octet-stream")}, + ) + + assert response.status_code == 200 + assert response.json()["text"] == "hello" + + +def test_oversized_file_rejected(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.post( + "/api/uploads", + files={"file": ("big.txt", b"a" * (MAX_UPLOAD_BYTES + 1), "text/plain")}, + ) + + assert response.status_code == 413 + assert response.json()["error"]["code"] == "FILE_TOO_LARGE" + + +def test_undecodable_bytes_rejected(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.post( + "/api/uploads", + files={"file": ("bad.txt", b"not utf8 \xc3(", "text/plain")}, + ) + + assert response.status_code == 415 + assert response.json()["error"]["code"] == "DECODE_FAILED" + + +def test_missing_file_field_uses_error_envelope(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.post("/api/uploads") + + assert response.status_code == 422 + assert response.json()["error"]["code"] == "OUT_OF_RANGE" diff --git a/tests/unit/test_api_voices.py b/tests/unit/test_api_voices.py new file mode 100644 index 0000000..7d28db8 --- /dev/null +++ b/tests/unit/test_api_voices.py @@ -0,0 +1,127 @@ +"""Unit tests for the voice listing and preview endpoints.""" + +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 +from tts.voices import store + +FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "voices" +DEFAULT_VOICE_ID = "de_DE-thorsten-low" + + +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 _client(tmp_path: Path) -> TestClient: + settings = _settings(tmp_path) + store.ensure_data_dirs(settings) + return TestClient(create_app(settings)) + + +def _install_fixtures(voices_dir: Path, *names: str) -> None: + voices_dir.mkdir(parents=True, exist_ok=True) + for name in names: + shutil.copyfile(FIXTURES / f"{name}.onnx.json", voices_dir / f"{name}.onnx.json") + (voices_dir / f"{name}.onnx").touch() + + +def test_list_voices_matches_the_contract(tmp_path: Path) -> None: + client = _client(tmp_path) + _install_fixtures(tmp_path / "voices", "en_US-alpha-medium", DEFAULT_VOICE_ID) + + with client: + response = client.get("/api/voices") + + assert response.status_code == 200 + body = response.json() + assert [item["id"] for item in body["items"]] == [DEFAULT_VOICE_ID, "en_US-alpha-medium"] + assert body["items"][1]["sampleRate"] == 22_050 + assert body["items"][0]["language"] == "de_DE" + assert body["total"] == 2 + assert body["defaultVoiceId"] == DEFAULT_VOICE_ID + + +def test_list_voices_with_empty_store(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.get("/api/voices") + + assert response.status_code == 200 + assert response.json() == {"items": [], "total": 0, "defaultVoiceId": DEFAULT_VOICE_ID} + + +def test_preview_unknown_voice_returns_voice_not_found(tmp_path: Path) -> None: + client = _client(tmp_path) + _install_fixtures(tmp_path / "voices", "en_US-alpha-medium") + + with client: + response = client.post("/api/voices/preview", json={"voiceId": "en_US-missing-medium"}) + + assert response.status_code == 422 + assert response.json()["error"]["code"] == "VOICE_NOT_FOUND" + + +def test_preview_with_empty_store_returns_no_voices_installed(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.post("/api/voices/preview", json={"voiceId": "en_US-lessac-medium"}) + + assert response.status_code == 409 + body = response.json()["error"] + assert body["code"] == "NO_VOICES_INSTALLED" + assert "tts add-voice" in body["message"] + + +def test_preview_engine_failure_maps_to_500( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + client = _client(tmp_path) + _install_fixtures(tmp_path / "voices", "en_US-alpha-medium") + + def _fail(voice_id: str) -> bytes: + raise RuntimeError("engine exploded") + + monkeypatch.setattr(store, "preview_wav", _fail) + + with client: + response = client.post("/api/voices/preview", json={"voiceId": "en_US-alpha-medium"}) + + assert response.status_code == 500 + body = response.json()["error"] + assert body["code"] == "ENGINE_ERROR" + assert body["details"] is None + + +def test_preview_success_returns_wav_bytes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + client = _client(tmp_path) + _install_fixtures(tmp_path / "voices", "en_US-alpha-medium") + monkeypatch.setattr(store, "preview_wav", lambda voice_id: b"RIFF-wav") + + with client: + response = client.post("/api/voices/preview", json={"voiceId": "en_US-alpha-medium"}) + + assert response.status_code == 200 + assert response.headers["content-type"] == "audio/wav" + assert response.content == b"RIFF-wav" + + +def test_preview_missing_voice_id_uses_error_envelope(tmp_path: Path) -> None: + with _client(tmp_path) as client: + response = client.post("/api/voices/preview", json={}) + + assert response.status_code == 422 + assert response.json()["error"]["code"] == "OUT_OF_RANGE" From 3cb9b391cc3badf130771fd4dd029ce2017c8978 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Fri, 20 Nov 2026 23:04:30 +0530 Subject: [PATCH 2/3] chore(tasks): record t2.1 in progress --- docs/TASKS.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/TASKS.md b/docs/TASKS.md index 96209d8..75186aa 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -28,7 +28,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| _(empty — next up: T2.1 on branch `arch/tts/t2.1`)_ | | | | | +| T2.1 | Uploads + voices routes | `arch/tts/t2.1` | 156 unit tests (16 new); 15 integration tests (2 new) vs `en_US-lessac-medium` (valid RIFF/WAV preview ≤ 5 s); Ruff check/format; strict mypy; `git diff --check` | PR pending — awaiting review | ## Remaining @@ -114,3 +114,6 @@ _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 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. From 5bd43d0fd52ffc3dd99b0db5c2d0a8db19b48786 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Fri, 20 Nov 2026 23:05:08 +0530 Subject: [PATCH 3/3] chore(tasks): link t2.1 pull request --- docs/TASKS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/TASKS.md b/docs/TASKS.md index 75186aa..34b0906 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -28,7 +28,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| T2.1 | Uploads + voices routes | `arch/tts/t2.1` | 156 unit tests (16 new); 15 integration tests (2 new) vs `en_US-lessac-medium` (valid RIFF/WAV preview ≤ 5 s); Ruff check/format; strict mypy; `git diff --check` | PR pending — awaiting review | +| T2.1 | Uploads + voices routes | `arch/tts/t2.1` | 156 unit tests (16 new); 15 integration tests (2 new) vs `en_US-lessac-medium` (valid RIFF/WAV preview ≤ 5 s); Ruff check/format; strict mypy; `git diff --check` | [#14](https://github.com/prateekchaplot/tts/pull/14) open — awaiting review | ## Remaining