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
5 changes: 4 additions & 1 deletion docs/TASKS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` | [#14](https://github.com/prateekchaplot/tts/pull/14) open — awaiting review |

## Remaining

Expand Down Expand Up @@ -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.
4 changes: 2 additions & 2 deletions src/tts/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
53 changes: 53 additions & 0 deletions src/tts/api/routes/uploads.py
Original file line number Diff line number Diff line change
@@ -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))
75 changes: 75 additions & 0 deletions src/tts/api/routes/voices.py
Original file line number Diff line number Diff line change
@@ -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")
60 changes: 60 additions & 0 deletions tests/integration/test_api_voices_preview.py
Original file line number Diff line number Diff line change
@@ -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
137 changes: 137 additions & 0 deletions tests/unit/test_api_uploads.py
Original file line number Diff line number Diff line change
@@ -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"
Loading