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
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ jobs:
d=$(mktemp -d); mkdir -p $d/live/ci.test
openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj /CN=ci.test \
-keyout $d/live/ci.test/privkey.pem -out $d/live/ci.test/fullchain.pem
docker run --rm --add-host app:127.0.0.1 -e DOMAIN=ci.test \
docker run --rm --add-host app:127.0.0.1 -e DOMAIN=ci.test -e NGINX_CORS_ORIGIN=https://readium.org \
-v $PWD/nginx/nginx.conf:/etc/nginx/nginx.conf:ro \
-v $PWD/nginx/snippets:/etc/nginx/snippets:ro \
-v $PWD/nginx/templates:/etc/nginx/templates:ro \
Expand Down
4 changes: 3 additions & 1 deletion .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,8 @@ jobs:
username: ${{ secrets.GCP_VM_USER }}
key: ${{ secrets.GCP_SSH_PRIVATE_KEY }}
envs: DOTENV_B64,POCKET_ENV_B64,ELEVENLABS_ENV_B64
# Default is 10m; the script waits up to 12m for readiness (plus the image pull).
command_timeout: 20m
script: |
set -euo pipefail
cd ~/speech-server
Expand All @@ -72,6 +74,6 @@ jobs:
chmod 600 elevenlabs.env
fi
docker compose pull app
docker compose up -d --no-build app
docker compose up -d --no-build --wait --wait-timeout 720 app
Comment thread
ronibhakta1 marked this conversation as resolved.
Resolved
docker compose restart nginx
docker image prune -f
7 changes: 4 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ USER appuser

EXPOSE 8000

# start_period covers first-run model downloads (~240 MB per language)
HEALTHCHECK --interval=30s --timeout=5s --start-period=300s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')"
# /readyz (not /healthz): healthy only once models are loaded, so `compose up --wait` and the
# deploy fail when the load fails. start_period covers first-run downloads (~110-220 MB/language).
HEALTHCHECK --interval=30s --timeout=5s --start-period=600s --retries=3 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/readyz')"

ENTRYPOINT ["/app/scripts/entrypoint.sh"]
17 changes: 10 additions & 7 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
DC = docker compose -f docker-compose.yml -f docker-compose.dev.yml
DC_RUN = $(DC) run --rm --no-deps app
# The runtime image has no dev tools (ruff/pytest/mypy) and its entrypoint ignores arguments, so
# bypass it and sync them first. VOICE_LANGUAGES= keeps a local pocket-tts.env out of the tests.
DC_RUN = $(DC) run --rm --no-deps --entrypoint "" -e VOICE_LANGUAGES= app sh -c
DEV = uv sync --frozen --dev --no-install-project -q

.DEFAULT_GOAL := help

Expand All @@ -22,22 +25,22 @@ dev-docker-build: ## Rebuild then run the dev stack (docker)
$(DC) up --build

test-docker: ## Run unit/route tests (docker)
$(DC_RUN) pytest -m 'not integration and not slow' -v
$(DC_RUN) "$(DEV) && pytest -p no:cacheprovider -m 'not integration and not slow' -v"

test-integration-docker: ## Run integration tests (docker)
$(DC_RUN) pytest -m integration -v
$(DC_RUN) "$(DEV) && pytest -p no:cacheprovider -m integration -v"

lint-docker: ## Run ruff check (docker)
$(DC_RUN) ruff check app/ tests/
$(DC_RUN) "$(DEV) && ruff check --no-cache app/ tests/"

fmt-docker: ## Run ruff format (docker)
$(DC_RUN) ruff format app/ tests/
$(DC_RUN) "$(DEV) && ruff format --no-cache app/ tests/"

fmt-check-docker: ## Check ruff formatting without writing (docker)
$(DC_RUN) ruff format --check app/ tests/
$(DC_RUN) "$(DEV) && ruff format --check --no-cache app/ tests/"

typecheck-docker: ## Run mypy (docker)
$(DC_RUN) mypy app/
$(DC_RUN) "$(DEV) && mypy --cache-dir=/tmp/mypy app/"

