From 0731d0f0380eb4a7d41f7ce3a6b8411b9d7563ca Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Sat, 21 Nov 2026 00:38:43 +0530 Subject: [PATCH 1/2] feat(api): add generations routes with SSE and media exports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Append generations.router to the shared ROUTERS registry (§14.4); T2.3 adds its own settings entry downstream. --- src/tts/api/__init__.py | 4 +- src/tts/api/routes/generations.py | 444 ++++++++++++++++++ .../integration/test_api_generations_flow.py | 121 +++++ tests/unit/test_api_generations_routes.py | 425 +++++++++++++++++ 4 files changed, 992 insertions(+), 2 deletions(-) create mode 100644 src/tts/api/routes/generations.py create mode 100644 tests/integration/test_api_generations_flow.py create mode 100644 tests/unit/test_api_generations_routes.py diff --git a/src/tts/api/__init__.py b/src/tts/api/__init__.py index 608bb2c..4851a9f 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, uploads, voices +from tts.api.routes import generations, health, uploads, voices -ROUTERS: list[APIRouter] = [health.router, uploads.router, voices.router] +ROUTERS: list[APIRouter] = [health.router, uploads.router, voices.router, generations.router] diff --git a/src/tts/api/routes/generations.py b/src/tts/api/routes/generations.py new file mode 100644 index 0000000..94c20dd --- /dev/null +++ b/src/tts/api/routes/generations.py @@ -0,0 +1,444 @@ +"""Generation endpoints: create, list, detail, media, SSE, cancel, delete. + +Everything here is wiring and contract mapping. Synthesis, timing, and cue +logic live in ``jobs`` and its dependencies (§7.9); this module only validates +requests, maps domain errors to the §9.1 envelope, and serializes rows from the +DAL into the §9.1 schemas. +""" + +from __future__ import annotations + +import json +import logging +import re +import threading +from collections.abc import Iterator +from datetime import UTC, datetime +from pathlib import Path +from typing import Annotated, Any, cast + +from fastapi import APIRouter, Query, Request +from fastapi.responses import FileResponse, PlainTextResponse, Response, StreamingResponse + +from tts.api.errors import AppError +from tts.api.schemas import ( + CueSchema, + GenerationCreateRequest, + GenerationDetail, + GenerationError, + GenerationList, + GenerationState, + GenerationStatus, + GenerationSummary, + SourceType, + WordTimingSchema, +) +from tts.config import Settings +from tts.history.dal import ActiveGenerationError, Dal +from tts.jobs.manager import ( + GenerationNotCancellableError, + GenerationNotFoundError, + JobManager, +) +from tts.jobs.sse import RETRY_LINE, Subscriber +from tts.subtitles.srt import render_srt +from tts.subtitles.vtt import render_vtt +from tts.types import Cue +from tts.voices import store + +logger = logging.getLogger(__name__) + +router = APIRouter(tags=["generations"]) + +_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") +_NOT_FOUND_MESSAGE = "That generation does not exist." +_NOT_READY_MESSAGE = "The audio is not ready yet. Please wait for generation to finish." +_NO_VOICES_MESSAGE = ( + "No voices are installed. Run `tts add-voice en_US-lessac-medium` " + "(needs internet once), then reload." +) +_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) + + +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) + + +# -- small helpers ----------------------------------------------------------- + + +def _validate_id(generation_id: str) -> str: + """Reject anything that is not a UUID4 before it can reach a path join.""" + if not _UUID_RE.fullmatch(str(generation_id)): + raise AppError("GENERATION_NOT_FOUND", 404, _NOT_FOUND_MESSAGE) + return str(generation_id) + + +def _row_or_404(dal: Dal, generation_id: str) -> dict[str, Any]: + row = dal.get(generation_id) + if row is None: + raise AppError("GENERATION_NOT_FOUND", 404, _NOT_FOUND_MESSAGE) + return row + + +def _ready_row(dal: Dal, generation_id: str) -> dict[str, Any]: + row = _row_or_404(dal, generation_id) + if row["status"] != "succeeded": + raise AppError("GENERATION_NOT_READY", 409, _NOT_READY_MESSAGE) + return row + + +def _json_list(value: object) -> list[dict[str, Any]]: + """Decode a JSON column, degrading to an empty list rather than failing.""" + if not value: + return [] + try: + parsed = json.loads(str(value)) + except json.JSONDecodeError: + logger.warning("Ignoring malformed generation JSON column") + return [] + if not isinstance(parsed, list): + return [] + return [item for item in parsed if isinstance(item, dict)] + + +def _error_info(row: dict[str, Any]) -> GenerationError | None: + code = row["error_code"] + if not code: + return None + return GenerationError(code=str(code), message=str(row["error_message"] or "")) + + +def _summary(row: dict[str, Any]) -> GenerationSummary: + """Map a stored row to the camelCase GenerationSummary contract.""" + return GenerationSummary( + generation_id=str(row["id"]), + status=cast(GenerationState, str(row["status"])), + created_at=str(row["created_at"]), + source_type=cast(SourceType, str(row["source_type"])), + input_preview=str(row["input_text"] or "")[:120], + input_filename=row["input_filename"], + voice_id=str(row["voice_id"]), + voice_name=str(row["voice_name"]), + rate=float(row["rate"]), + volume=float(row["volume"]), + duration_seconds=row["duration_seconds"], + error=_error_info(row), + ) + + +def _detail(row: dict[str, Any]) -> GenerationDetail: + """Map a stored row to GenerationDetail; pending values stay null.""" + detail = GenerationDetail(**_summary(row).model_dump()) + if row["status"] not in ("queued", "running", "cancelling"): + detail.text = str(row["input_text"] or "") + if row["status"] == "succeeded": + detail.sample_rate = row["sample_rate"] + detail.aligned_word_ratio = row["aligned_word_ratio"] + detail.word_timings = [ + WordTimingSchema( + text=str(word.get("text", "")), + start_ms=int(word.get("startMs", 0)), + end_ms=int(word.get("endMs", 0)), + aligned=bool(word.get("aligned", False)), + ) + for word in _json_list(row["word_timings_json"]) + ] + detail.cues = [ + CueSchema( + index=int(cue.get("index", 0)), + start_ms=int(cue.get("startMs", 0)), + end_ms=int(cue.get("endMs", 0)), + text=str(cue.get("text", "")), + ) + for cue in _json_list(row["cues_json"]) + ] + return detail + + +def _download_stem(row: dict[str, Any]) -> str: + """Build the §9.2 ``{slug}_{timestamp}`` download name.""" + words = re.findall(r"[A-Za-z0-9]+", str(row["input_text"] or ""))[:6] + slug = re.sub(r"[^a-z0-9-]", "", "-".join(words).lower()).strip("-") or "speech" + try: + created = datetime.fromisoformat(str(row["created_at"])) + except ValueError: + created = datetime.now(UTC) + if created.tzinfo is None: + created = created.replace(tzinfo=UTC) + stamp = created.astimezone(UTC).strftime("%Y%m%d-%H%M%S") + return f"{slug}_{stamp}" + + +def _download_headers(row: dict[str, Any], suffix: str) -> dict[str, str]: + name = f"{_download_stem(row)}.{suffix}" + return {"Content-Disposition": f'attachment; filename="{name}"'} + + +def _audio_path(row: dict[str, Any], settings: Settings) -> Path: + """Resolve a stored audio path, refusing anything outside the generations dir.""" + value = row["audio_path"] + if not value: + raise AppError("GENERATION_NOT_READY", 409, _NOT_READY_MESSAGE) + generations_dir = (settings.data_dir / "generations").resolve() + try: + path = Path(str(value)).resolve() + except OSError as error: + raise AppError("GENERATION_NOT_READY", 409, _NOT_READY_MESSAGE) from error + if not path.is_relative_to(generations_dir) or not path.is_file(): + raise AppError("GENERATION_NOT_READY", 409, _NOT_READY_MESSAGE) + return path + + +def _cue_objects(row: dict[str, Any]) -> list[Cue]: + return [ + Cue( + index=int(cue.get("index", 0)), + start_ms=int(cue.get("startMs", 0)), + end_ms=int(cue.get("endMs", 0)), + text=str(cue.get("text", "")), + ) + for cue in _json_list(row["cues_json"]) + ] + + +def _stream(subscriber: Subscriber) -> Iterator[str]: + """Send the reconnect hint, then named SSE frames until the terminal event.""" + yield RETRY_LINE + for event in subscriber.events(): + if event is None: + return + yield event.to_wire() + if event.terminal: + return + + +def _settings_defaults(dal: Dal, settings: Settings) -> dict[str, Any]: + """Seed and read §8.2 settings so omitted request fields get stored defaults.""" + dal.seed_settings(settings.default_voice_id) + values = dal.get_settings() + return { + "defaultVoiceId": str(values.get("defaultVoiceId", settings.default_voice_id)), + "rate": float(values.get("rate", 1.0)), + "volume": float(values.get("volume", 1.0)), + } + + +def _range_check(field: str, value: float, bounds: tuple[float, float]) -> None: + low, high = bounds + if not low <= value <= high: + raise AppError( + "OUT_OF_RANGE", + 422, + f"{field} must be between {low} and {high}.", + {"field": field, "min": low, "max": high, "value": value}, + ) + + +# -- routes ------------------------------------------------------------------ + + +@router.post( + "/generations", status_code=202, response_model=GenerationStatus, summary="Queue a generation" +) +def create_generation(payload: GenerationCreateRequest, request: Request) -> GenerationStatus: + """Validate the request, then hand it to the single-worker job manager.""" + settings: Settings = request.app.state.settings + store.ensure_data_dirs(settings) + + text = payload.text + if text is None or not text.strip(): + raise AppError( + "EMPTY_INPUT", + 422, + "Please type or upload some text before generating.", + ) + if len(text) > settings.max_input_chars: + raise AppError( + "INPUT_TOO_LONG", + 422, + f"Input is {len(text):,} characters; the limit is {settings.max_input_chars:,}.", + {"maxChars": settings.max_input_chars, "receivedChars": len(text)}, + ) + + # T1.6 contract: an empty store wins over an unknown voice so the UI can + # show the no-voice remedy (§10.4). + voices = store.list_voices() + if not voices: + raise AppError("NO_VOICES_INSTALLED", 409, _NO_VOICES_MESSAGE) + + defaults = _settings_defaults(_dal(request), settings) + voice_id = payload.voice_id if payload.voice_id is not None else defaults["defaultVoiceId"] + if voice_id not in {voice.id for voice in voices}: + raise AppError("VOICE_NOT_FOUND", 422, f"Voice {voice_id!r} is not installed.") + + rate = payload.rate if payload.rate is not None else defaults["rate"] + volume = payload.volume if payload.volume is not None else defaults["volume"] + _range_check("rate", rate, _RATE_RANGE) + _range_check("volume", volume, _VOLUME_RANGE) + + try: + generation_id = _jobs(request).submit( + voice_id=voice_id, + text=text, + source_type="text", + rate=rate, + volume=volume, + ) + except store.VoiceNotFoundError as error: + raise AppError("VOICE_NOT_FOUND", 422, f"Voice {voice_id!r} is not installed.") from error + except Exception as error: + logger.exception("Could not queue generation") + raise AppError("INTERNAL_ERROR", 500, "The generation could not be started.") from error + + return GenerationStatus(generation_id=generation_id, status="queued") + + +@router.get("/generations", response_model=GenerationList, summary="List generation history") +def list_generations( + request: Request, + limit: Annotated[int | None, Query(ge=1, le=100)] = None, + offset: Annotated[int, Query(ge=0)] = 0, +) -> GenerationList: + """Return newest-first summaries with a stable total count.""" + settings: Settings = request.app.state.settings + effective_limit = min(limit or settings.history_limit, 100) + rows, total = _dal(request).list(limit=effective_limit, offset=offset) + return GenerationList(items=[_summary(row) for row in rows], total=total) + + +@router.get( + "/generations/{generation_id}", response_model=GenerationDetail, summary="Get generation detail" +) +def get_generation(generation_id: str, request: Request) -> GenerationDetail: + """Return the full record; result fields stay null until success.""" + row = _row_or_404(_dal(request), _validate_id(generation_id)) + return _detail(row) + + +@router.get("/generations/{generation_id}/audio", summary="Download generated audio") +def get_audio(generation_id: str, request: Request) -> FileResponse: + """Serve the completed WAV with the §9.2 attachment name.""" + settings: Settings = request.app.state.settings + row = _ready_row(_dal(request), _validate_id(generation_id)) + path = _audio_path(row, settings) + return FileResponse( + path, + media_type="audio/wav", + headers=_download_headers(row, "wav"), + ) + + +@router.get("/generations/{generation_id}/subtitles", summary="Download subtitles") +def get_subtitles( + generation_id: str, + request: Request, + format: Annotated[str | None, Query()] = None, +) -> PlainTextResponse: + """Render completed cues as SRT or WebVTT.""" + row = _ready_row(_dal(request), _validate_id(generation_id)) + if format == "srt": + body = render_srt(_cue_objects(row)) + elif format == "vtt": + body = render_vtt(_cue_objects(row)) + else: + raise AppError( + "SUBTITLE_FORMAT_UNKNOWN", + 400, + "Unknown subtitle format; accepted values are srt and vtt.", + ) + return PlainTextResponse(body, headers=_download_headers(row, format)) + + +@router.get("/generations/{generation_id}/events", summary="Stream generation events") +def generation_events(generation_id: str, request: Request) -> StreamingResponse: + """Expose the manager's event queue as an SSE stream with reconnect replay.""" + generation_id = _validate_id(generation_id) + try: + subscriber = _jobs(request).subscribe(generation_id) + except GenerationNotFoundError as error: + raise AppError("GENERATION_NOT_FOUND", 404, _NOT_FOUND_MESSAGE) from error + return StreamingResponse( + _stream(subscriber), + media_type="text/event-stream", + headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}, + ) + + +@router.post( + "/generations/{generation_id}/cancel", + response_model=GenerationStatus, + summary="Cancel a generation", +) +def cancel_generation(generation_id: str, request: Request) -> GenerationStatus: + """Cancel a queued or running job; an already-cancelling job answers cancelled.""" + generation_id = _validate_id(generation_id) + row = _row_or_404(_dal(request), generation_id) + status = str(row["status"]) + if status in ("succeeded", "failed", "cancelled"): + raise AppError("GENERATION_BUSY", 409, "This generation has already finished.") + + if status == "cancelling": + # §9.2 pins the answer for an already-cancelling job, while jobs.cancel + # truthfully keeps reporting "cancelling" until the worker confirms. + return GenerationStatus(generation_id=generation_id, status="cancelled") + + try: + result = _jobs(request).cancel(generation_id) + except GenerationNotFoundError as error: + raise AppError("GENERATION_NOT_FOUND", 404, _NOT_FOUND_MESSAGE) from error + except GenerationNotCancellableError as error: + raise AppError("GENERATION_BUSY", 409, "This generation has already finished.") from error + return GenerationStatus(generation_id=generation_id, status=result) + + +@router.delete("/generations/{generation_id}", status_code=204, summary="Delete a generation") +def delete_generation(generation_id: str, request: Request) -> Response: + """Delete a finished generation's row and WAV atomically (§8.5).""" + generation_id = _validate_id(generation_id) + dal = _dal(request) + _row_or_404(dal, generation_id) + try: + deleted = dal.delete(generation_id) + except ActiveGenerationError as error: + raise AppError( + "GENERATION_BUSY", + 409, + "Please cancel this generation before deleting it.", + ) from error + if not deleted: + raise AppError("GENERATION_NOT_FOUND", 404, _NOT_FOUND_MESSAGE) + return Response(status_code=204) diff --git a/tests/integration/test_api_generations_flow.py b/tests/integration/test_api_generations_flow.py new file mode 100644 index 0000000..998962d --- /dev/null +++ b/tests/integration/test_api_generations_flow.py @@ -0,0 +1,121 @@ +"""Integration test for the generations HTTP surface against a real Piper voice. + +Covers the §14.2 T2.2 acceptance criteria end to end: create → SSE → succeeded +→ detail/media exports → delete, with a reconnect replay check. +""" + +from __future__ import annotations + +import io +import json +import wave +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pytest +from fastapi.testclient import TestClient + +from tts.app import create_app +from tts.config import Settings +from tts.history.dal import Dal +from tts.jobs.manager import JobManager +from tts.voices.store import ensure_data_dirs, list_voices + +pytestmark = pytest.mark.integration + +VOICE_ID = "en_US-lessac-medium" +TEXT = "Hello from the generations API. This audio has two sentences." + + +def _event_names(body: str) -> list[str]: + return [ + line.removeprefix("event: ") for line in body.splitlines() if line.startswith("event: ") + ] + + +@pytest.fixture(scope="module") +def env(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Any]: + settings = Settings.load() + voices_dir = ensure_data_dirs(settings) + if VOICE_ID not in {voice.id for voice in list_voices()}: + pytest.skip( + f"{VOICE_ID} is not installed; run: python -m piper.download_voices " + f"{VOICE_ID} --download-dir {voices_dir}" + ) + + dal = Dal(tmp_path_factory.mktemp("generations-api"), history_limit=settings.history_limit) + jobs = JobManager(dal, settings) + app = create_app(settings) + app.state.dal = dal + 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: + client: TestClient = env[0] + dal: Dal = env[1] + + created = client.post( + "/api/generations", + json={"text": TEXT, "voiceId": VOICE_ID, "rate": 1.0, "volume": 1.0}, + ) + assert created.status_code == 202 + body = created.json() + assert body["status"] == "queued" + generation_id = body["generationId"] + + with client.stream("GET", f"/api/generations/{generation_id}/events") as stream: + assert stream.status_code == 200 + stream_body = stream.read().decode("utf-8") + + assert "retry: 3000" in stream_body + names = _event_names(stream_body) + assert "succeeded" in names + if "progress" in names: + progress_payloads = [ + json.loads(line.removeprefix("data: ")) + for line in stream_body.splitlines() + if line.startswith("data: ") and "sentenceIndex" in line + ] + assert max(int(item["sentenceIndex"]) for item in progress_payloads) >= 1 + + # A reconnect replays the terminal state instead of leaving a gap (§9.2). + with client.stream("GET", f"/api/generations/{generation_id}/events") as reconnect: + replay = reconnect.read().decode("utf-8") + assert _event_names(replay) == ["succeeded"] + + detail = client.get(f"/api/generations/{generation_id}") + assert detail.status_code == 200 + result = detail.json() + assert result["status"] == "succeeded" + assert result["text"] == TEXT + assert result["durationSeconds"] > 0 + assert result["wordTimings"] + assert all(word["startMs"] <= word["endMs"] for word in result["wordTimings"]) + + audio = client.get(f"/api/generations/{generation_id}/audio") + assert audio.status_code == 200 + assert audio.headers["content-disposition"].endswith('.wav"') + with wave.open(io.BytesIO(audio.content), "rb") as wav_file: + assert wav_file.getnchannels() == 1 + assert wav_file.getsampwidth() == 2 + assert wav_file.getnframes() > 0 + + for subtitle_format, header in (("srt", "1\n"), ("vtt", "WEBVTT")): + subtitles = client.get( + f"/api/generations/{generation_id}/subtitles", + params={"format": subtitle_format}, + ) + assert subtitles.status_code == 200 + assert subtitles.text.startswith(header) + assert subtitles.headers["content-disposition"].endswith(f'.{subtitle_format}"') + + audio_path = str(dal.get(generation_id)["audio_path"]) + deleted = client.delete(f"/api/generations/{generation_id}") + assert deleted.status_code == 204 + assert dal.get(generation_id) is None + assert not Path(audio_path).exists() diff --git a/tests/unit/test_api_generations_routes.py b/tests/unit/test_api_generations_routes.py new file mode 100644 index 0000000..6b2d040 --- /dev/null +++ b/tests/unit/test_api_generations_routes.py @@ -0,0 +1,425 @@ +"""Unit tests for the generations HTTP surface (§9.2, task T2.2).""" + +from __future__ import annotations + +import json +import re +import uuid +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Any, Literal + +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from tts.api.routes import generations +from tts.app import create_app +from tts.config import Settings +from tts.history.dal import Dal +from tts.jobs.manager import GenerationNotFoundError +from tts.jobs.sse import SseEvent, Subscriber +from tts.voices.store import VoiceInfo + +VOICE = VoiceInfo(id="v1", name="Voice One", language="en", gender=None, sample_rate=22_050) + + +class FakeJobs: + """A job manager stand-in: no engine, no worker thread, no piper import.""" + + def __init__(self) -> None: + self.submissions: list[dict[str, Any]] = [] + self.subscribed: list[str] = [] + self.events: list[SseEvent] = [] + self.known_ids: set[str] = set() + self.cancel_result: Literal["cancelled", "cancelling"] = "cancelled" + + def submit(self, **kwargs: Any) -> str: + self.submissions.append(kwargs) + return str(uuid.uuid4()) + + def cancel(self, generation_id: str) -> Literal["cancelled", "cancelling"]: + return self.cancel_result + + def subscribe(self, generation_id: str) -> Subscriber: + if generation_id not in self.known_ids: + raise GenerationNotFoundError(generation_id) + self.subscribed.append(generation_id) + subscriber = Subscriber(generation_id) + for event in self.events: + subscriber.put(event) + subscriber.close() + return subscriber + + +@dataclass +class Env: + client: TestClient + app: FastAPI + dal: Dal + jobs: FakeJobs + settings: Settings + + +def _app(settings: Settings, dal: Dal, jobs: FakeJobs) -> FastAPI: + app = create_app(settings) + app.state.dal = dal + app.state.jobs = jobs + return app + + +@pytest.fixture +def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any: + settings = Settings( + host="127.0.0.1", + port=8321, + data_dir=tmp_path / "data", + max_input_chars=50_000, + history_limit=20, + log_level="INFO", + default_voice_id="v1", + ) + dal = Dal(settings.data_dir, history_limit=settings.history_limit) + monkeypatch.setattr(generations.store, "list_voices", lambda: [VOICE]) + monkeypatch.setattr(generations.store, "ensure_data_dirs", lambda s: s.data_dir / "voices") + jobs = FakeJobs() + 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]: + """Store a succeeded row with a real WAV stub and camelCase result columns.""" + generations_dir = env.settings.data_dir / "generations" + generations_dir.mkdir(parents=True, exist_ok=True) + wav = generations_dir / "audio.wav" + wav.write_bytes(b"RIFFfake wave data") + generation_id = env.dal.create_generation(text=text, voice_id="v1", voice_name="Voice One") + env.dal.set_status( + generation_id, + "succeeded", + duration_seconds=2.5, + sample_rate=22_050, + audio_path=str(wav), + word_timings_json=json.dumps( + [{"text": "Hello", "startMs": 10, "endMs": 300, "aligned": True}] + ), + cues_json=json.dumps([{"index": 1, "startMs": 0, "endMs": 2_000, "text": "Hello world"}]), + aligned_word_ratio=0.9, + ) + return generation_id, wav + + +# -- create ------------------------------------------------------------------ + + +def test_create_queues_with_validation_order_and_defaults(env: Env) -> None: + response = env.client.post("/api/generations", json={"text": "Hello world."}) + + assert response.status_code == 202 + assert response.json()["status"] == "queued" + assert uuid.UUID(response.json()["generationId"]) + assert env.jobs.submissions == [ + { + "voice_id": "v1", + "text": "Hello world.", + "source_type": "text", + "rate": 1.0, + "volume": 1.0, + } + ] + assert env.dal.get_settings() == {"defaultVoiceId": "v1", "rate": 1.0, "volume": 1.0} + + +def test_create_uses_persisted_defaults_when_fields_omitted(env: Env) -> None: + env.dal.put_settings({"defaultVoiceId": "v1", "rate": 1.25, "volume": 0.5}) + + response = env.client.post("/api/generations", json={"text": "Hello"}) + + assert response.status_code == 202 + assert env.jobs.submissions[0]["rate"] == 1.25 + assert env.jobs.submissions[0]["volume"] == 0.5 + + +def test_create_empty_text_returns_empty_input(env: Env) -> None: + response = env.client.post("/api/generations", json={"text": " \n"}) + + assert response.status_code == 422 + assert response.json()["error"]["code"] == "EMPTY_INPUT" + assert env.jobs.submissions == [] + + +def test_create_over_limit_returns_input_too_long_with_details(env: Env) -> None: + settings = replace(env.settings, max_input_chars=5) + with TestClient(_app(settings, env.dal, env.jobs)) as client: + response = client.post("/api/generations", json={"text": "six chars"}) + + assert response.status_code == 422 + error = response.json()["error"] + assert error["code"] == "INPUT_TOO_LONG" + assert error["details"] == {"maxChars": 5, "receivedChars": 9} + + +def test_create_without_voices_returns_no_voices(env: Env, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(generations.store, "list_voices", list) + + response = env.client.post("/api/generations", json={"text": "Hello"}) + + assert response.status_code == 409 + assert response.json()["error"]["code"] == "NO_VOICES_INSTALLED" + assert "tts add-voice" in response.json()["error"]["message"] + + +def test_create_unknown_voice_returns_voice_not_found(env: Env) -> None: + response = env.client.post("/api/generations", json={"text": "Hello", "voiceId": "nope"}) + + assert response.status_code == 422 + assert response.json()["error"]["code"] == "VOICE_NOT_FOUND" + + +@pytest.mark.parametrize( + ("field", "value"), + [("rate", 2.1), ("rate", 0.49), ("volume", -0.1), ("volume", 1.1)], +) +def test_create_out_of_range_returns_details(env: Env, field: str, value: float) -> None: + response = env.client.post("/api/generations", json={"text": "Hello", field: value}) + + assert response.status_code == 422 + error = response.json()["error"] + assert error["code"] == "OUT_OF_RANGE" + assert error["details"]["field"] == field + assert "min" in error["details"] and "max" in error["details"] + + +# -- list and detail --------------------------------------------------------- + + +def test_list_maps_summaries_and_pagination(env: Env) -> None: + first, _ = _succeeded_row(env, "First text") + second = env.dal.create_generation(text="Second text", voice_id="v1", voice_name="Voice One") + env.dal.set_status(second, "failed", error={"code": "ENGINE_ERROR", "message": "Boom"}) + + response = env.client.get("/api/generations", params={"limit": 1, "offset": 0}) + + assert response.status_code == 200 + body = response.json() + assert body["total"] == 2 + assert len(body["items"]) == 1 + item = body["items"][0] + assert item["generationId"] == second + assert item["inputPreview"] == "Second text" + assert item["error"] == {"code": "ENGINE_ERROR", "message": "Boom"} + assert "durationSeconds" in item and "createdAt" in item + assert str(first) != second + + +def test_detail_pending_fields_are_null(env: Env) -> None: + generation_id = env.dal.create_generation(text="Hello", voice_id="v1", voice_name="Voice One") + + response = env.client.get(f"/api/generations/{generation_id}") + + assert response.status_code == 200 + body = response.json() + assert body["status"] == "queued" + for key in ("wordTimings", "cues", "alignedWordRatio", "durationSeconds", "sampleRate"): + assert body[key] is None, key + + +def test_detail_succeeded_maps_camel_case_results(env: Env) -> None: + generation_id, _ = _succeeded_row(env) + + response = env.client.get(f"/api/generations/{generation_id}") + + assert response.status_code == 200 + body = response.json() + assert body["text"] == "Hello world this is a test" + assert body["alignedWordRatio"] == 0.9 + assert body["sampleRate"] == 22_050 + assert body["durationSeconds"] == 2.5 + assert body["wordTimings"] == [{"text": "Hello", "startMs": 10, "endMs": 300, "aligned": True}] + assert body["cues"] == [{"index": 1, "startMs": 0, "endMs": 2_000, "text": "Hello world"}] + + +@pytest.mark.parametrize("generation_id", ["not-a-uuid", "00000000-0000-0000-0000-0000000000000"]) +def test_detail_unknown_or_malformed_id_is_not_found(env: Env, generation_id: str) -> None: + response = env.client.get(f"/api/generations/{generation_id}") + + assert response.status_code == 404 + assert response.json()["error"]["code"] == "GENERATION_NOT_FOUND" + + +# -- media ------------------------------------------------------------------- + + +def test_audio_requires_success_and_sets_download_name(env: Env) -> None: + pending = env.dal.create_generation(text="Hello", voice_id="v1", voice_name="Voice One") + assert env.client.get(f"/api/generations/{pending}/audio").status_code == 409 + + generation_id, wav = _succeeded_row(env) + response = env.client.get(f"/api/generations/{generation_id}/audio") + + assert response.status_code == 200 + assert response.content == wav.read_bytes() + assert re.fullmatch( + r'attachment; filename="hello-world-this-is-a-test_\d{8}-\d{6}\.wav"', + response.headers["content-disposition"], + ) + + +def test_subtitles_render_srt_and_vtt_with_named_downloads(env: Env) -> None: + generation_id, _ = _succeeded_row(env) + + srt = env.client.get(f"/api/generations/{generation_id}/subtitles", params={"format": "srt"}) + assert srt.status_code == 200 + assert "Hello world" in srt.text + assert srt.headers["content-disposition"].endswith('.srt"') + + vtt = env.client.get(f"/api/generations/{generation_id}/subtitles", params={"format": "vtt"}) + assert vtt.status_code == 200 + assert vtt.text.startswith("WEBVTT") + assert vtt.headers["content-disposition"].endswith('.vtt"') + + +def test_download_name_caps_slug_at_six_words(env: Env) -> None: + generation_id, _ = _succeeded_row(env, "One two three four five six seven eight") + + response = env.client.get( + f"/api/generations/{generation_id}/subtitles", params={"format": "srt"} + ) + + assert response.status_code == 200 + assert response.headers["content-disposition"].startswith( + 'attachment; filename="one-two-three-four-five-six_' + ) + + +def test_subtitles_bad_format_names_accepted_values(env: Env) -> None: + generation_id, _ = _succeeded_row(env) + + response = env.client.get(f"/api/generations/{generation_id}/subtitles") + + assert response.status_code == 400 + error = response.json()["error"] + assert error["code"] == "SUBTITLE_FORMAT_UNKNOWN" + assert "srt" in error["message"] and "vtt" in error["message"] + + +def test_subtitles_before_success_are_not_ready(env: Env) -> None: + generation_id = env.dal.create_generation(text="Hello", voice_id="v1", voice_name="Voice One") + + response = env.client.get( + f"/api/generations/{generation_id}/subtitles", params={"format": "srt"} + ) + + assert response.status_code == 409 + assert response.json()["error"]["code"] == "GENERATION_NOT_READY" + + +# -- SSE --------------------------------------------------------------------- + + +def test_events_send_retry_then_replay_then_terminal(env: Env) -> None: + generation_id = env.dal.create_generation(text="Hello", voice_id="v1", voice_name="Voice One") + env.jobs.known_ids.add(generation_id) + env.jobs.events = [ + SseEvent( + name="progress", + data={ + "generationId": generation_id, + "status": "running", + "sentenceIndex": 1, + "sentenceCount": 2, + }, + ), + SseEvent( + name="succeeded", + data={"generationId": generation_id, "status": "succeeded", "durationSeconds": 2.5}, + terminal=True, + ), + ] + + with env.client.stream("GET", f"/api/generations/{generation_id}/events") as response: + body = "\n".join(response.iter_lines()) + + assert response.status_code == 200 + assert response.headers["content-type"].startswith("text/event-stream") + assert body.startswith("retry: 3000") + assert "event: progress" in body + assert "event: succeeded" in body + assert generation_id in body + assert env.jobs.subscribed == [generation_id] + + +def test_events_unknown_id_fails_before_stream(env: Env) -> None: + with env.client.stream("GET", "/api/generations/not-a-uuid/events") as response: + response.read() + assert response.status_code == 404 + + with env.client.stream("GET", f"/api/generations/{uuid.uuid4()}/events") as response: + response.read() + assert response.status_code == 404 + assert response.json()["error"]["code"] == "GENERATION_NOT_FOUND" + assert env.jobs.subscribed == [] + + +# -- cancel and delete ------------------------------------------------------- + + +@pytest.mark.parametrize( + ("status", "cancel_result", "expected"), + [("queued", "cancelled", "cancelled"), ("running", "cancelling", "cancelling")], +) +def test_cancel_maps_job_answer( + env: Env, status: str, cancel_result: Literal["cancelled", "cancelling"], expected: str +) -> None: + generation_id = env.dal.create_generation(text="Hello", voice_id="v1", voice_name="Voice One") + env.dal.set_status(generation_id, status) + env.jobs.cancel_result = cancel_result + + response = env.client.post(f"/api/generations/{generation_id}/cancel") + + assert response.status_code == 200 + assert response.json() == {"generationId": generation_id, "status": expected} + + +def test_cancel_already_cancelling_answers_cancelled(env: Env) -> None: + generation_id = env.dal.create_generation(text="Hello", voice_id="v1", voice_name="Voice One") + env.dal.set_status(generation_id, "cancelling") + env.jobs.cancel_result = "cancelling" + + response = env.client.post(f"/api/generations/{generation_id}/cancel") + + assert response.status_code == 200 + assert response.json()["status"] == "cancelled" + + +def test_cancel_terminal_is_busy_and_unknown_is_not_found(env: Env) -> None: + done, _ = _succeeded_row(env) + busy = env.client.post(f"/api/generations/{done}/cancel") + assert busy.status_code == 409 + assert busy.json()["error"]["code"] == "GENERATION_BUSY" + + missing = env.client.post(f"/api/generations/{uuid.uuid4()}/cancel") + assert missing.status_code == 404 + + +def test_delete_removes_row_and_audio(env: Env) -> None: + generation_id, wav = _succeeded_row(env) + + response = env.client.delete(f"/api/generations/{generation_id}") + + assert response.status_code == 204 + assert response.content == b"" + assert env.dal.get(generation_id) is None + assert not wav.exists() + + +def test_delete_active_is_busy_and_unknown_is_not_found(env: Env) -> None: + active = env.dal.create_generation(text="Hello", voice_id="v1", voice_name="Voice One") + busy = env.client.delete(f"/api/generations/{active}") + assert busy.status_code == 409 + assert busy.json()["error"]["code"] == "GENERATION_BUSY" + + missing = env.client.delete(f"/api/generations/{uuid.uuid4()}") + assert missing.status_code == 404 From b6d2e157f435f834007b1864db2d0cdf940b4bd0 Mon Sep 17 00:00:00 2001 From: Prateek Chaplot Date: Sat, 21 Nov 2026 00:39:21 +0530 Subject: [PATCH 2/2] chore(tasks): mark t2.2 doing Verification: 184 unit, 16 integration, Ruff, strict mypy, ESLint, tsc, 34 vitest; PR pending review. --- docs/TASKS.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/TASKS.md b/docs/TASKS.md index a62bfbc..6927383 100644 --- a/docs/TASKS.md +++ b/docs/TASKS.md @@ -29,7 +29,7 @@ Statuses: done (PR merged) · doing (branch open, pending review) · remaining | ID | Task | Branch | Verification | Status | |---|---|---|---|---| -| _(empty — next up: T2.2 on branch `arch/tts/t2.2`)_ | | | | | +| T2.2 | Generations routes | `arch/tts/t2.2` | 184 unit tests (28 new); 16 integration tests (1 new) vs `en_US-lessac-medium`; Ruff check/format; strict mypy; ESLint; `tsc --noEmit`; 34 vitest; `git diff --check` | PR open, awaiting review | ## Remaining @@ -46,7 +46,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.2 | Generations routes | `src/tts/api/routes/generations.py` | T0.3, T1.6 | Create/SSE/cancel/delete, validation/errors, audio and subtitle exports | | 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 @@ -118,3 +117,8 @@ _All P1 tasks done._ - 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. +- 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.