diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 95c3207..abbce04 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -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 \
diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml
index c6ba2a3..69096ed 100644
--- a/.github/workflows/deploy.yml
+++ b/.github/workflows/deploy.yml
@@ -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
@@ -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
docker compose restart nginx
docker image prune -f
diff --git a/Dockerfile b/Dockerfile
index 8db4601..ee8f193 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -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"]
diff --git a/Makefile b/Makefile
index 04437f6..d7461dc 100644
--- a/Makefile
+++ b/Makefile
@@ -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
@@ -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)
diff --git a/README.md b/README.md
index 12c12a2..5f3c179 100644
--- a/README.md
+++ b/README.md
@@ -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 |
@@ -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.
---
diff --git a/app/api/errors.py b/app/api/errors.py
index c20400a..05cce28 100644
--- a/app/api/errors.py
+++ b/app/api/errors.py
@@ -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#"
@@ -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):
@@ -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.
@@ -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_,
@@ -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:
@@ -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),
)
diff --git a/app/api/routes/synthesize.py b/app/api/routes/synthesize.py
index 6cd6758..5f523b0 100644
--- a/app/api/routes/synthesize.py
+++ b/app/api/routes/synthesize.py
@@ -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
@@ -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"),
},
@@ -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
)
@@ -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}"},
)
diff --git a/app/config/settings.py b/app/config/settings.py
index 4028956..448bc68 100644
--- a/app/config/settings.py
+++ b/app/config/settings.py
@@ -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"
@@ -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")
diff --git a/app/core/circuit_breaker.py b/app/core/circuit_breaker.py
index c9dbe2b..6217d4b 100644
--- a/app/core/circuit_breaker.py
+++ b/app/core/circuit_breaker.py
@@ -10,8 +10,9 @@ 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
@@ -19,19 +20,29 @@ def __init__(self, failure_threshold: int, recovery_seconds: float) -> None:
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
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:
diff --git a/app/core/concurrency.py b/app/core/concurrency.py
index 404c866..daef3c8 100644
--- a/app/core/concurrency.py
+++ b/app/core/concurrency.py
@@ -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:
@@ -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()
diff --git a/app/core/daily_limit.py b/app/core/daily_limit.py
index 180ee3e..7bb93c5 100644
--- a/app/core/daily_limit.py
+++ b/app/core/daily_limit.py
@@ -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")
diff --git a/app/core/registry.py b/app/core/registry.py
index d3840cc..f4fef04 100644
--- a/app/core/registry.py
+++ b/app/core/registry.py
@@ -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())
diff --git a/app/core/synthesizer.py b/app/core/synthesizer.py
index 2b5618f..647564f 100644
--- a/app/core/synthesizer.py
+++ b/app/core/synthesizer.py
@@ -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:
diff --git a/app/data/voices/pocket/voices.json b/app/data/voices/pocket/voices.json
index 776464f..4b9f4ab 100644
--- a/app/data/voices/pocket/voices.json
+++ b/app/data/voices/pocket/voices.json
@@ -4,7 +4,7 @@
"originalName": "alba",
"identifier": "urn:readium:tts:pocket:alba",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -13,7 +13,7 @@
"originalName": "anna",
"identifier": "urn:readium:tts:pocket:anna",
"language": "en",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -22,7 +22,7 @@
"originalName": "azelma",
"identifier": "urn:readium:tts:pocket:azelma",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -31,7 +31,7 @@
"originalName": "bill_boerst",
"identifier": "urn:readium:tts:pocket:bill-boerst",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -40,7 +40,7 @@
"originalName": "caro_davy",
"identifier": "urn:readium:tts:pocket:caro-davy",
"language": "en-GB",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -49,7 +49,7 @@
"originalName": "charles",
"identifier": "urn:readium:tts:pocket:charles",
"language": "en",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -58,7 +58,7 @@
"originalName": "cosette",
"identifier": "urn:readium:tts:pocket:cosette",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -67,7 +67,7 @@
"originalName": "eponine",
"identifier": "urn:readium:tts:pocket:eponine",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -76,7 +76,7 @@
"originalName": "eve",
"identifier": "urn:readium:tts:pocket:eve",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -85,7 +85,7 @@
"originalName": "fantine",
"identifier": "urn:readium:tts:pocket:fantine",
"language": "en",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -94,7 +94,7 @@
"originalName": "george",
"identifier": "urn:readium:tts:pocket:george",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -103,7 +103,7 @@
"originalName": "jane",
"identifier": "urn:readium:tts:pocket:jane",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -112,7 +112,7 @@
"originalName": "javert",
"identifier": "urn:readium:tts:pocket:javert",
"language": "en-US",
- "otherLanguages": ["fr-CA", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr-CA", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -121,7 +121,7 @@
"originalName": "jean",
"identifier": "urn:readium:tts:pocket:jean",
"language": "en-US",
- "otherLanguages": ["fr-CA", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr-CA", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -130,7 +130,7 @@
"originalName": "marius",
"identifier": "urn:readium:tts:pocket:marius",
"language": "en-US",
- "otherLanguages": ["fr-CA", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr-CA", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -139,7 +139,7 @@
"originalName": "mary",
"identifier": "urn:readium:tts:pocket:mary",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -148,7 +148,7 @@
"originalName": "michael",
"identifier": "urn:readium:tts:pocket:michael",
"language": "en-US",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -157,7 +157,7 @@
"originalName": "paul",
"identifier": "urn:readium:tts:pocket:paul",
"language": "en-GB",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -166,7 +166,7 @@
"originalName": "peter_yearsley",
"identifier": "urn:readium:tts:pocket:peter-yearsley",
"language": "en",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -175,7 +175,7 @@
"originalName": "stuart_bell",
"identifier": "urn:readium:tts:pocket:stuart-bell",
"language": "en-GB",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -184,7 +184,7 @@
"originalName": "vera",
"identifier": "urn:readium:tts:pocket:vera",
"language": "en",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -193,7 +193,7 @@
"originalName": "estelle",
"identifier": "urn:readium:tts:pocket:estelle",
"language": "fr-FR",
- "otherLanguages": ["en", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["en", "es", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -202,7 +202,7 @@
"originalName": "giovanni",
"identifier": "urn:readium:tts:pocket:giovanni",
"language": "it",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -211,7 +211,7 @@
"originalName": "juergen",
"identifier": "urn:readium:tts:pocket:juergen",
"language": "de",
- "otherLanguages": ["fr", "es", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "es", "de", "it", "pt-PT", "nl"],
"gender": "male",
"quality": "veryHigh"
},
@@ -220,7 +220,7 @@
"originalName": "lola",
"identifier": "urn:readium:tts:pocket:lola",
"language": "es",
- "otherLanguages": ["fr", "en", "de", "it", "pt-PT"],
+ "otherLanguages": ["fr", "en", "de", "it", "pt-PT", "nl"],
"gender": "female",
"quality": "veryHigh"
},
@@ -229,8 +229,16 @@
"originalName": "rafael",
"identifier": "urn:readium:tts:pocket:rafael",
"language": "pt-PT",
- "otherLanguages": ["fr", "en", "de", "it", "es"],
+ "otherLanguages": ["fr", "en", "de", "it", "es", "nl"],
"gender": "male",
"quality": "veryHigh"
+ },
+ {
+ "name": "Daan",
+ "originalName": "daan",
+ "identifier": "urn:readium:tts:pocket:daan",
+ "language": "nl",
+ "otherLanguages": ["fr", "en", "es", "de", "it", "pt-PT"],
+ "quality": "veryHigh"
}
]
diff --git a/app/drivers/ffmpeg.py b/app/drivers/ffmpeg.py
index 1df456c..71d2c60 100644
--- a/app/drivers/ffmpeg.py
+++ b/app/drivers/ffmpeg.py
@@ -6,11 +6,23 @@
# (ffmpeg_args, content-type)
_FORMATS: dict[str, tuple[list[str], str]] = {
"mp3": (["-f", "mp3"], "audio/mpeg"),
- "opus": (["-f", "ogg", "-c:a", "libopus"], "audio/ogg"),
+ "opus": (["-f", "ogg", "-c:a", "libopus", "-application", "voip"], "audio/ogg"),
"wav": ([], "audio/wav"), # wav bypasses ffmpeg; entry here makes content_type() safe
}
+# kbps used when the request gives none, picked on the quality knee measured with PESQ-WB
+# against the 24 kHz source (opus 32k: 4.50, 48k: 4.55, 64k: 4.48; mp3 64k: 4.45, 32k: 3.81,
+# 128k: 4.63). Opus keeps the 8-12 kHz band down to 24k, so 32k loses nothing PESQ can't see.
+# ffmpeg's own mp3 default (~32k here) sounds clearly worse; its opus default (~64k) is larger.
+_DEFAULT_KBPS = {"opus": 32, "mp3": 64}
+
+
+def bitrate_args(format: str, bitrate: int | None) -> list[str]:
+ kbps = bitrate or _DEFAULT_KBPS.get(format)
+ return ["-b:a", f"{kbps}k"] if kbps else []
+
+
def is_available(ffmpeg_bin: str = "ffmpeg") -> bool:
return shutil.which(ffmpeg_bin) is not None
@@ -27,8 +39,6 @@ async def encode(
bitrate: int | None = None,
) -> bytes:
fmt_args, _ = _FORMATS[format]
- bitrate_args = ["-b:a", f"{bitrate}k"] if bitrate else []
-
cmd = [
ffmpeg_bin,
"-f",
@@ -40,7 +50,7 @@ async def encode(
"-i",
"pipe:0",
*fmt_args,
- *bitrate_args,
+ *bitrate_args(format, bitrate),
"-loglevel",
"error",
"pipe:1",
diff --git a/app/main.py b/app/main.py
index dcd76aa..c6acc23 100644
--- a/app/main.py
+++ b/app/main.py
@@ -4,6 +4,7 @@
from contextlib import asynccontextmanager, suppress
from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from starlette.middleware.trustedhost import TrustedHostMiddleware
@@ -40,6 +41,15 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:
init_semaphore(settings.max_concurrent_syntheses)
registry = _build_registry()
+ if (
+ settings.app_env == "production"
+ and "elevenlabs" in {p.id for p in registry.all()}
+ and settings.elevenlabs_daily_char_limit == 0
+ ):
+ logger.warning(
+ "ELEVENLABS_DAILY_CHAR_LIMIT=0 (unlimited) on a public server — anyone can spend "
+ "your ElevenLabs credits. Set a daily cap."
+ )
catalog = VoiceCatalog(registry)
breakers = CircuitBreakerRegistry(
[p.id for p in registry.all()],
@@ -103,6 +113,16 @@ def create_app() -> FastAPI:
allowed_hosts=[settings.domain, "localhost", "127.0.0.1"],
)
app.add_middleware(RequestLoggingMiddleware)
+ if settings.cors_origin_list:
+ # Added last = outermost, so even error responses carry the CORS headers.
+ app.add_middleware(
+ CORSMiddleware,
+ allow_origins=settings.cors_origin_list,
+ allow_methods=["GET", "POST"],
+ allow_headers=["Content-Type"],
+ # Not CORS-safelisted: JS reads them only if exposed (pagination, tracing, backoff).
+ expose_headers=["X-Request-Id", "X-Total-Count", "X-Offset", "X-Limit", "Retry-After"],
+ )
register_error_handlers(app)
app.include_router(health_router)
diff --git a/app/providers/pocket_tts.py b/app/providers/pocket_tts.py
index ba2b618..8ac5aee 100644
--- a/app/providers/pocket_tts.py
+++ b/app/providers/pocket_tts.py
@@ -23,18 +23,18 @@
_VOICES_PATH = Path(__file__).parent.parent / "data" / "voices" / "pocket" / "voices.json"
-# BCP-47 prefix → pocket-tts language identifier. Default to the fast/small 6-layer model for
-# every language that has one. French is the exception: pocket-tts ships only a 24-layer French
-# (`french_24l`), no 6-layer variant. de/es/it/pt/en also have 24-layer (`_24l`) variants that are
-# higher quality but ~3× larger and ~4× slower — not used here. Making this selectable is deferred
-# (see issue); flip a value to its `_24l` form to opt a language into the heavier model.
+# BCP-47 prefix → pocket-tts language identifier (pocket-tts >= 4.0). English is Kyutai's 18.2M
+# flagship (8 layers, d_model 512, ~111 MB), which matches the older ~100M model's quality at ~3.5x
+# the CPU speed; every other language uses its ~100M 6-layer model (~219 MB). The older 24-layer
+# `_24l` models (~672 MB, ~3x larger, slower) are not supported.
_LANG_MODEL: dict[str, str] = {
- "en": "english",
- "fr": "french_24l",
+ "en": "english_18m_2026-10",
+ "fr": "french",
"it": "italian",
"de": "german",
"es": "spanish",
"pt": "portuguese",
+ "nl": "dutch",
}
@@ -90,6 +90,17 @@ def _load_sync(self) -> bool:
unknown,
)
+ for key, langs in add_map.items():
+ missing = langs - enabled
+ if missing and key in known_keys:
+ logger.warning(
+ "VOICE_LANGUAGES adds '%s' for %s, but %s not in LANGUAGES — ignored "
+ "(add the language to LANGUAGES to install it)",
+ key,
+ sorted(missing),
+ "it is" if len(missing) == 1 else "they are",
+ )
+
lang_voices: dict[str, list[tuple[VoiceEntry, str]]] = {}
self._voices = []
for entry in entries:
diff --git a/app/static/demo.html b/app/static/demo.html
index f20c1fd..712f4bd 100644
--- a/app/static/demo.html
+++ b/app/static/demo.html
@@ -6,154 +6,161 @@
Readium Speech Server
@@ -161,7 +168,15 @@
- POST /synthesize · GET /voices · GET /service
+
+
+
+ GitHub
+
Readium Speech Server Demo
@@ -171,6 +186,7 @@
Readium Speech Server Demo
+
@@ -188,7 +204,7 @@
Readium Speech Server Demo
-
+
@@ -229,7 +245,7 @@
Readium Speech Server Demo
-
Bitrate is shown in the API
+
Bitrate is shown in the API
request below — it's the raw output.bitrate escape hatch for developers calling
/synthesize directly. The player itself (via the npm engine) picks its own bitrate
from the strategy/adapt-to-network options above, not from this select.
@@ -251,9 +267,10 @@
Readium Speech Server Demo
import {
SpeechServerEngine,
ReadiumSpeechNavigator,
+ SpeechPreferences,
setupDecorations,
DecorationStyleType,
-} from "https://esm.sh/@readium/speech@0.5.0";
+} from "https://esm.sh/@readium/speech@0.18.0";
const el = id => document.getElementById(id);
const textEl=el('text'), voiceEl=el('voice'), formatEl=el('format'), languageEl=el('language'), vmetaEl=el('vmeta');
@@ -359,12 +376,10 @@
Readium Speech Server Demo
engine = new SpeechServerEngine({ endpoints: ENDPOINTS, fetch: instrumentedFetch, format: currentFormatOptions() });
if (voices.length) engine.setAvailableVoices(voices);
speechNavigator = new ReadiumSpeechNavigator(engine);
- // Content language drives our own language