ci-docker: lint-docker fmt-check-docker typecheck-docker test-docker ## Run full CI suite (docker)

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Designed to pair with [Readium Speech](https://github.com/readium/speech), Readi
|---|---|
| **API** | `GET /service` · `GET /voices` · `POST /synthesize` |
| **Providers** | [PocketTTS](docs/providers/pocket.md) (local) · [ElevenLabs](docs/providers/elevenlabs.md) (hosted) |
| **Languages** | English · French · Italian · German · Spanish · Portuguese |
| **Languages** | English · French · Italian · German · Spanish · Portuguese · Dutch |
| **Formats** | WAV (default) · MP3 · Opus |
| **Word boundaries** | ElevenLabs (word-level timing marks) |
| **Deployment** | Docker · CPU-only · Single named volume for model weights |
Expand Down Expand Up @@ -46,7 +46,7 @@ curl -s -X POST http://localhost:8000/synthesize \
-o /tmp/speech.wav && open /tmp/speech.wav
```

> **First start** downloads the selected language models (~240 MB each) into a persistent Docker volume. Every restart after that is instant — models are already cached.
> **First start** downloads the selected language models (~110–220 MB each) into a persistent Docker volume. Every restart after that is instant — models are already cached.

---

Expand Down
29 changes: 21 additions & 8 deletions app/api/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
from pydantic import BaseModel
from starlette.exceptions import HTTPException

from app.config.settings import settings

PROBLEM_MEDIA_TYPE = "application/problem+json"
ERROR_BASE = "https://readium.org/speech-server/error#"

Expand All @@ -33,10 +35,13 @@ class AppError(Exception):
code: str = "internal_error"
title: str = "Internal Server Error"

def __init__(self, message: str, detail: str | None = None) -> None:
def __init__(
self, message: str, detail: str | None = None, headers: dict[str, str] | None = None
) -> None:
super().__init__(message)
self.message = message
self.detail = detail
self.headers = headers # extra response headers, e.g. Retry-After


class RequestValidationFailed(AppError):
Expand All @@ -51,12 +56,6 @@ class VoiceNotFound(AppError):
title = "Voice Not Found"


class UnsupportedFormat(AppError):
status_code = 415
code = "unsupported_format"
title = "Unsupported Format"


class VoiceLanguageUnsupported(AppError):
# Requested voice (or voice+language) isn't served here. Deliberately neutral —
# it never reveals *why* (install/config state), only that it's unsupported.
Expand Down Expand Up @@ -105,6 +104,7 @@ def _problem_response(
title: str,
detail: str | None = None,
errors: list[dict[str, Any]] | None = None,
headers: dict[str, str] | None = None,
) -> JSONResponse:
body = ProblemDetail(
type=type_,
Expand All @@ -118,17 +118,29 @@ def _problem_response(
status_code=status,
content=body.model_dump(exclude_none=True),
media_type=PROBLEM_MEDIA_TYPE,
headers=headers,
)


# --- error handlers ---


def _cors_headers(request: Request) -> dict[str, str]:
"""ServerErrorMiddleware sits outside CORSMiddleware, so a 500 would reach an allowed browser
origin without CORS headers (it would see a network error, not our Problem Details)."""
origin = request.headers.get("origin")
if origin and origin in settings.cors_origin_list:
return {"Access-Control-Allow-Origin": origin, "Vary": "Origin"}
return {}


def register_error_handlers(app: FastAPI) -> None:
@app.exception_handler(AppError)
async def handle_app_error(request: Request, exc: AppError) -> JSONResponse:
detail = f"{exc.message}: {exc.detail}" if exc.detail else exc.message
return _problem_response(request, exc.status_code, ERROR_BASE + exc.code, exc.title, detail)
return _problem_response(
request, exc.status_code, ERROR_BASE + exc.code, exc.title, detail, headers=exc.headers
)

@app.exception_handler(HTTPException)
async def handle_http_exception(request: Request, exc: HTTPException) -> JSONResponse:
Expand Down Expand Up @@ -159,4 +171,5 @@ async def handle_unhandled(request: Request, exc: Exception) -> JSONResponse:
ERROR_BASE + AppError.code,
AppError.title,
"An unexpected error occurred.",
headers=_cors_headers(request),
)
9 changes: 4 additions & 5 deletions app/api/routes/synthesize.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import base64

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.responses import JSONResponse, Response

from app.api.deps import SynthesizerDep, require_ready
from app.api.errors import problem_response
Expand Down Expand Up @@ -31,7 +31,6 @@
400: problem_response("Empty text, or no voice given and no default configured"),
404: problem_response("Voice not found, or voice/language not supported here"),
413: problem_response("Text exceeds max length"),
415: problem_response("Unsupported audio format"),
422: problem_response("Request schema validation error"),
503: problem_response("Service starting up (models loading), or provider unavailable"),
},
Expand Down Expand Up @@ -89,7 +88,7 @@
async def synthesize(
request: SynthesizeRequest,
synthesizer: SynthesizerDep,
) -> StreamingResponse | JSONResponse:
) -> Response:
audio_bytes, content_type, boundaries, boundaries_supported = await synthesizer.synthesize(
request
)
Expand All @@ -106,8 +105,8 @@ async def synthesize(
)

ext = content_type.split("/")[-1].replace("mpeg", "mp3")
return StreamingResponse(
iter([audio_bytes]),
return Response(
content=audio_bytes,
media_type=content_type,
headers={"Content-Disposition": f"inline; filename=speech.{ext}"},
)
20 changes: 17 additions & 3 deletions app/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,26 @@ class Settings(BaseSettings):
workers: int = Field(default=1, ge=1)
domain: str = ""

# Auth (off by default for PoC)
# Auth: not implemented — no route checks the key. API_KEY_ENABLED=true is rejected at startup
# so nobody believes the API is locked when it isn't.
api_key_enabled: bool = False
api_key: str = ""

# Browser origins allowed to call the API cross-origin (comma-separated, exact scheme+host).
# Default: the Readium Speech demos at https://readium.org/speech/demo/. Empty = no CORS.
cors_origins: str = "https://readium.org"

@property
def cors_origin_list(self) -> list[str]:
return [o.strip().rstrip("/") for o in self.cors_origins.split(",") if o.strip()]

# Concurrency. Safe hardware-blind floor: 1 = never oversubscribe CPU. Each
# synthesis uses ~2 cores (pocket-tts's generate→decode pipeline), so a 2-core box
# thrashes at 2 under mixed-language load. configure.sh derives a higher value from
# nproc/RAM for bigger hardware.
max_concurrent_syntheses: int = Field(default=1, ge=1)
# How long a request waits for a free synthesis slot before getting 429 "busy".
synthesis_queue_timeout_seconds: float = Field(default=30.0, gt=0)

# Providers
enabled_providers: str = "pocket"
Expand Down Expand Up @@ -127,8 +138,11 @@ def _parse_voice_language_overrides(

@model_validator(mode="after")
def validate_auth_and_providers(self) -> "Settings":
if self.api_key_enabled and not self.api_key:
raise ValueError("API_KEY must be set when API_KEY_ENABLED is true")
if self.api_key_enabled:
raise ValueError(
"API_KEY_ENABLED is not supported yet: no route checks the key, so the API "
"would be open. Unset it (rate limiting is done by nginx)."
)
providers = [p.strip() for p in self.enabled_providers.split(",")]
if self.default_provider not in providers:
raise ValueError(f"DEFAULT_PROVIDER '{self.default_provider}' not in ENABLED_PROVIDERS")
Expand Down
23 changes: 17 additions & 6 deletions app/core/circuit_breaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,28 +10,39 @@ class _State(Enum):

class CircuitBreaker:
"""Per-provider failure gate. Trips OPEN after `failure_threshold` consecutive
failures; rejects calls until `recovery_seconds` has elapsed, then allows one
HALF_OPEN trial call — a success closes it, a failure re-opens it."""
failures; rejects calls until `recovery_seconds` has elapsed, then allows ONE
HALF_OPEN trial call at a time — a success closes it, a failure re-opens it. A trial
that never reports back is retried after another `recovery_seconds`."""

def __init__(self, failure_threshold: int, recovery_seconds: float) -> None:
self._failure_threshold = failure_threshold
self._recovery_seconds = recovery_seconds
self._state = _State.CLOSED
self._failures = 0
self._opened_at = 0.0
self._probe_at = float("-inf")

def allow(self) -> bool:
now = time.monotonic()
if self._state is _State.OPEN:
if time.monotonic() - self._opened_at >= self._recovery_seconds:
self._state = _State.HALF_OPEN
return True
return False
if now - self._opened_at < self._recovery_seconds:
return False
self._state = _State.HALF_OPEN
if self._state is _State.HALF_OPEN:
if now - self._probe_at < self._recovery_seconds:
return False
self._probe_at = now
Comment thread
ronibhakta1 marked this conversation as resolved.
Resolved
return True

def record_success(self) -> None:
self._failures = 0
self._state = _State.CLOSED

def record_neutral(self) -> None:
"""The call ended with a client/quota error, not a provider verdict: free a half-open
trial slot without closing or re-opening the breaker."""
self._probe_at = float("-inf")

def record_failure(self) -> None:
self._failures += 1
if self._state is _State.HALF_OPEN or self._failures >= self._failure_threshold:
Expand Down
16 changes: 15 additions & 1 deletion app/core/concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@

import anyio

from app.api.errors import RateLimited
from app.config.settings import settings

_semaphore: asyncio.Semaphore | None = None
_RETRY_AFTER_SECONDS = "5" # a slot usually frees within one synthesis (a few seconds)


def init_semaphore(max_concurrent: int) -> None:
Expand All @@ -15,10 +19,20 @@ def init_semaphore(max_concurrent: int) -> None:
async def run_inference[T](fn: Callable[..., T], *args: Any) -> T:
"""Offload blocking CPU-bound work to a thread, bounded by the concurrency semaphore.

Waiting for a free slot is capped (SYNTHESIS_QUEUE_TIMEOUT_SECONDS): past that the request
fails fast with 429 instead of queueing behind other work indefinitely.
Callers needing kwargs should wrap with functools.partial before passing.
"""
sem = _semaphore
if sem is None:
raise RuntimeError("Semaphore not initialized — call init_semaphore() at startup.")
async with sem:
try:
await asyncio.wait_for(sem.acquire(), settings.synthesis_queue_timeout_seconds)
except TimeoutError as exc:
raise RateLimited(
"Server is busy — try again shortly.", headers={"Retry-After": _RETRY_AFTER_SECONDS}
) from exc
try:
return await anyio.to_thread.run_sync(fn, *args)
finally:
sem.release()
13 changes: 0 additions & 13 deletions app/core/daily_limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,3 @@ def reserve(path: str, amount: int, limit: int) -> tuple[bool, int]:
return (True, used)
finally:
fcntl.flock(f, fcntl.LOCK_UN)


if __name__ == "__main__": # self-check
import tempfile

fp = str(Path(tempfile.mkdtemp()) / "u.json")
assert reserve(fp, 100, 250) == (True, 100)
assert reserve(fp, 100, 250) == (True, 200)
assert reserve(fp, 100, 250) == (False, 200) # would exceed → rejected, not added
assert reserve(fp, 50, 250) == (True, 250) # exact fit ok
assert reserve(fp, 1, 250)[0] is False # full
assert reserve(fp, 10_000, 0) == (True, 0) # limit 0 = unlimited, untracked
print("daily_limit self-check ok")
3 changes: 0 additions & 3 deletions app/core/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,5 @@ def register(self, provider: TTSProvider) -> None:
raise ValueError(f"Provider '{provider.id}' is already registered")
self._providers[provider.id] = provider

def get(self, provider_id: str) -> TTSProvider | None:
return self._providers.get(provider_id)

def all(self) -> list[TTSProvider]:
return list(self._providers.values())
7 changes: 5 additions & 2 deletions app/core/synthesizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,11 @@ async def synthesize(
# Only provider OUTAGES (5xx) trip the breaker. Client/quota errors — 429 rate
# limit (incl. the daily budget), 404 unsupported voice — are not provider failures
# and must not open the breaker for everyone.
if breaker is not None and exc.status_code >= 500:
breaker.record_failure()
if breaker is not None:
if exc.status_code >= 500:
breaker.record_failure()
else:
breaker.record_neutral()
raise
else:
if breaker is not None:
Expand Down
Loading
Loading