From c495b1b17597aa935e05766dc2a1c586f86bdeb0 Mon Sep 17 00:00:00 2001 From: Roni bhakta <77425964+ronibhakta1@users.noreply.github.com> Date: Wed, 28 Oct 2026 00:22:27 +0530 Subject: [PATCH 1/3] feat: move Pocket TTS to Kyutai 4.x models, add Dutch, update demo Pocket TTS - Bump pocket-tts to 4.0.1 (uv.lock refreshed). - English now uses the 18.2M flagship (english_18m_2026-10): ~111 MB instead of 219 MB, ~3.5x faster on CPU at matching quality. - French switches from french_24l to the new 6-layer french. The 24-layer _24l models are no longer used. - Add Dutch (nl) with the native voice daan; every voice declares nl. - configure.sh and pocket_plan.py know about nl. - prune_weights.py docstring: pocket-tts 4.x pins files to mixed revisions, so pruning stays folder-based. Demo - Pin @readium/speech to 0.18.0 (was 0.5.0). Replace the removed setVoice/setRate/setPitch/setSpeakInContentLanguage calls with submitPreferences(new SpeechPreferences(...)). Docs and tests - Measured sizes and RAM in configuration.md and pocket.md; fix the stale README download size and the API.md language-row fallback claim. - Tests for the model map, installed model configs, voice language coverage and Dutch; integration test for en/fr/nl. Refs readium/speech-server#35, readium/speech-server#36 --- README.md | 2 +- app/data/voices/pocket/voices.json | 60 ++++++++++++--------- app/providers/pocket_tts.py | 14 ++--- app/static/demo.html | 27 +++++----- docs/API.md | 2 +- docs/configuration.md | 29 +++++----- docs/providers/pocket.md | 28 +++++----- docs/voices.md | 2 +- pyproject.toml | 2 +- scripts/configure.sh | 3 +- scripts/pocket_plan.py | 4 +- scripts/prune_weights.py | 11 ++-- tests/integration/test_pocket_tts.py | 27 ++++++++++ tests/test_language_filter.py | 10 ++-- tests/test_pocket_models.py | 63 ++++++++++++++++++++++ uv.lock | 81 ++++++++++++++++++---------- 16 files changed, 244 insertions(+), 121 deletions(-) create mode 100644 tests/test_pocket_models.py diff --git a/README.md b/README.md index 12c12a2..dd05a9e 100644 --- a/README.md +++ b/README.md @@ -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/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/providers/pocket_tts.py b/app/providers/pocket_tts.py index ba2b618..ff70435 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", } diff --git a/app/static/demo.html b/app/static/demo.html index f20c1fd..17c4cf1 100644 --- a/app/static/demo.html +++ b/app/static/demo.html @@ -251,9 +251,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 +360,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 sets. bindNavigatorEvents(speechNavigator); - if (prevVoiceId) speechNavigator.setVoice(prevVoiceId); + if (prevVoiceId) await speechNavigator.submitPreferences(new SpeechPreferences({ voice: prevVoiceId })); } let langDisplay; try { langDisplay = new Intl.DisplayNames(['en'],{type:'language'}); } catch { langDisplay = null; } const nameOfLang = c => (langDisplay ? langDisplay.of(c) : c) || c; @@ -494,12 +493,12 @@

Readium Speech Server Demo

} function progressNow() { const d = dur(); return d ? Math.min(1, currentPlaybackTime() / d) : 0; } -/* ponytail: SpeechServerEngine (0.5.0) has no public playback-position or seek API — it +/* ponytail: SpeechServerEngine (0.18.0) has no public playback-position or seek API — it schedules AudioBufferSourceNodes on a private AudioContext and never exposes them. This reaches into engine.audioContext/scheduledChunks/handleUtteranceEnded (private fields, accessible at runtime since TS `private` is compile-time only) to read position and to reschedule nodes at an offset via AudioBufferSourceNode.start(when, offset) — the only way - Web Audio supports seeking a started source. Pinned to @readium/speech@0.5.0's internal + Web Audio supports seeking a started source. Pinned to @readium/speech@0.18.0's internal shape; drop this the moment the engine ships a public seek()/getCurrentTime(). */ function chunkRanges() { const scheduled = engine && engine['scheduledChunks']; @@ -707,15 +706,19 @@

Readium Speech Server Demo

nav.on('end', onTransportEnd); } -function speak() { +async function speak() { if (!textEl.value.trim()) { showError('Write some text first.'); textEl.focus(); return; } if (!voiceEl.value) { showError('No voice selected.'); return; } clearError(); speakBtn.disabled = true; speakLabel.textContent = 'Synthesizing…'; - speechNavigator.setVoice(voiceEl.value); - speechNavigator.setRate(speedEl.value && !speedEl.disabled ? (parseFloat(speedEl.value) || 1) : 1); - if (pitchEl.value && !pitchEl.disabled) speechNavigator.setPitch(parseFloat(pitchEl.value)); + // voice / rate / pitch are Preferences since 0.15.0 (setVoice/setRate/setPitch were removed). + const prefs = { + voice: voiceEl.value, + rate: speedEl.value && !speedEl.disabled ? (parseFloat(speedEl.value) || 1) : 1, + }; + if (pitchEl.value && !pitchEl.disabled) prefs.pitch = parseFloat(pitchEl.value); + await speechNavigator.submitPreferences(new SpeechPreferences(prefs)); const ssmlOn = ssmlEl.checked && !ssmlEl.disabled; const utterance = { language: languageEl.value }; diff --git a/docs/API.md b/docs/API.md index a65e3f7..0a411a2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -208,7 +208,7 @@ Only `text` is required; everything else defaults as shown (`voice` falls back t | `id` | string \| null | `null` | Client-generated UUID v7 URN. Parsed, logged, **not otherwise used** — no caching or idempotency yet ([roadmap](#not-implemented)) | | `text` | string | — | Max `MAX_TEXT_LENGTH` chars (2000 default). Rejected if empty/whitespace after trim | | `ssml` | bool | `false` | PocketTTS strips tags before synthesis (regex `<[^>]+>` removal) — no SSML-aware prosody | -| `language` | string \| null | `null` | For voices installed across more than one language (`VOICE_LANGUAGES=*:*` or an explicit override), picks which installed language to synthesize in; falls back to the voice's primary language if unset or not installed for that voice | +| `language` | string \| null | `null` | For voices installed across more than one language (`VOICE_LANGUAGES=*:*` or an explicit override), picks which installed language to synthesize in; unset = the voice's primary language. A language the voice isn't installed for is rejected (no fallback) | | `voice` | string \| null | `null` | A voice `identifier` from `/voices`, or a raw `originalName`. 404 if not found. When omitted, falls back to `POCKET_DEFAULT_VOICE`; if that's unset too, `400` | | `prev_utterance` / `next_utterance` | string \| null | `null` | Accepted, passed into `SynthesisParams`; PocketTTS ignores both | | `publication_id` | string \| null | `null` | Accepted, currently unused (reserved for future cache scoping) | diff --git a/docs/configuration.md b/docs/configuration.md index 96cc2cc..ddf2817 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -50,7 +50,7 @@ A linear two-step flow: pick languages first, then choose coverage over them. **Languages** re-runs the same multi-select as first-time setup — whatever you check becomes `LANGUAGES` (the ceiling: the base models that load). Newly-added languages download once on next -restart (~219 MB for en/it/pt, ~672 MB for fr/de/es); removed languages keep their model files in +restart (~111 MB for en, ~219 MB for each other language); removed languages keep their model files in the Docker volume — see [Disk space](#disk-space) to reclaim selectively. **Voice coverage** chooses what installs on top of the native defaults (see @@ -92,7 +92,7 @@ only ever *adds* cross-language support: | Variable | Default | Description | |---|---|---| -| `LANGUAGES` | _(empty)_ | Comma-separated BCP-47 language codes to **load as base models**. No hardcoded fallback — env-driven; unset means no base models load (no voices served). Size per language is *not* uniform: the 6-layer `en`/`it`/`de`/`es`/`pt` models are ~219 MB download / ~438 MB RAM; the 24-layer `fr` model is ~672 MB download / ~1344 MB RAM (loaded size ~2x the download, measured at startup). Supported: `en fr it de es pt`. This is the ceiling — nothing below can exceed it | +| `LANGUAGES` | _(empty)_ | Comma-separated BCP-47 language codes to **load as base models**. No hardcoded fallback — env-driven; unset means no base models load (no voices served). Size per language is *not* uniform: see [model sizes](#model-sizes--ram). Supported: `en fr it de es pt nl`. This is the ceiling — nothing below can exceed it | | `VOICE_LANGUAGES` | _(empty)_ | Which voices get warmed against which of those loaded models, beyond each voice's own primary — see [Per-voice language overrides](#per-voice-language-overrides) | | `POCKET_DEFAULT_VOICE` | _(empty)_ | Default voice when none is specified. No hardcoded fallback — env-driven; empty means the setting is unset | @@ -160,24 +160,23 @@ The wizard deliberately keeps sizes out of its prompts — they live here. All f `kyutai/pocket-tts-without-voice-cloning` models (what the server loads without gated access) and are approximate. -**Base language model** — one per selected language, loaded once per worker. Two size classes: +**Base language model** — one per selected language, loaded once per worker. Download is the +Hugging Face file size; RAM is the whole server process (including the torch runtime) measured after +loading that one language with its native voices, on pocket-tts 4.0.1: -| Languages | Layers | Download (disk, once) | RAM (per worker) | +| Language | Layers | Download (disk, once) | Process RAM (per worker) | |---|---|---|---| -| `en` `it` `de` `es` `pt` | 6 | ~219 MB | ~438 MB | -| `fr` | 24 (`_24l`) | ~672 MB | ~1344 MB | +| `en` (`english_18m_2026-10`) | 8 (d_model 512) | ~111 MB | ~540 MB (21 voices) | +| `fr` | 6 | ~219 MB | ~880 MB (1 voice) | +| `it` `de` `es` `pt` `nl` | 6 | ~219 MB | not measured; expect about the `fr` figure | -RAM ≈ 2× the download (measured at startup). This is the dominant cost. +This is the dominant cost. Loading `en`+`fr`+`nl` with every voice cross-installed (`VOICE_LANGUAGES=*:*`) +used ~1.6 GB. Add a language and its whole base model is added per worker. -**Voice embedding** — one per installed `(voice, language)`, small: ~6 MB into a 6-layer language, -~25–33 MB into a 24-layer language. Native voices carry one; each cross-language pair adds one more. +**Voice embedding** — one per installed `(voice, language)`, small: ~6 MB into a language model. +Native voices carry one; each cross-language pair adds one more. -**RAM formula:** `WORKERS × (sum of each active language's RAM size)`. -Example: 1 worker, English + French = `438 + 1344 ≈ 1782 MB` RAM (download ~891 MB base + a few -hundred MB of embeddings). Add a language, and its whole base model is added per worker. - -To see the exact **voice/pair count** for your config (not sizes), the wizard's config view uses -`scripts/pocket_plan.py`. +**RAM:** `WORKERS × (RAM of each active language)`, plus embeddings. Measure on your own hardware before sizing `WORKERS`. ## Disk space diff --git a/docs/providers/pocket.md b/docs/providers/pocket.md index 5b08f1c..73337c7 100644 --- a/docs/providers/pocket.md +++ b/docs/providers/pocket.md @@ -38,7 +38,7 @@ re-encoding (the default, and fastest — no ffmpeg). The server can transcode o ## Languages & voices -- **Native languages:** `en` `fr` `it` `de` `es` `pt`. English ships many voices; each other +- **Native languages:** `en` `fr` `it` `de` `es` `pt` `nl`. English ships many voices; each other language ships one native voice. - **Cross-language:** any voice can also speak the languages it declares in `otherLanguages`, *if* that `(voice, language)` pair is installed (`VOICE_LANGUAGES`). A voice needs the target @@ -50,23 +50,19 @@ re-encoding (the default, and fastest — no ffmpeg). The server can transcode o ## Constraints - CPU only; torch ≥ 2.5 CPU build. Throughput scales by worker processes. -- **Model variant:** most languages ship both a fast/small **6-layer** model and a slower/bigger - higher-quality **24-layer** (`_24l`) one. We default to **6-layer** everywhere it exists. - French is the exception — pocket-tts ships only a 24-layer French, so `fr` is always 24-layer. +- **Models:** one model per language, pinned in `_LANG_MODEL` (`app/providers/pocket_tts.py`), + all from pocket-tts ≥ 4.0. The older 24-layer (`_24l`) models are not supported. - | Lang | 6-layer | 24-layer | Used | + | Lang | Model | Layers | Download | |---|---|---|---| - | `en` | `english` | — | 6-layer | - | `fr` | — | `french_24l` | **24-layer (only option)** | - | `it` | `italian` | `italian_24l` | 6-layer | - | `de` | `german` | `german_24l` | 6-layer | - | `es` | `spanish` | `spanish_24l` | 6-layer | - | `pt` | `portuguese` | `portuguese_24l` | 6-layer | - - (This is why you see `french_24l` but plain `spanish`/`german` — not an inconsistency; French - has no 6-layer.) The mapping lives in `_LANG_MODEL` (`app/providers/pocket_tts.py`). Making the - 6l/24l choice user-selectable per language is **deferred** pending need — see the follow-up - issue. + | `en` | `english_18m_2026-10` (Kyutai 18.2M flagship) | 8 (d_model 512) | ~111 MB | + | `fr` | `french` | 6 | ~219 MB | + | `it` | `italian` | 6 | ~219 MB | + | `de` | `german` | 6 | ~219 MB | + | `es` | `spanish` | 6 | ~219 MB | + | `pt` | `portuguese` | 6 | ~219 MB | + | `nl` | `dutch` | 6 | ~219 MB | + - Each model uses ~2 CPU cores via an internal generate→decode pipeline and pins torch to a single intra-op thread itself (on import) — so we don't set `torch.set_num_threads()`. Give the box more cores by running more workers, not more threads per model. diff --git a/docs/voices.md b/docs/voices.md index e938fc6..a02c3e0 100644 --- a/docs/voices.md +++ b/docs/voices.md @@ -52,7 +52,7 @@ languages without repeating it per voice. PocketTTS pre-computes voice embeddings per voice per language (stored as `.safetensors` files under `kyutai/pocket-tts-without-voice-cloning`), sized by the target language's model: -~5–8 MB into the 6-layer `en`/`it`/`de`/`es`/`pt` models, ~24–33 MB into the 24-layer `fr`. The embedding is warmed once at +~5–8 MB into each language model. The embedding is warmed once at model-load time — no per-request cloning overhead — but only for the (voice, language) pairs `VOICE_LANGUAGES` and `LANGUAGES` actually call for. Unused language weights can be reclaimed from the Docker volume with `scripts/prune_weights.py` — see [Configuration → disk space](configuration.md). diff --git a/pyproject.toml b/pyproject.toml index a88b095..686f9f8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ dependencies = [ "httpx>=0.27.0", "anyio>=4.0.0", "torch>=2.5", - "pocket-tts>=0.1.0", + "pocket-tts>=4.0.1", ] [dependency-groups] diff --git a/scripts/configure.sh b/scripts/configure.sh index 9fa3bf8..bc721eb 100755 --- a/scripts/configure.sh +++ b/scripts/configure.sh @@ -150,7 +150,7 @@ _migrate_voice_install_mode() { } # ── Language helpers ────────────────────────────────────────────────────────── -ALL_LANGS=(en fr it de es pt) +ALL_LANGS=(en fr it de es pt nl) BASE_LANGS="" # protected language base while custom coverage is being edited lang_name() { @@ -158,6 +158,7 @@ lang_name() { en) echo "English" ;; fr) echo "French" ;; it) echo "Italian" ;; de) echo "German" ;; es) echo "Spanish" ;; pt) echo "Portuguese" ;; + nl) echo "Dutch" ;; hi) echo "Hindi" ;; *) echo "$1" ;; esac diff --git a/scripts/pocket_plan.py b/scripts/pocket_plan.py index bc60c09..ed577f0 100755 --- a/scripts/pocket_plan.py +++ b/scripts/pocket_plan.py @@ -23,7 +23,7 @@ sys.path.insert(0, str(Path(__file__).parent.parent)) from app.providers.voice_loading import VoiceEntry, plan_install # noqa: E402 -SUPPORTED = ("en", "fr", "it", "de", "es", "pt") +SUPPORTED = ("en", "fr", "it", "de", "es", "pt", "nl") def _split(csv: str) -> list[str]: @@ -138,7 +138,7 @@ def _selftest() -> None: # all + en,fr: every voice that can speak a selected language installs — incl. # non-native-primary ones (giovanni/lola/... speaking fr/en cross-language). a = plan(vj, "en,fr", "*:*") - assert a["mode"] == "all" and a["installed_voices"] == 26 and a["cross_pairs"] == 28, a + assert a["mode"] == "all" and a["installed_voices"] == 27 and a["cross_pairs"] == 30, a c = plan(vj, "en,fr", "alba:fr") assert c["mode"] == "custom" and c["cross_pairs"] == 1, c diff --git a/scripts/prune_weights.py b/scripts/prune_weights.py index 4e6c587..2f80b52 100644 --- a/scripts/prune_weights.py +++ b/scripts/prune_weights.py @@ -9,11 +9,12 @@ PocketTTS caches everything — base model, tokenizer, and per-voice embeddings — under `languages//` inside two HuggingFace repos (`kyutai/pocket-tts` and -`kyutai/pocket-tts-without-voice-cloning`), sharing one snapshot revision per -repo (confirmed by reading pocket_tts's own config/*.yaml and utils/utils.py — -every language config references the same two revision hashes). That makes -per-language pruning safe: each language's files live under one exclusive path -prefix, distinct from every other language's. +`kyutai/pocket-tts-without-voice-cloning`). Revisions are NOT uniform: with pocket-tts 4.x +the model, tokenizer and embedding files of one language are pinned to different revisions, and +older pocket-tts versions leave older snapshots in the cache. Pruning is therefore by language +folder name across every snapshot: it removes folders no longer in the install plan (e.g. the old +`english`, `french_24l`) but keeps a kept folder's older-revision copy (wasted disk, never loaded). +Each language's files live under one exclusive path prefix, distinct from every other language's. Content-addressed HF cache layout means each snapshot file is a symlink into `blobs/`. Before deleting a blob, this script confirms no OTHER diff --git a/tests/integration/test_pocket_tts.py b/tests/integration/test_pocket_tts.py index 5abead5..2430b4a 100644 --- a/tests/integration/test_pocket_tts.py +++ b/tests/integration/test_pocket_tts.py @@ -79,3 +79,30 @@ def params(text: str) -> SynthesisParams: ) ) async def test_speed_affects_duration(pocket: PocketTTSProvider) -> None: ... + + +async def test_default_models_speak_en_fr_nl(monkeypatch: pytest.MonkeyPatch) -> None: + from app.config.settings import settings + + monkeypatch.setattr(settings, "languages", "en,fr,nl") + p = PocketTTSProvider() + await p.load() + voices = await p.list_voices() + for lang, text in [ + ("en", "Hello world."), + ("fr", "Bonjour le monde."), + ("nl", "Hallo wereld."), + ]: + v = next(v for v in voices if v.language.startswith(lang)) + result = await p.synthesize( + SynthesisParams( + text=text, + ssml=False, + language=None, + voice_uri=v.identifier, + speed=1.0, + pitch=None, + ) + ) + assert_valid_pcm(result) + assert result.sample_rate == 24000 diff --git a/tests/test_language_filter.py b/tests/test_language_filter.py index e60e5c8..f8e1174 100644 --- a/tests/test_language_filter.py +++ b/tests/test_language_filter.py @@ -11,7 +11,7 @@ from app.config.settings import Settings _POCKET_JSON = Path(__file__).parent.parent / "app" / "data" / "voices" / "pocket" / "voices.json" -_SUPPORTED = {"en", "fr", "it", "de", "es", "pt"} +_SUPPORTED = {"en", "fr", "it", "de", "es", "pt", "nl"} @contextmanager @@ -36,7 +36,7 @@ def test_pocket_json_covers_all_supported_languages() -> None: def test_pocket_json_english_voice_count() -> None: voices = json.loads(_POCKET_JSON.read_text()) en = [v for v in voices if v["language"].split("-")[0].lower() == "en"] - assert len(en) == 21 # voices whose PRIMARY language is English (not all 26 — each + assert len(en) == 21 # voices whose PRIMARY language is English (not all 27 — each # voice appears once now, not duplicated per language) @@ -139,7 +139,7 @@ async def test_list_voices_filters_to_single_language() -> None: with language_config(*langs): result = await provider.list_voices() assert all("fr" in _prefixes(v) for v in result) - assert len(result) == 26 # every voice declares French as primary or additional + assert len(result) == 27 # every voice declares French as primary or additional @pytest.mark.asyncio @@ -148,7 +148,7 @@ async def test_list_voices_multiple_languages() -> None: with language_config(*langs): result = await provider.list_voices() assert all({"en", "fr"} & _prefixes(v) for v in result) - assert len(result) == 26 # each voice counted once, not per matching language + assert len(result) == 27 # each voice counted once, not per matching language @pytest.mark.asyncio @@ -156,7 +156,7 @@ async def test_list_voices_all_languages_returns_all() -> None: provider, langs = _loaded_provider(*_SUPPORTED) with language_config(*langs): result = await provider.list_voices() - assert len(result) == 26 # all voices, each still counted once + assert len(result) == 27 # all voices, each still counted once @pytest.mark.asyncio diff --git a/tests/test_pocket_models.py b/tests/test_pocket_models.py new file mode 100644 index 0000000..23e3490 --- /dev/null +++ b/tests/test_pocket_models.py @@ -0,0 +1,63 @@ +"""Pocket model map + Dutch data — fast, no model download.""" + +import json +import subprocess +import sys +from importlib.util import find_spec +from pathlib import Path + +import pytest + +from app.providers.pocket_tts import _LANG_MODEL, _VOICES_PATH, PocketTTSProvider + +_ROOT = Path(__file__).parent.parent + + +def test_defaults_are_new_models() -> None: + assert _LANG_MODEL["en"] == "english_18m_2026-10" + assert _LANG_MODEL["fr"] == "french" + assert _LANG_MODEL["nl"] == "dutch" + + +def test_no_legacy_24_layer_models() -> None: + assert not [m for m in _LANG_MODEL.values() if "24l" in m] + + +def test_supported_languages_match_model_map() -> None: + assert PocketTTSProvider.supported_languages == frozenset(_LANG_MODEL) + + +def test_every_model_ships_in_installed_pocket_tts() -> None: + spec = find_spec("pocket_tts") + assert spec and spec.submodule_search_locations + configs = Path(next(iter(spec.submodule_search_locations))) / "config" + for model in _LANG_MODEL.values(): + assert (configs / f"{model}.yaml").is_file(), f"{model} missing in pocket-tts" + + +def test_every_voice_language_has_a_model() -> None: + for v in json.loads(_VOICES_PATH.read_text()): + langs = {v["language"].split("-")[0].lower()} | { + code.split("-")[0].lower() for code in v.get("otherLanguages", []) + } + assert langs <= set(_LANG_MODEL), (v["originalName"], langs - set(_LANG_MODEL)) + + +def test_daan_is_native_dutch() -> None: + daan = next(v for v in json.loads(_VOICES_PATH.read_text()) if v["originalName"] == "daan") + assert daan["language"].split("-")[0] == "nl" + + +def test_pocket_plan_selftest() -> None: + subprocess.run( + [sys.executable, str(_ROOT / "scripts" / "pocket_plan.py"), "--selftest"], check=True + ) + + +@pytest.mark.parametrize("lang", ["fr", "nl"]) +def test_every_voice_declares_dutch_and_french(lang: str) -> None: + for v in json.loads(_VOICES_PATH.read_text()): + langs = {v["language"].split("-")[0].lower()} | { + c.split("-")[0].lower() for c in v.get("otherLanguages", []) + } + assert lang in langs, v["originalName"] diff --git a/uv.lock b/uv.lock index 1e60e47..ffeec29 100644 --- a/uv.lock +++ b/uv.lock @@ -78,15 +78,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/45/19/cc8bd127d28a43da249aa955cfd164cf8fd534e79e42cea96c4854d72fd0/ast_serialize-0.5.0-cp39-abi3-win_arm64.whl", hash = "sha256:92a31c9c20d25a076edaeec76b128a3535d74a24f340b9a8a7e96c9b86dc9642", size = 1081181, upload-time = "2026-05-17T17:48:28.122Z" }, ] -[[package]] -name = "beartype" -version = "0.22.9" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c7/94/1009e248bbfbab11397abca7193bea6626806be9a327d399810d523a07cb/beartype-0.22.9.tar.gz", hash = "sha256:8f82b54aa723a2848a56008d18875f91c1db02c32ef6a62319a002e3e25a975f", size = 1608866, upload-time = "2025-12-13T06:50:30.72Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/71/cc/18245721fa7747065ab478316c7fea7c74777d07f37ae60db2e84f8172e8/beartype-0.22.9-py3-none-any.whl", hash = "sha256:d16c9bbc61ea14637596c5f6fbff2ee99cbe3573e46a716401734ef50c3060c2", size = 1333658, upload-time = "2025-12-13T06:50:28.266Z" }, -] - [[package]] name = "certifi" version = "2026.6.17" @@ -684,10 +675,9 @@ wheels = [ [[package]] name = "pocket-tts" -version = "2.1.0" +version = "4.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "beartype" }, { name = "einops" }, { name = "fastapi" }, { name = "huggingface-hub" }, @@ -698,15 +688,16 @@ dependencies = [ { name = "safetensors" }, { name = "scipy" }, { name = "sentencepiece" }, + { name = "tokenizers" }, { name = "torch", version = "2.12.1", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "python_full_version < '3.15' and sys_platform == 'darwin'" }, { name = "torch", version = "2.12.1+cpu", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "python_full_version >= '3.15' or sys_platform != 'darwin'" }, { name = "typer" }, { name = "typing-extensions" }, { name = "uvicorn" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/f9/2c/7445f57163bb40e2b2fab4df70d18a4216c4965cdf74196344d95859fc07/pocket_tts-2.1.0.tar.gz", hash = "sha256:6f244f445413400f686506f5ccfb75048547caab7b455b927f4a854c551c60a8", size = 642108, upload-time = "2026-05-04T14:00:29.207Z" } +sdist = { url = "https://files.pythonhosted.org/packages/03/a5/e787a6b68ad100c1f33539e3f9108b32a08d65d94d18996927a3562cdd38/pocket_tts-4.0.1.tar.gz", hash = "sha256:bf3eb338bc5f80793afcff438cbbde33c62b8d1d43f7188a74df8b64c620a6fd", size = 912980, upload-time = "2026-10-21T13:15:19.116Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/cf/63/d16958d388efee3f0fc7287e1418ed652ddbc2b61ff4f581f0ad0abce625/pocket_tts-2.1.0-py3-none-any.whl", hash = "sha256:7b8f01d3e52aa7df84887b711994586bdc875e024a8b40a15f757feeeb29f752", size = 68096, upload-time = "2026-05-04T14:00:27.547Z" }, + { url = "https://files.pythonhosted.org/packages/6c/33/e95df6d67fac720836b8240cb2512a253c0e64da85b9c485df31aad0ce71/pocket_tts-4.0.1-py3-none-any.whl", hash = "sha256:a6baf5fd9195399a632d7ef1cb75d4ee772b8d3534c85b90164b39c687a69961", size = 100708, upload-time = "2026-10-21T13:15:17.127Z" }, ] [[package]] @@ -1139,7 +1130,7 @@ requires-dist = [ { name = "anyio", specifier = ">=4.0.0" }, { name = "fastapi", specifier = ">=0.115.0" }, { name = "httpx", specifier = ">=0.27.0" }, - { name = "pocket-tts", specifier = ">=0.1.0" }, + { name = "pocket-tts", specifier = ">=4.0.1" }, { name = "pydantic", specifier = ">=2.0.0" }, { name = "pydantic-settings", specifier = ">=2.0.0" }, { name = "torch", specifier = ">=2.5", index = "https://download.pytorch.org/whl/cpu" }, @@ -1180,6 +1171,40 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, ] +[[package]] +name = "tokenizers" +version = "0.23.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e0/7c/2cabb2174e772636683008f2c5621949b645da7d303c596589e84516a184/tokenizers-0.23.3.tar.gz", hash = "sha256:cded33237c77caeef62944d32aa9a7ef42bdce2b3497e18d137e072a8c4be438", size = 385286, upload-time = "2026-10-09T10:16:55.759Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/aa/2e/4ce5b9716f26e526eff6b0502ebed4ea8d7161f03b3c77617c9f25528e97/tokenizers-0.23.3-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:9d2b5c97daf61688c2ad1803ca851800feaba50fb68d5821779e9ea5880d968c", size = 3148800, upload-time = "2026-10-09T10:00:51.457Z" }, + { url = "https://files.pythonhosted.org/packages/b2/72/01e49f032bb346e5aaf06c10c74fe8aeec847173adbadd66eb7c53054bf2/tokenizers-0.23.3-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:68649e97d5b43c44c031d8d848874a6eecae8f8fe40ea989aa777a5a83aca716", size = 3101381, upload-time = "2026-10-09T10:00:54.063Z" }, + { url = "https://files.pythonhosted.org/packages/15/fc/ae987741829b1cd547668c4c94be732ae3eefd1d74344e64c3d2ca714acd/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec82e80e65a862275b97c3d90b7a523df8d9519ee48aeb4e9625b2cc909274e0", size = 3519944, upload-time = "2026-10-09T10:00:55.885Z" }, + { url = "https://files.pythonhosted.org/packages/1c/da/cc8f6c030afaf05fbddc608158fbb761dca46913cbeba6b112e59fc82e2a/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c64a0713180ff16829d4e7f39a658b77ea11443af4e1aa46523692943c9b1414", size = 3397695, upload-time = "2026-10-09T10:00:57.444Z" }, + { url = "https://files.pythonhosted.org/packages/ec/f1/256f78d1365fa2cd3ea6db716883d74667c8cbb6a21f15fa5b89a773cdc2/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ddedfd4b3b4be6be24ff6ca645c4a37fddfd305f6f3e354c54cf10b715c48215", size = 3753125, upload-time = "2026-10-09T10:01:00.165Z" }, + { url = "https://files.pythonhosted.org/packages/60/93/eee007ac2fcbf4ecfce7fbc354826cf3611f56bdb886f3e91b1f7dd06b8f/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:2a89614730d7b80940a5d2ed9320e1ec8add5a745c6151d8d05071b7215505b6", size = 4018598, upload-time = "2026-10-09T10:01:02.05Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f9/0c96c4739461fce9d8d865b416728081bf6230022d7163bd6244f35f4b31/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:e88646b8580c5ad7f4361477f1298e9cc01771a1ee9aecfe32c47b8ff614cc38", size = 3602442, upload-time = "2026-10-09T10:01:03.77Z" }, + { url = "https://files.pythonhosted.org/packages/3a/40/6706b82693715581457c6d5423eaa7faae576bb0526c5738a57085eb4449/tokenizers-0.23.3-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:376851d22bcf9d650a5c3090bb83e6cf9e895fbf0595369fa4cd43c1f69b5f87", size = 3396193, upload-time = "2026-10-09T10:01:05.48Z" }, + { url = "https://files.pythonhosted.org/packages/fe/0c/85946de40e25b7364b8f1bcf56def129069acd5bb364b7c86a32919e1a23/tokenizers-0.23.3-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:bf501c40b72d2d5c8623620210430e9cac1ce47a46e45b34107b70a1557d46b0", size = 3553483, upload-time = "2026-10-09T10:01:07.387Z" }, + { url = "https://files.pythonhosted.org/packages/f1/6b/8d615d92cad1d511ca5ab188d1c7c167f0b3d295cc0d96207f9f82d486d8/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:114e2b55ed177179d59f4ab98200a4471e11e78f9e4b5a922d146740f96fcf52", size = 9972248, upload-time = "2026-10-09T10:01:09.437Z" }, + { url = "https://files.pythonhosted.org/packages/c9/7d/a922e37ddd58d1b463bbc2ad08120c8f59c60b814cd353519a116b24f8ba/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:d3407fb7b9c4d75dd68850ffd7180bc0a5d2dbaf0762d888e612f31fec3f9c6b", size = 9802957, upload-time = "2026-10-09T10:01:11.869Z" }, + { url = "https://files.pythonhosted.org/packages/4b/06/5d3f506a86ae0699a0e4ea05c05978f9aee169ef2c1d844e68c971cf8194/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:84513ef0aeb8bf8f4ea11a2e8a7ac163ec5288aa115e649a59b470ac5c3107df", size = 10145487, upload-time = "2026-10-09T10:01:14.268Z" }, + { url = "https://files.pythonhosted.org/packages/26/e5/065625317690ea3548d834dad81f48ea1fd32e4964610e658e195d7fe28e/tokenizers-0.23.3-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:e05ab7baf7f47b406a95fea6f3b0a484b2ddcd9e1d14b68844c457eb755085a3", size = 10266026, upload-time = "2026-10-09T10:16:33.054Z" }, + { url = "https://files.pythonhosted.org/packages/77/4e/babede85d0d19f5e3deeef0063e01848141329934d3d77c31b5cab5ac2b4/tokenizers-0.23.3-cp310-abi3-win32.whl", hash = "sha256:1ebf28794e7e4954e20a7f70fbea410b2d1f0418f7dbbca97ca384fcfef38c25", size = 2588086, upload-time = "2026-10-09T10:16:35.686Z" }, + { url = "https://files.pythonhosted.org/packages/d1/6c/24f074c9a0efb98e61b20aafe6b2641922d5db24e447d5d6daffd9e17555/tokenizers-0.23.3-cp310-abi3-win_amd64.whl", hash = "sha256:1f0823bb00c5fdc98e487354d54dd55a03848d61a1a0bf29a68c77f24f3b26c3", size = 2872101, upload-time = "2026-10-09T10:16:37.533Z" }, + { url = "https://files.pythonhosted.org/packages/53/77/a476b6f73a661c11d113a342d2326b91506cf2285f0995d1212a6bb2022d/tokenizers-0.23.3-cp310-abi3-win_arm64.whl", hash = "sha256:7e48734d2de9260d86f03ab056d2cfeeff3869f61dbd49aaa15a2793b5f3458b", size = 2742580, upload-time = "2026-10-09T10:16:39.244Z" }, + { url = "https://files.pythonhosted.org/packages/65/46/f66baaedd42414a3f583c47379dc350e3e1f858a690d2574fd85ae70681b/tokenizers-0.23.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:efa3d7318406b4d115dce61ad5061953f1f44b128e79c020ce4615d763e23b6e", size = 3154274, upload-time = "2026-10-09T10:16:40.876Z" }, + { url = "https://files.pythonhosted.org/packages/c6/41/8de8c63b2d935eee5a0f42011fb7b786ffafeab0b8eb6d17acb8af2293b7/tokenizers-0.23.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:a4fbb3662f9f59d199d61338e54b4bcc11d07ebbb1aeb3540dacb2be9c521cb7", size = 3077805, upload-time = "2026-10-09T10:16:42.856Z" }, + { url = "https://files.pythonhosted.org/packages/e3/08/b1cbae8dc8fc7c91f992ac2d87a086e9b3f25a28814047ca16a82fe8c87b/tokenizers-0.23.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:de536665495cb4b409d25bade41963f801aff4225c19a6b804b048f7d14e34c7", size = 3491678, upload-time = "2026-10-09T10:16:45.093Z" }, + { url = "https://files.pythonhosted.org/packages/3e/0d/aac0cb2f3a1fdbef514145b4c5f2df4d05deeb1ee8f73ae641a1b4a62a85/tokenizers-0.23.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5cc24bb457dd4a8af89c8fcb40074d570129ec473df2a866c276ee55db4749d7", size = 3367420, upload-time = "2026-10-09T10:16:47.112Z" }, + { url = "https://files.pythonhosted.org/packages/1e/1d/41a697d0c193a320b243fbd68b2057b6eb2f01ecf80899e1a16e646ff699/tokenizers-0.23.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:acd5c57b4bd3e56e246e2731a3a3a6825a7a7d89b7e3b761ba80bc521710f04b", size = 9945973, upload-time = "2026-10-09T10:16:49.326Z" }, + { url = "https://files.pythonhosted.org/packages/37/e9/b56e619fcd583000a2b1254bb46af8dc6a174d3ba3329f454ad5a95a2be2/tokenizers-0.23.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:82eb480f6f1c21cea3349dec32cf1a6384c6c1e775f00f83b0d51197bc013687", size = 10237491, upload-time = "2026-10-09T10:16:51.943Z" }, + { url = "https://files.pythonhosted.org/packages/6f/68/f58b3beb95f3b62816e91e5e768e684cd63e58f9cbece22036dae3b1c971/tokenizers-0.23.3-cp314-cp314t-win_amd64.whl", hash = "sha256:1554a6eed34d9d6a78d23360f4e06df8dffab1ae08c7e8488e0b3e3b36cc266f", size = 2847654, upload-time = "2026-10-09T10:16:54.166Z" }, +] + [[package]] name = "torch" version = "2.12.1" @@ -1188,13 +1213,13 @@ resolution-markers = [ "python_full_version < '3.15' and sys_platform == 'darwin'", ] dependencies = [ - { name = "filelock", marker = "python_full_version < '3.15' and sys_platform == 'darwin'" }, - { name = "fsspec", marker = "python_full_version < '3.15' and sys_platform == 'darwin'" }, - { name = "jinja2", marker = "python_full_version < '3.15' and sys_platform == 'darwin'" }, - { name = "networkx", marker = "python_full_version < '3.15' and sys_platform == 'darwin'" }, - { name = "setuptools", marker = "python_full_version < '3.15' and sys_platform == 'darwin'" }, - { name = "sympy", marker = "python_full_version < '3.15' and sys_platform == 'darwin'" }, - { name = "typing-extensions", marker = "python_full_version < '3.15' and sys_platform == 'darwin'" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "typing-extensions" }, ] wheels = [ { url = "https://download-r2.pytorch.org/whl/cpu/torch-2.12.1-cp312-cp312-macosx_14_0_arm64.whl", hash = "sha256:d2dd0f2c5f7ccbddaf34cade0deaf476808368f902b9cdb7f36a2ab42301bc0e", upload-time = "2026-06-17T15:44:03Z" }, @@ -1212,13 +1237,13 @@ resolution-markers = [ "python_full_version < '3.15' and sys_platform != 'darwin'", ] dependencies = [ - { name = "filelock", marker = "python_full_version >= '3.15' or sys_platform != 'darwin'" }, - { name = "fsspec", marker = "python_full_version >= '3.15' or sys_platform != 'darwin'" }, - { name = "jinja2", marker = "python_full_version >= '3.15' or sys_platform != 'darwin'" }, - { name = "networkx", marker = "python_full_version >= '3.15' or sys_platform != 'darwin'" }, - { name = "setuptools", marker = "python_full_version >= '3.15' or sys_platform != 'darwin'" }, - { name = "sympy", marker = "python_full_version >= '3.15' or sys_platform != 'darwin'" }, - { name = "typing-extensions", marker = "python_full_version >= '3.15' or sys_platform != 'darwin'" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "typing-extensions" }, ] wheels = [ { url = "https://download-r2.pytorch.org/whl/cpu/torch-2.12.1%2Bcpu-cp312-cp312-linux_s390x.whl", hash = "sha256:900b253fc8c739bebffb63d7f75abff4cd53d79947265a00c16cb53b68ecdb91", upload-time = "2026-06-18T01:57:23Z" }, From 39a5dd2905741ce81feca2040111b12a3d2f3457 Mon Sep 17 00:00:00 2001 From: Roni bhakta <77425964+ronibhakta1@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:23:54 +0530 Subject: [PATCH 2/3] fix: harden the server, tune audio defaults, and polish the demo Server - CORS for the Readium Speech demos (CORS_ORIGINS, default https://readium.org); nginx now allows OPTIONS for the preflight and answers rate limits with 429. - Deploy gates on /readyz (healthcheck + docker compose up --wait), so a failed model load fails the job instead of going green. - ElevenLabs: warn in production when the daily cap is 0; keep the usage counter on the weights volume so a redeploy does not reset it. - A busy server returns 429 with Retry-After after SYNTHESIS_QUEUE_TIMEOUT_SECONDS instead of queueing without limit. - API_KEY_ENABLED=true is refused at startup (nothing enforces the key). - Circuit breaker admits one half-open trial at a time. - Wizard: no crash without pydantic, drops cross-language pairs for languages that are no longer selected; the server warns about ignored pairs. - Pocket integration fixture initialises the semaphore. Audio - Default bitrate when the request gives none: Opus 32 kbps (voip), MP3 64 kbps, chosen on measured PESQ against the 24 kHz source. A client bitrate still wins. - nginx serves HTTP/2. Demo - Replay reuses the loaded audio instead of calling /synthesize again. - Word highlighting works: decorate() needs the quote under text, the demo passed it at the top level so nothing was painted. - Opus is the default format and the engine is rebuilt so the request matches. - Smaller type and spacing, shadcn-style components in plain CSS, grouped voice picker, elapsed time on the Speak button, character counter, empty-state hint, GitHub button and clickable endpoint links. Closes #36, #37, #38, #39, #40, #41, #42, #43, #44, #45, #46, #47, #48 --- .github/workflows/deploy.yml | 2 +- Dockerfile | 7 +- Makefile | 17 +- README.md | 2 +- app/api/errors.py | 17 +- app/api/routes/synthesize.py | 9 +- app/config/settings.py | 20 +- app/core/circuit_breaker.py | 18 +- app/core/concurrency.py | 16 +- app/core/daily_limit.py | 13 - app/core/registry.py | 3 - app/drivers/ffmpeg.py | 18 +- app/main.py | 20 ++ app/providers/pocket_tts.py | 11 + app/static/demo.html | 337 +++++++++++------- docker-compose.dev.yml | 4 + docker-compose.yml | 2 + docs/API.md | 10 +- docs/configuration.md | 16 +- docs/deployment.md | 20 +- docs/development.md | 6 +- docs/providers/elevenlabs.md | 2 +- docs/voices.md | 8 +- nginx/templates/00-hardening.conf.template | 5 +- .../templates/20-speech-server.conf.template | 12 +- scripts/configure.sh | 50 ++- tests/integration/test_pocket_tts.py | 2 + tests/test_circuit_breaker.py | 12 + tests/test_cors.py | 77 ++++ tests/test_ffmpeg_bitrate.py | 14 + 30 files changed, 527 insertions(+), 223 deletions(-) create mode 100644 tests/test_cors.py create mode 100644 tests/test_ffmpeg_bitrate.py diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index c6ba2a3..2d0576a 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -72,6 +72,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 dd05a9e..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 | diff --git a/app/api/errors.py b/app/api/errors.py index c20400a..44a6762 100644 --- a/app/api/errors.py +++ b/app/api/errors.py @@ -33,10 +33,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 +54,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 +102,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,6 +116,7 @@ def _problem_response( status_code=status, content=body.model_dump(exclude_none=True), media_type=PROBLEM_MEDIA_TYPE, + headers=headers, ) @@ -128,7 +127,9 @@ 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: 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..ed0f969 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,13 +20,18 @@ 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: 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/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 ff70435..8ac5aee 100644 --- a/app/providers/pocket_tts.py +++ b/app/providers/pocket_tts.py @@ -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 17c4cf1..c16d820 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.

@@ -422,13 +438,17 @@

Readium Speech Server Demo

const usable = voices.filter(v => voiceLangs(v).has(lang)); voiceEl.innerHTML = ''; const byRegion = new Map(); - for (const v of usable) { if (!byRegion.has(v.language)) byRegion.set(v.language, []); byRegion.get(v.language).push(v); } - for (const [tag, list] of byRegion) { - const group = document.createElement('optgroup'); group.label = nameOfLang(tag); + for (const v of usable) { const k = prefix(v.language); if (!byRegion.has(k)) byRegion.set(k, []); byRegion.get(k).push(v); } + // Voices that speak this language natively first; the rest are cross-language. + const groups = [...byRegion].sort(([a], [b]) => (prefix(b) === lang) - (prefix(a) === lang)); + for (const [tag, list] of groups) { + const group = document.createElement('optgroup'); + group.label = prefix(tag) === lang ? `${nameOfLang(tag)} · native` : `${nameOfLang(tag)} voices · cross-language`; for (const v of list) { const opt = document.createElement('option'); const provider = v.provider ? (PROVIDER_NAMES[v.provider] || v.provider) : null; - opt.value = v.identifier; opt.textContent = provider ? `${v.name} — ${v.gender || 'voice'} · ${provider}` : `${v.name} — ${v.gender || 'voice'}`; + opt.value = v.identifier; + opt.textContent = [v.name + (v.gender ? ` — ${v.gender}` : ''), provider].filter(Boolean).join(' · '); group.appendChild(opt); } voiceEl.appendChild(group); @@ -437,8 +457,15 @@

Readium Speech Server Demo

voiceEl.value = (best && best.identifier) || ''; updateControlsForVoice(); updateCurl(); } +const countEl = el('count'); let maxChars = 0; +function updateCount() { + const n = textEl.value.length; + countEl.textContent = maxChars ? `${n} / ${maxChars}` : `${n}`; + countEl.className = 'count' + (maxChars && n > maxChars ? ' over' : maxChars && n > maxChars * 0.9 ? ' warn' : ''); +} function onLanguageChange() { const s = SAMPLES[languageEl.value]; if (s) textEl.value = s; + updateCount(); renderVoices(); } @@ -452,6 +479,7 @@

Readium Speech Server Demo

]); } catch (e) { showError('Could not reach the server. Is it running?'); return; } serviceCaps = svc; + maxChars = svc.limits?.maxTextLength || 0; updateCount(); formatEl.innerHTML = ''; for (const f of svc.output.formats) { @@ -459,10 +487,12 @@

Readium Speech Server Demo

opt.textContent = FORMAT_NOTE[f] ? `${f} · ${FORMAT_NOTE[f]}` : f; formatEl.appendChild(opt); } - formatEl.value = svc.output.default; + // Opus is ~5x smaller than the server's wav default for speech; keep wav only if it's all there is. + formatEl.value = svc.output.formats.includes('opus') ? 'opus' : svc.output.default; updateBitrateEnabled(); voices = voiceList; + await rebuildEngine(); // the engine was built before the format select was filled; apply its default if (!voices.length) { showError('No voices installed. Configure a provider and restart.'); } const langs = new Set(); for (const v of voices) for (const l of voiceLangs(v)) langs.add(l); @@ -645,6 +675,13 @@

Readium Speech Server Demo

} /* synth flow */ +let synthTimer = null; +function startSynthTimer() { + const t0 = performance.now(); + clearInterval(synthTimer); + synthTimer = setInterval(() => { speakLabel.textContent = `Synthesizing ${((performance.now() - t0) / 1000).toFixed(1)}s`; }, 100); +} +function stopSynthTimer() { clearInterval(synthTimer); synthTimer = null; speakLabel.textContent = 'Speak'; } function showError(msg){ bannerEl.className = 'banner err'; bannerEl.textContent = msg; } function clearError(){ bannerEl.className = 'banner'; bannerEl.textContent = ''; } function setResponse(text, ok){ outputEl.innerHTML = ''; const s=document.createElement('span'); s.className='status'+(ok?'':' bad'); s.textContent=text; outputEl.appendChild(s); } @@ -659,9 +696,13 @@

Readium Speech Server Demo

decorations.decorate([{ id: 'tts-word', style: { type: DecorationStyleType.Highlight, tint: '#FFE066', enforceContrast: false }, - highlight: word, - before: readingText.slice(0, charIndex), - after: readingText.slice(charIndex + charLength), + // The locator's quote goes under `text`; top-level highlight/before/after are ignored, which + // left every decoration blank (nothing painted, and later words counted as "unchanged"). + text: { + highlight: word, + before: readingText.slice(0, charIndex), + after: readingText.slice(charIndex + charLength), + }, }], 'tts'); } function clearReadingHighlight() { @@ -677,8 +718,8 @@

Readium Speech Server Demo

function onNavError(event) { const d = event.detail; const msg = (d && d.message) ? d.message : (typeof d === 'string' ? d : JSON.stringify(d)); - showError(msg); - speakBtn.disabled = false; speakLabel.textContent = 'Speak'; + showError(/\b429\b|busy|rate.?limit/i.test(msg) ? 'The server is busy. Try again in a few seconds.' : msg); + speakBtn.disabled = false; stopSynthTimer(); } // Click the highlighted text to go back to editing it (reading div sits over #text via CSS :has()). function backToEditing() { speechNavigator.stop(); textEl.focus(); } @@ -710,7 +751,7 @@

Readium Speech Server Demo

if (!textEl.value.trim()) { showError('Write some text first.'); textEl.focus(); return; } if (!voiceEl.value) { showError('No voice selected.'); return; } clearError(); - speakBtn.disabled = true; speakLabel.textContent = 'Synthesizing…'; + speakBtn.disabled = true; speakLabel.textContent = 'Synthesizing…'; startSynthTimer(); // voice / rate / pitch are Preferences since 0.15.0 (setVoice/setRate/setPitch were removed). const prefs = { @@ -734,7 +775,7 @@

Readium Speech Server Demo

let currentBlob = null, currentFormat = null; onSynthUpdate = (detail) => { const { requestBody, status, ok, blob, serverMs, boundaries, error } = detail; - speakBtn.disabled = false; speakLabel.textContent = 'Speak'; + speakBtn.disabled = false; stopSynthTimer(); if (!ok) { setResponse(`${status}\n`, false); @@ -769,7 +810,28 @@

Readium Speech Server Demo

} /* transport wiring */ -playBtn.addEventListener('click', () => { if (speechNavigator.getState() === 'playing') speechNavigator.pause(); else speechNavigator.play(); }); +/* Replay after the clip ended: the engine keeps the decoded chunks in scheduledChunks, but + navigator.play() from idle calls engine.speak(), which synthesizes again (new /synthesize + request). Reschedule the kept buffers instead. Same private-field coupling as seekTo(). */ +function replayLoaded() { + // Only a single-utterance load keeps the whole clip: a multi-utterance queue overwrites the chunks. + if (!chunkRanges().length || !engine['audioContext'] || engine.getUtteranceCount() !== 1) return false; + seekTo(0); + speechNavigator['setNavigatorState']('playing'); + engine['setState']('playing'); + engine['isSpeakingInternal'] = true; + engine['startBoundaryPolling'](engine['speakGeneration']); + engine['audioContext'].resume?.(); + onStart(); // 'end' hid the reading overlay; replay emits no 'start' event, so re-show it + onTransportStart(); + return true; +} +playBtn.addEventListener('click', () => { + const state = speechNavigator.getState(); + if (state === 'playing') speechNavigator.pause(); + else if (state === 'idle' && replayLoaded()) return; + else speechNavigator.play(); +}); function seek(clientX) { if (!peaks) return; const r = waveEl.getBoundingClientRect(); @@ -798,6 +860,7 @@

Readium Speech Server Demo

for (const e of [textEl, speedEl, pitchEl, ssmlEl, boundaryEl, bitrateEl]) { e.addEventListener('input', updateCurl); e.addEventListener('change', updateCurl); } +textEl.addEventListener('input', updateCount); textEl.addEventListener('keydown', e => { if ((e.metaKey||e.ctrlKey) && e.key === 'Enter') speak(); }); el('copyCurl').addEventListener('click', async () => { try { await window.navigator.clipboard.writeText(curlEl.textContent); const b=el('copyCurl'); b.textContent='Copied'; setTimeout(()=>b.textContent='Copy',1200); } catch {} diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml index 8c357a6..38a40ef 100644 --- a/docker-compose.dev.yml +++ b/docker-compose.dev.yml @@ -9,5 +9,9 @@ services: volumes: - ./app:/app/app - ./tests:/app/tests + - ./scripts:/app/scripts + # `uv sync --frozen --dev` (make *-docker targets) reads these; the image only has pyproject. + - ./pyproject.toml:/app/pyproject.toml + - ./uv.lock:/app/uv.lock environment: - RELOAD=true diff --git a/docker-compose.yml b/docker-compose.yml index f3b693e..6d5ac4d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,6 +12,8 @@ services: required: false environment: - HF_TOKEN=${HF_TOKEN:-} + # On the weights volume so the daily-spend counter survives redeploys (default is /tmp). + - ELEVENLABS_USAGE_FILE=${ELEVENLABS_USAGE_FILE:-/weights/elevenlabs_usage.json} volumes: - weights_cache:/weights networks: diff --git a/docs/API.md b/docs/API.md index 0a411a2..5bc56ef 100644 --- a/docs/API.md +++ b/docs/API.md @@ -20,7 +20,9 @@ Base path: `/`. All bodies are `application/json` unless noted. ## Authentication -None enforced today. `API_KEY_ENABLED` / `API_KEY` exist in [configuration](configuration.md) but no middleware checks them yet — every route is open regardless of the setting. Don't rely on it. +None. Every route is open. `API_KEY_ENABLED=true` is rejected at startup (it would not protect anything), so the setting can't give a false sense of security. + +**CORS:** browsers on `CORS_ORIGINS` (default `https://readium.org`, the Readium Speech demos) may call the API cross-origin; `X-Request-Id`, `X-Total-Count`, `X-Offset`, `X-Limit` and `Retry-After` are readable from JavaScript. Set `CORS_ORIGINS=` (empty) to disable. In production, nginx sits in front (see [configuration](configuration.md#production-vs-development)) and rate-limits `/synthesize` (2 req/s, burst 4) plus per-IP connection caps — unrelated to app auth, but the only request throttling that exists. @@ -54,7 +56,7 @@ Pydantic schema errors (`422`) additionally carry an `errors` array (raw Pydanti | 502 | `provider_error` | Provider or ffmpeg failed (bad voice state, generation error, encode failure) | | 503 | `service_not_ready` | Three causes: (1) **startup** — the server accepts connections immediately and loads models in the background, so `/synthesize` and `/voices` return 503 until warmup finishes (`/healthz` and `/service` stay up throughout; `/readyz` flips to 200 when ready); (2) `/readyz` — also 503 if ffmpeg is missing or a provider is unhealthy; (3) `/synthesize` — also 503 when a provider's circuit breaker is open, see [configuration](configuration.md) for `CIRCUIT_BREAKER_*` | -`unsupported_format` (415), `rate_limited` (429), and `provider_timeout` (504) are declared in `app/api/errors.py` for future providers but no current code path raises them — a `429`/`503` seen in production is nginx's own rate/connection limit, a plain nginx error page, not this JSON shape. +`provider_timeout` (504) is declared in `app/api/errors.py` for the ElevenLabs provider. `rate_limited` (429) is raised when the server is busy (no synthesis slot within `SYNTHESIS_QUEUE_TIMEOUT_SECONDS`; the response carries `Retry-After: 5`) and by the ElevenLabs daily cap. A `429` that is a plain nginx error page, not this JSON shape, is nginx's own rate/connection limit on `/synthesize`. A `503` is a real outage (models loading, or a provider's circuit breaker is open). --- @@ -214,7 +216,7 @@ Only `text` is required; everything else defaults as shown (`voice` falls back t | `publication_id` | string \| null | `null` | Accepted, currently unused (reserved for future cache scoping) | | `boundary` | bool | `false` | `true` → JSON response with base64 audio + timing marks instead of raw binary | | `output.format` | `"wav" \| "mp3" \| "opus"` | `"wav"` | `wav` bypasses ffmpeg and is highest quality (fastest, no lossy encoding); `mp3`/`opus` are ffmpeg-encoded on request — see [`GET /service`](#get-service) for what's available | -| `output.bitrate` | int \| null | `null` | kbps for `mp3`/`opus`; ffmpeg default (~128 mp3, ~64 opus) if unset; ignored for `wav` | +| `output.bitrate` | int \| null | `null` | kbps for `mp3`/`opus`; server default if unset (32 kbps opus, 64 kbps mp3); ignored for `wav` | | `output.sample_rate` | int \| null | `null` | **Accepted but not applied** — output is always the model's native rate (24000 Hz for PocketTTS). No resampling happens today | | `output.speed` | float | `1.0` | **Accepted but ignored** by PocketTTS (logged at debug level) | | `output.pitch` | float \| null | `null` | **Accepted but ignored** by PocketTTS | @@ -263,7 +265,7 @@ No `end` field (next mark's `elapsedTime`, or total duration for the last word, Things the schema or config surfaces but the server doesn't actually do yet: -- **Auth** — `API_KEY_ENABLED` is validated at startup but never enforced on requests. +- **Auth** — there is none; `API_KEY_ENABLED=true` is rejected at startup. - **Word boundaries on PocketTTS** — the underlying model exposes no timing/alignment data, so PocketTTS's `providers[].controls.boundary` (on `GET /service`) stays `false`. ElevenLabs populates real per-word marks. - **`output.speed` / `output.pitch` / `output.sample_rate`** — accepted, validated, silently ignored by PocketTTS. - **`id` / `publication_id`** — parsed, not used for caching, idempotency, or dedup. diff --git a/docs/configuration.md b/docs/configuration.md index ddf2817..d660e16 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -74,14 +74,18 @@ only ever *adds* cross-language support: |---|---|---| | `HF_TOKEN` | _(empty)_ | HuggingFace token. Optional — prevents rate-limiting on first-run model downloads. Shared across any provider that pulls models from HF | | `WORKERS` | `1` | Uvicorn worker processes. Each loads a full copy of every active language model | -| `MAX_CONCURRENT_SYNTHESES` | `1` | Max parallel CPU inference jobs per worker. Each job uses ~2 cores; `configure.sh` derives this from `nproc`/RAM so cores ≈ workers × concurrency × 2 (no oversubscription) | +| `MAX_CONCURRENT_SYNTHESES` | `1` | Max parallel CPU inference jobs per worker. Each language model is single-threaded behind a lock, so this only parallelises **different** languages — for several readers in the same language, raise `WORKERS` instead. Each job uses ~2 cores; `configure.sh` derives this from `nproc`/RAM so cores ≈ workers × concurrency × 2 (no oversubscription) | | `CIRCUIT_BREAKER_ENABLED` | `true` | Trip a provider's circuit breaker after repeated `synthesize()` failures, returning `503` immediately instead of hammering a broken provider | | `CIRCUIT_BREAKER_FAILURE_THRESHOLD` | `5` | Consecutive failures before a provider's breaker opens | -| `CIRCUIT_BREAKER_RECOVERY_SECONDS` | `30` | How long an open breaker waits before allowing one trial call | -| `API_KEY_ENABLED` | `false` | Reserved — validated at startup but **not yet enforced** on any route | -| `API_KEY` | _(empty)_ | Reserved, same caveat | +| `CIRCUIT_BREAKER_RECOVERY_SECONDS` | `30` | How long an open breaker waits before allowing one trial call (one at a time) | +| `API_KEY_ENABLED` | `false` | Not implemented. `true` is rejected at startup (no route checks a key, so it would leave the API open) | +| `API_KEY` | _(empty)_ | Reserved | +| `CORS_ORIGINS` | `https://readium.org` | Comma-separated browser origins (scheme + host, no path) allowed to call the API cross-origin. Default is the Readium Speech demos (`https://readium.org/speech/demo/`). Empty disables CORS. nginx also lets `OPTIONS` through for the preflight | +| `SYNTHESIS_QUEUE_TIMEOUT_SECONDS` | `30` | How long a request waits for a free synthesis slot before `429` "busy" | | `LOG_LEVEL` | `INFO` | `DEBUG` · `INFO` · `WARNING` · `ERROR` | | `PORT` | `8000` | Listen port | +| `HOST` | `0.0.0.0` | Address uvicorn binds to. Leave as is in Docker; only change it to bind to one interface outside Docker | +| `APP_ENV` | `development` | `production` turns on `TrustedHostMiddleware` (needs `DOMAIN`), the OpenAPI `servers` entry and the ElevenLabs uncapped-spend warning. The wizard writes `production`; set `development` for local runs | | `MAX_TEXT_LENGTH` | `2000` | Maximum characters per synthesis request | | `FFMPEG_BIN` | `ffmpeg` | Path to ffmpeg binary (bundled in the Docker image) | | `ENABLED_PROVIDERS` | `pocket` | Comma-separated provider ids to register at startup: `pocket`, `elevenlabs` | @@ -107,7 +111,7 @@ Only loaded/required when `elevenlabs` is in `ENABLED_PROVIDERS`. Managed by the | `ELEVENLABS_MODEL_ID` | `eleven_multilingual_v2` | Model + cost multiplier. `flash_v2_5`/`turbo_v2_5` are 0.5 credits/char (cheapest); `multilingual_v2`/`v3` are 1.0. [Compare](https://elevenlabs.io/docs/models) · [pricing](https://elevenlabs.io/pricing) | | `ELEVENLABS_LANGUAGES` | _(empty)_ | ElevenLabs' **own** languages (comma BCP-47, e.g. `en,fr,ja`), separate from pocket's `LANGUAGES` — languages are provider-scoped. Empty = no ElevenLabs voices. Supported: the 29 languages common to all ElevenLabs models (`ar bg cs da de el en es fi fil fr hi hr id it ja ko ms nl pl pt ro ru sk sv ta tr uk zh`) | | `ELEVENLABS_DAILY_CHAR_LIMIT` | `0` | Max characters sent to ElevenLabs **per day** so users can't spam it. `0` = unlimited. Resets at 00:00 UTC; over the cap `/synthesize` returns `429 rate_limited`. Pick per your model's rate ([pricing](https://elevenlabs.io/pricing/api) — flash/turbo bill half, so the same cost buys ~2× the characters). Host-wide (shared across workers via a JSON file). Set via wizard: Manage provider → elevenlabs → Set daily limit | -| `ELEVENLABS_USAGE_FILE` | `/tmp/elevenlabs_usage.json` | Where the daily counter is stored. Point at a volume path to persist the count across container restarts | +| `ELEVENLABS_USAGE_FILE` | `/tmp/elevenlabs_usage.json` (code default) | Where the daily counter is stored. `docker-compose.yml` sets it to `/weights/elevenlabs_usage.json` on the weights volume, so the count survives redeploys; outside Docker, point it at a persistent path | | `ELEVENLABS_BASE_URL` | `https://api.elevenlabs.io` | API base URL — override for testing | `LANGUAGES` and `VOICE_LANGUAGES` operate at different levels and both matter: `LANGUAGES` @@ -208,4 +212,4 @@ First-time setup writes `APP_ENV=production` and prompts for `DOMAIN`. `make sta For local dev, set `APP_ENV=development` in `.env` (`DOMAIN` becomes optional) and use `make dev-docker` — exposes `:8000` directly with no nginx. -nginx rate-limits `/synthesize` (2 req/s, burst 4) and caps connections per IP. A `503` from behind nginx is a plain nginx error page, not the app's Problem Details JSON. +nginx rate-limits `/synthesize` (2 req/s, burst 4) and caps connections per IP. Over the limit it answers `429` with a plain nginx error page, not the app's Problem Details JSON. diff --git a/docs/deployment.md b/docs/deployment.md index 553cea5..bfd5d4f 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -63,13 +63,29 @@ once. Nginx serves TLS (see `nginx/` + `DOMAIN`). Adding a *new* var is the same flow — it's just part of the file. `entrypoint.sh` validates required vars at container start and fails fast if one is missing, so a -bad/incomplete secret is caught immediately (the old container keeps running). +bad/incomplete secret is caught immediately: the new container exits and the deploy job +fails. (`docker compose up` has already replaced the old container by then, so the site is +down until the secret is fixed and redeployed.) ## Notes - **Model/voice config** (`LANGUAGES`, `VOICE_LANGUAGES`) lives in `pocket-tts.env`. Changing it and redeploying triggers new downloads on next start (cached after); - reclaim disk for removed ones with `make prune-models-apply`. + reclaim disk for removed ones with `make prune-models` (dry run), then + `make prune-models-apply`, run on the VM. The same applies after a release that changes + models (e.g. the move to the Kyutai 4.x models): the new weights download on first start and + the old ones stay in the volume until pruned. The prune removes model folders that are no + longer used; an older-revision copy of a folder that is still in use stays (wasted disk only). +- **Deploys wait for readiness:** the container healthcheck calls `/readyz` (models loaded), + and the deploy runs `docker compose up -d --wait --wait-timeout 720`. If models fail to + load (e.g. a Hugging Face download error) the deploy job fails instead of going green. + The first start after a model change downloads weights, so `/readyz` is 503 for a few minutes. +- **CORS:** `CORS_ORIGINS` (in `.env`, so in the `DOTENV_B64` secret) lists the browser origins + allowed to call the API. It defaults to `https://readium.org` (the Readium Speech demos). + nginx lets `OPTIONS` through for the CORS preflight. +- **ElevenLabs spend cap:** set `ELEVENLABS_DAILY_CHAR_LIMIT` in `elevenlabs.env`. `0` means + unlimited, and a production server logs a warning at startup if ElevenLabs is on with `0`. + The counter is kept on the weights volume, so redeploys don't reset it. - **Secrets vs non-secrets:** bundling both files as base64 secrets is the pragmatic choice for a single VM. To review config in PRs instead, graduate to a SOPS/age-encrypted env committed to the repo and decrypted at deploy. diff --git a/docs/development.md b/docs/development.md index eee2797..8c78d20 100644 --- a/docs/development.md +++ b/docs/development.md @@ -11,7 +11,7 @@ | `make start` | Start production stack (detached) | | `make stop` | Stop containers | | `make logs` | Tail app logs | -| `make test-docker` | Fast test suite — no models needed | +| `make test-docker` | Fast test suite — no models needed (the `*-docker` targets bypass the entrypoint and `uv sync` the dev tools into the container first; the dev stack mounts `app/`, `tests/`, `scripts/`, `pyproject.toml` and `uv.lock`) | | `make test-integration-docker` | Integration tests — requires models in volume | | `make ci-docker` | Lint + format check + typecheck + tests | | `make lint-docker` | `ruff check` | @@ -51,14 +51,14 @@ Client └─ Synthesizer ├─ validate text length + content ├─ resolve voice identifier → (provider, Voice) (VoiceCatalog) - ├─ circuit breaker check ← per-provider, 503 fast if open + ├─ circuit breaker check ← per-provider, 503 fast if open (one trial call when half-open) ├─ provider.synthesize() ← runs in thread pool, bounded by semaphore │ └─ TTSModel.generate_audio() — CPU inference └─ encode PCM → mp3/opus (ffmpeg driver) or wrap → wav (default) ``` - Routes are `async`; all CPU-bound inference runs off the event loop via `anyio.to_thread.run_sync` -- A semaphore (`MAX_CONCURRENT_SYNTHESES`) prevents model thrashing under concurrent load +- A semaphore (`MAX_CONCURRENT_SYNTHESES`) prevents model thrashing under concurrent load; a request that can't get a slot within `SYNTHESIS_QUEUE_TIMEOUT_SECONDS` gets `429` with `Retry-After` - A per-provider circuit breaker (`CIRCUIT_BREAKER_*`) fails fast instead of repeatedly hitting a broken provider - Model throughput scales by adding worker processes (`WORKERS`), not threads - Model weights live in a named Docker volume — downloaded once, instant on every subsequent start diff --git a/docs/providers/elevenlabs.md b/docs/providers/elevenlabs.md index f9152dd..5a27934 100644 --- a/docs/providers/elevenlabs.md +++ b/docs/providers/elevenlabs.md @@ -96,7 +96,7 @@ format (via the `/with-timestamps` endpoint). [pricing](https://elevenlabs.io/pricing/api) (Flash/Turbo $0.05 vs Multilingual/v3 $0.10 per 1K chars, so flash/turbo bill half → allow ~2× the characters for the same cost). Over the cap, `/synthesize` returns `429 rate_limited` until 00:00 UTC. The counter is a small JSON file - (`ELEVENLABS_USAGE_FILE`, default `/tmp/…`) shared across workers — point it at a volume to persist + (`ELEVENLABS_USAGE_FILE`; code default `/tmp/…`, `docker-compose.yml` puts it on the weights volume) shared across workers — outside Docker, point it at a persistent path across restarts. Set it in the wizard (**Manage provider → elevenlabs → Set daily limit**). - `controls` (service-wide, see `GET /service` — not repeated per voice): `speed` (maps to `voice_settings.speed`) and `boundary` supported; `pitch` and `ssml` are not (SSML tags are diff --git a/docs/voices.md b/docs/voices.md index a02c3e0..36bcd5f 100644 --- a/docs/voices.md +++ b/docs/voices.md @@ -1,6 +1,6 @@ # Voices -26 voice identities, each declared **once** — not duplicated per language. A voice has one +27 voice identities, each declared **once** — not duplicated per language. A voice has one primary `language` and, optionally, `otherLanguages` it's also capable of speaking. The identifier has no language segment: it's always `urn:readium:tts:pocket:`, and which language to speak is chosen at request time via `SynthesizeRequest.language`. @@ -9,7 +9,7 @@ language to speak is chosen at request time via `SynthesizeRequest.language`. urn:readium:tts:pocket:alba # one identifier for Alba, in any installed language ``` -The 26 voice identities, sourced from [kyutai/tts-voices](https://huggingface.co/kyutai/tts-voices): +The 27 voice identities, sourced from [kyutai/tts-voices](https://huggingface.co/kyutai/tts-voices): | Voice | Gender | Origin | |---|---|---| @@ -20,9 +20,9 @@ The 26 voice identities, sourced from [kyutai/tts-voices](https://huggingface.co | cosette | female | Expresso dataset (CC BY-NC 4.0) | | jean | male | EARS dataset (CC BY-NC 4.0) | | estelle | female | Unmute production voices | -| giovanni, lola, juergen, rafael | mixed | Kyutai (language reference voices) | +| giovanni, lola, juergen, rafael, daan | mixed | Kyutai (language reference voices; `daan` is the Dutch one) | -Supported language codes: `en`, `fr`, `it`, `de`, `es`, `pt` — derived directly from PocketTTS model names. +Supported language codes: `en`, `fr`, `it`, `de`, `es`, `pt`, `nl` — derived directly from PocketTTS model names. ## Cross-language voices diff --git a/nginx/templates/00-hardening.conf.template b/nginx/templates/00-hardening.conf.template index 68a5852..53c9b12 100644 --- a/nginx/templates/00-hardening.conf.template +++ b/nginx/templates/00-hardening.conf.template @@ -7,9 +7,8 @@ client_body_timeout 10s; keepalive_timeout 15s; large_client_header_buffers 2 1k; -# Sized around app/config/settings.py's max_concurrent_syntheses default (2): -# protects a tiny backend semaphore from an unauthenticated burst -# (API_KEY_ENABLED defaults false). +# Sized around app/config/settings.py's max_concurrent_syntheses default (1): +# protects a tiny backend semaphore from an unauthenticated burst (the API has no auth). limit_req_zone $binary_remote_addr zone=synth:10m rate=2r/s; limit_conn_zone $binary_remote_addr zone=perip:10m; diff --git a/nginx/templates/20-speech-server.conf.template b/nginx/templates/20-speech-server.conf.template index d8aa73f..d936405 100644 --- a/nginx/templates/20-speech-server.conf.template +++ b/nginx/templates/20-speech-server.conf.template @@ -27,6 +27,7 @@ server { server { listen 443 ssl; + http2 on; # the browser reads ahead with several parallel /synthesize requests server_name ${DOMAIN}; ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem; @@ -64,23 +65,26 @@ server { # requests on a hard refresh) could trip nginx's built-in 503 rate-limit # rejection well before actually threatening the synthesis backend. location = /synthesize { - limit_except POST { + # OPTIONS: CORS preflight for the browser demo (JSON POST). + limit_except POST OPTIONS { deny all; } limit_req zone=synth burst=4 nodelay; limit_conn perip 10; + # 429 (not nginx's default 503) so clients treat a rate limit as "slow down", not an outage. + limit_req_status 429; + limit_conn_status 429; include /etc/nginx/snippets/proxy-pass.conf; - # TTS inference is CPU-bound and can be slow (24-layer models, long text, - # emulated arch) — give synthesis more than the 120s default on other + # TTS inference is CPU-bound and can be slow (long text, emulated arch) — give synthesis more than the 120s default on other # routes so a legitimately long generation isn't cut off with a 504. proxy_read_timeout 300s; } location / { - limit_except GET POST HEAD { + limit_except GET POST HEAD OPTIONS { deny all; } diff --git a/scripts/configure.sh b/scripts/configure.sh index bc721eb..d0d01d8 100755 --- a/scripts/configure.sh +++ b/scripts/configure.sh @@ -77,7 +77,7 @@ _provider_enabled() { # $1=id → "yes"/"no" # Hardware-derived defaults. pocket-tts uses ~2 CPU cores per synthesis (its # generate→decode pipeline; docs: "Uses only 2 CPU cores") and each worker holds a -# full model copy (~2 GB for en+fr). So 1 worker ≈ 2 cores + ~2 GB RAM. Derive +# full model copy (measured ~0.5 GB en, ~0.9 GB fr; 2 GB/worker keeps a margin). So 1 worker ≈ 2 cores + ~2 GB RAM. Derive # non-thrashing WORKERS / MAX_CONCURRENT_SYNTHESES from the box instead of shipping a # static default that only fits one machine. Sets DETECTED_* and SUGGESTED_* globals. _detect_hw() { @@ -484,10 +484,14 @@ PORT=8000 WORKERS=1 DOMAIN= -# ── Auth (off by default) ── +# ── Auth (not implemented — API_KEY_ENABLED=true is rejected at startup) ── API_KEY_ENABLED=false API_KEY= +# ── CORS: browser origins allowed to call the API (comma-separated, scheme+host, no path). +# Default is the Readium Speech demos at https://readium.org/speech/demo/. Empty = disabled. ── +CORS_ORIGINS=https://readium.org + # ── Concurrency ── MAX_CONCURRENT_SYNTHESES=2 @@ -548,7 +552,18 @@ _show_plan() { local langs voice_lang langs=$(current_langs) voice_lang=$(get_penv VOICE_LANGUAGES) - python3 "$POCKET_PLAN" "$VOICES_JSON" "$langs" "$voice_lang" + # pocket_plan imports app.providers.voice_loading, which needs pydantic — a bare system + # python3 lacks it. Borrow a throwaway one via uv; without uv, skip the view, don't abort. + local py=(python3) + if ! python3 -c 'import pydantic' 2>/dev/null; then + if command -v uv >/dev/null 2>&1; then + py=(uv run --no-project --quiet --with pydantic python3) + else + warn "Install plan unavailable (needs pydantic or uv). Languages: ${langs:-none}" + return 0 + fi + fi + "${py[@]}" "$POCKET_PLAN" "$VOICES_JSON" "$langs" "$voice_lang" } do_show_pocket_config() { @@ -577,6 +592,13 @@ _menu_change_languages() { fi set_penv LANGUAGES "$new" ok "LANGUAGES updated → $new" + local pairs kept + pairs=$(get_penv VOICE_LANGUAGES) + kept=$(_voicelang_prune_to_langs "$pairs" "$new") + if [[ "$kept" != "$pairs" ]]; then + set_penv VOICE_LANGUAGES "$kept" + warn "Dropped cross-language pairs for languages no longer selected: ${pairs} → ${kept:-(none)}" + fi printf '\n%sNote:%s new languages download on next start; removed ones stay on disk\n' "$Y" "$R" printf '(reclaim: %smake prune-models-apply%s). Restart to apply: %smake stop && make start%s\n\n' \ "$C" "$R" "$C" "$R" @@ -694,6 +716,23 @@ _voicelang_delete() { echo "$out" } +# Drop explicit pairs (add or removal form) whose language isn't in `langs` — the server only +# installs a pair for a language that is in LANGUAGES, so such a pair would be silently ignored. +_voicelang_prune_to_langs() { + local list="$1" langs="$2" out="" p bare + [[ -z "$list" ]] && return + IFS=',' read -ra _p <<< "$list" + for p in "${_p[@]}"; do + [[ -z "$p" ]] && continue + bare="${p#-}" + if [[ "$p" != "*:*" ]]; then + case ",${langs}," in *",${bare#*:},"*) ;; *) continue ;; esac + fi + out="${out:+${out},}${p}" + done + echo "$out" +} + # Per-voice cross-language editor. All steps are single-select (ENTER picks the # highlighted row) — no SPACE-to-check trap, no silent dead-ends. _custom_voice_loop() { @@ -983,7 +1022,7 @@ do_show_config() { workers=$(get_env WORKERS); workers="${workers:-1}" hf_token=$(get_env HF_TOKEN) key_enabled=$(get_env API_KEY_ENABLED); key_enabled="${key_enabled:-false}" - max_syn=$(get_env MAX_CONCURRENT_SYNTHESES); max_syn="${max_syn:-2}" + max_syn=$(get_env MAX_CONCURRENT_SYNTHESES); max_syn="${max_syn:-1}" printf ' %-30s %s%s%s\n' "Workers:" "$C" "$workers" "$R" printf ' %-30s %s%s%s\n' "Max concurrent syntheses:" "$C" "$max_syn" "$R" @@ -996,6 +1035,9 @@ do_show_config() { fi printf ' %-30s %s%s%s\n' "API key auth:" "$C" "$key_enabled" "$R" + local cors="https://readium.org (default)" + grep -q '^CORS_ORIGINS=' "$ENV_FILE" 2>/dev/null && cors="$(get_env CORS_ORIGINS)" + printf ' %-30s %s%s%s\n' "CORS origins:" "$C" "${cors:-(disabled)}" "$R" printf ' %-30s %s%s%s\n' "Enabled providers:" "$C" "$(get_env ENABLED_PROVIDERS)" "$R" printf '\n %sSee "Manage provider" for provider-specific config.%s\n' "$Y" "$R" printf ' Config files: %s, %s' "$ENV_FILE" "$POCKET_ENV_FILE" diff --git a/tests/integration/test_pocket_tts.py b/tests/integration/test_pocket_tts.py index 2430b4a..9404272 100644 --- a/tests/integration/test_pocket_tts.py +++ b/tests/integration/test_pocket_tts.py @@ -6,6 +6,7 @@ import pytest +from app.core.concurrency import init_semaphore from app.providers.pocket_tts import PocketTTSProvider from app.schemas.audio import SynthesisParams from tests.helpers.audio import assert_valid_pcm, pcm_duration_seconds @@ -15,6 +16,7 @@ @pytest.fixture async def pocket() -> PocketTTSProvider: + init_semaphore(1) # synthesize() runs inference through the semaphore p = PocketTTSProvider() await p.load() return p diff --git a/tests/test_circuit_breaker.py b/tests/test_circuit_breaker.py index 6baceb2..4e23c24 100644 --- a/tests/test_circuit_breaker.py +++ b/tests/test_circuit_breaker.py @@ -75,3 +75,15 @@ def test_registry_gives_each_provider_an_independent_breaker() -> None: registry.get("a").record_failure() assert registry.get("a").allow() is False assert registry.get("b").allow() is True + + +def test_half_open_allows_one_trial_at_a_time(monkeypatch) -> None: # type: ignore[no-untyped-def] + now = [0.0] + monkeypatch.setattr(cb_mod.time, "monotonic", lambda: now[0]) + b = CircuitBreaker(failure_threshold=1, recovery_seconds=10) + b.record_failure() + now[0] = 10 + assert b.allow() is True # the trial + assert b.allow() is False # everyone else waits for its result + now[0] = 20 + assert b.allow() is True # a trial that never reported is retried after recovery_seconds diff --git a/tests/test_cors.py b/tests/test_cors.py new file mode 100644 index 0000000..2ef750e --- /dev/null +++ b/tests/test_cors.py @@ -0,0 +1,77 @@ +"""CORS for the Readium Speech demos, plus the busy-queue and API-key guards.""" + +import asyncio + +import pytest +from httpx import AsyncClient + +from app.api.errors import RateLimited +from app.config.settings import Settings, settings +from app.core import concurrency + +_DEMO = "https://readium.org" + + +async def test_preflight_allows_demo_origin(client: AsyncClient) -> None: + resp = await client.options( + "/synthesize", + headers={ + "Origin": _DEMO, + "Access-Control-Request-Method": "POST", + "Access-Control-Request-Headers": "content-type", + }, + ) + assert resp.status_code == 200 + assert resp.headers["access-control-allow-origin"] == _DEMO + + +async def test_preflight_rejects_other_origin(client: AsyncClient) -> None: + resp = await client.options( + "/synthesize", + headers={"Origin": "https://evil.example", "Access-Control-Request-Method": "POST"}, + ) + assert "access-control-allow-origin" not in resp.headers + + +async def test_voices_exposes_pagination_headers_to_demo(client: AsyncClient) -> None: + resp = await client.get("/voices", headers={"Origin": _DEMO}) + assert resp.headers["access-control-allow-origin"] == _DEMO + assert "x-total-count" in resp.headers["access-control-expose-headers"].lower() + + +def test_cors_origin_list_strips_slash_and_blanks() -> None: + s = Settings(_env_file=None, cors_origins=" https://a.org/ ,, https://b.org") # type: ignore[arg-type] + assert s.cors_origin_list == ["https://a.org", "https://b.org"] + + +def test_api_key_enabled_is_rejected() -> None: + with pytest.raises(ValueError, match="API_KEY_ENABLED is not supported"): + Settings(_env_file=None, api_key_enabled=True, api_key="k") # type: ignore[arg-type] + + +async def test_run_inference_busy_returns_429(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, "synthesis_queue_timeout_seconds", 0.05) + concurrency.init_semaphore(1) + sem = concurrency._semaphore # noqa: SLF001 + assert sem is not None + await sem.acquire() # the only slot is taken + with pytest.raises(RateLimited): + await concurrency.run_inference(lambda: None) + sem.release() + assert await asyncio.wait_for(concurrency.run_inference(lambda: 7), 2) == 7 + + +async def test_busy_synthesize_returns_429_with_retry_after( + client: AsyncClient, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(settings, "synthesis_queue_timeout_seconds", 0.05) + concurrency.init_semaphore(1) + sem = concurrency._semaphore # noqa: SLF001 + assert sem is not None + await sem.acquire() + voice = (await client.get("/voices")).json()[0]["identifier"] + resp = await client.post("/synthesize", json={"text": "Hello.", "voice": voice}) + sem.release() + assert resp.status_code == 429 + assert resp.headers["retry-after"] == "5" + assert resp.headers["content-type"].startswith("application/problem+json") diff --git a/tests/test_ffmpeg_bitrate.py b/tests/test_ffmpeg_bitrate.py new file mode 100644 index 0000000..b59bfff --- /dev/null +++ b/tests/test_ffmpeg_bitrate.py @@ -0,0 +1,14 @@ +from app.drivers.ffmpeg import bitrate_args + + +def test_defaults_are_speech_sized(): + assert bitrate_args("opus", None) == ["-b:a", "32k"] + assert bitrate_args("mp3", None) == ["-b:a", "64k"] + + +def test_request_bitrate_wins(): + assert bitrate_args("opus", 64) == ["-b:a", "64k"] + + +def test_wav_has_no_bitrate(): + assert bitrate_args("wav", None) == [] From 75a4b4093e88eafd41c660fa75b21402a2b24c9b Mon Sep 17 00:00:00 2001 From: Roni bhakta <77425964+ronibhakta1@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:50:03 +0530 Subject: [PATCH 3/3] fix: address review feedback on CORS, the circuit breaker, replay and deploy - deploy: give the SSH step a 20m command timeout, longer than the 12m readiness wait (the action's default is 10m). - circuit breaker: a half-open trial that ends with a client/quota error (404, 429) no longer keeps the single trial slot; record_neutral() frees it without changing the breaker's state. - CORS: unhandled errors are answered by Starlette's outermost layer, outside CORSMiddleware, so the 500 now carries the allow-origin header itself. - nginx: its own rate-limit 429 responses now carry the CORS headers for NGINX_CORS_ORIGIN (default https://readium.org), Retry-After and a JSON body. Security headers move into a snippet so the named location can include them. - demo: replay only when the first audio chunk is still there; a seek drops earlier chunks and replaying the tail as the whole clip would be wrong. - integration tests: initialise the semaphore for every test, not only the ones using the fixture. --- .github/workflows/ci.yml | 2 +- .github/workflows/deploy.yml | 2 ++ app/api/errors.py | 12 ++++++++++ app/core/circuit_breaker.py | 5 ++++ app/core/synthesizer.py | 7 ++++-- app/static/demo.html | 8 +++++-- docker-compose.yml | 1 + docs/configuration.md | 1 + nginx/snippets/security-headers.conf | 6 +++++ nginx/templates/00-hardening.conf.template | 7 ++++++ .../templates/20-speech-server.conf.template | 17 ++++++++++---- tests/integration/test_pocket_tts.py | 6 ++++- tests/test_circuit_breaker.py | 11 +++++++++ tests/test_cors.py | 23 +++++++++++++++++++ 14 files changed, 98 insertions(+), 10 deletions(-) create mode 100644 nginx/snippets/security-headers.conf 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 2d0576a..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 diff --git a/app/api/errors.py b/app/api/errors.py index 44a6762..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#" @@ -123,6 +125,15 @@ def _problem_response( # --- 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: @@ -160,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/core/circuit_breaker.py b/app/core/circuit_breaker.py index ed0f969..6217d4b 100644 --- a/app/core/circuit_breaker.py +++ b/app/core/circuit_breaker.py @@ -38,6 +38,11 @@ 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/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/static/demo.html b/app/static/demo.html index c16d820..712f4bd 100644 --- a/app/static/demo.html +++ b/app/static/demo.html @@ -814,8 +814,12 @@

Readium Speech Server Demo

navigator.play() from idle calls engine.speak(), which synthesizes again (new /synthesize request). Reschedule the kept buffers instead. Same private-field coupling as seekTo(). */ function replayLoaded() { - // Only a single-utterance load keeps the whole clip: a multi-utterance queue overwrites the chunks. - if (!chunkRanges().length || !engine['audioContext'] || engine.getUtteranceCount() !== 1) return false; + // Only a single-utterance load keeps the whole clip (a multi-utterance queue overwrites the + // chunks), and only while its first chunk is still there: seekTo() drops chunks before the seek + // point, and replaying the remaining tail as if it were the clip would be wrong. + const ranges = chunkRanges(); + if (!ranges.length || !engine['audioContext'] || engine.getUtteranceCount() !== 1) return false; + if (ranges[0].entry.chunk.textOffset) return false; seekTo(0); speechNavigator['setNavigatorState']('playing'); engine['setState']('playing'); diff --git a/docker-compose.yml b/docker-compose.yml index 6d5ac4d..1f62862 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,6 +29,7 @@ services: - "443:443" environment: - DOMAIN=${DOMAIN:-localhost} + - NGINX_CORS_ORIGIN=${NGINX_CORS_ORIGIN:-https://readium.org} volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - ./nginx/snippets:/etc/nginx/snippets:ro diff --git a/docs/configuration.md b/docs/configuration.md index d660e16..a0a7a47 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -81,6 +81,7 @@ only ever *adds* cross-language support: | `API_KEY_ENABLED` | `false` | Not implemented. `true` is rejected at startup (no route checks a key, so it would leave the API open) | | `API_KEY` | _(empty)_ | Reserved | | `CORS_ORIGINS` | `https://readium.org` | Comma-separated browser origins (scheme + host, no path) allowed to call the API cross-origin. Default is the Readium Speech demos (`https://readium.org/speech/demo/`). Empty disables CORS. nginx also lets `OPTIONS` through for the preflight | +| `NGINX_CORS_ORIGIN` | `https://readium.org` | Read by the nginx container only (compose `environment`). The one browser origin allowed on nginx's own rate-limit `429` responses, which are sent before the app's CORS layer. Keep it equal to the main entry of `CORS_ORIGINS` | | `SYNTHESIS_QUEUE_TIMEOUT_SECONDS` | `30` | How long a request waits for a free synthesis slot before `429` "busy" | | `LOG_LEVEL` | `INFO` | `DEBUG` · `INFO` · `WARNING` · `ERROR` | | `PORT` | `8000` | Listen port | diff --git a/nginx/snippets/security-headers.conf b/nginx/snippets/security-headers.conf new file mode 100644 index 0000000..7b7609a --- /dev/null +++ b/nginx/snippets/security-headers.conf @@ -0,0 +1,6 @@ +# Added to the server block and to every location that sets its own add_header (nginx does not +# inherit add_header into a location that defines one). +add_header X-Content-Type-Options nosniff always; +add_header X-Frame-Options DENY always; +add_header Referrer-Policy no-referrer always; +add_header Strict-Transport-Security "max-age=31536000" always; diff --git a/nginx/templates/00-hardening.conf.template b/nginx/templates/00-hardening.conf.template index 53c9b12..0a303c4 100644 --- a/nginx/templates/00-hardening.conf.template +++ b/nginx/templates/00-hardening.conf.template @@ -2,6 +2,13 @@ server_tokens off; +# The one browser origin allowed on nginx's own responses (rate-limit 429s). The app's CORS_ORIGINS +# (a list) covers everything the app answers; keep NGINX_CORS_ORIGIN equal to its main entry. +map $http_origin $cors_allow_origin { + default ""; + "${NGINX_CORS_ORIGIN}" $http_origin; +} + client_header_timeout 10s; client_body_timeout 10s; keepalive_timeout 15s; diff --git a/nginx/templates/20-speech-server.conf.template b/nginx/templates/20-speech-server.conf.template index d936405..51d51d8 100644 --- a/nginx/templates/20-speech-server.conf.template +++ b/nginx/templates/20-speech-server.conf.template @@ -46,10 +46,19 @@ server { # (fine — this is a low-latency in-network hop). resolver 127.0.0.11 valid=10s; - add_header X-Content-Type-Options nosniff always; - add_header X-Frame-Options DENY always; - add_header Referrer-Policy no-referrer always; - add_header Strict-Transport-Security "max-age=31536000" always; + include /etc/nginx/snippets/security-headers.conf; + + # nginx answers its own rate-limit 429s before the app (and its CORS layer) sees the request. + error_page 429 = @rate_limited; + location @rate_limited { + include /etc/nginx/snippets/security-headers.conf; + add_header Access-Control-Allow-Origin $cors_allow_origin always; + add_header Access-Control-Expose-Headers "Retry-After" always; + add_header Vary Origin always; + add_header Retry-After 1 always; + default_type application/problem+json; + return 429 '{"type":"about:blank","title":"Too Many Requests","status":429,"detail":"Rate limit exceeded."}'; + } # App serves no static files today; costs nothing to block dotfiles anyway. location ~ /\. { diff --git a/tests/integration/test_pocket_tts.py b/tests/integration/test_pocket_tts.py index 9404272..9c7df87 100644 --- a/tests/integration/test_pocket_tts.py +++ b/tests/integration/test_pocket_tts.py @@ -14,9 +14,13 @@ pytestmark = pytest.mark.integration +@pytest.fixture(autouse=True) +def _semaphore() -> None: + init_semaphore(1) # synthesize() runs inference through the semaphore + + @pytest.fixture async def pocket() -> PocketTTSProvider: - init_semaphore(1) # synthesize() runs inference through the semaphore p = PocketTTSProvider() await p.load() return p diff --git a/tests/test_circuit_breaker.py b/tests/test_circuit_breaker.py index 4e23c24..eb9d9f8 100644 --- a/tests/test_circuit_breaker.py +++ b/tests/test_circuit_breaker.py @@ -87,3 +87,14 @@ def test_half_open_allows_one_trial_at_a_time(monkeypatch) -> None: # type: ign assert b.allow() is False # everyone else waits for its result now[0] = 20 assert b.allow() is True # a trial that never reported is retried after recovery_seconds + + +def test_neutral_result_frees_the_half_open_trial(monkeypatch) -> None: # type: ignore[no-untyped-def] + now = [0.0] + monkeypatch.setattr(cb_mod.time, "monotonic", lambda: now[0]) + b = CircuitBreaker(failure_threshold=1, recovery_seconds=10) + b.record_failure() + now[0] = 10 + assert b.allow() is True # the trial + b.record_neutral() # it ended in a 404/429: no verdict on the provider + assert b.allow() is True # the next request is the new trial, not a 503 for 10 s diff --git a/tests/test_cors.py b/tests/test_cors.py index 2ef750e..bc964b8 100644 --- a/tests/test_cors.py +++ b/tests/test_cors.py @@ -75,3 +75,26 @@ async def test_busy_synthesize_returns_429_with_retry_after( assert resp.status_code == 429 assert resp.headers["retry-after"] == "5" assert resp.headers["content-type"].startswith("application/problem+json") + + +async def test_unhandled_error_still_carries_cors_headers() -> None: + """Starlette answers a crash in its outermost layer, outside CORSMiddleware.""" + from httpx import ASGITransport + + from app.main import create_app + + app = create_app() + + @app.get("/boom") + async def boom() -> None: + raise RuntimeError("boom") + + transport = ASGITransport(app=app, raise_app_exceptions=False) + async with AsyncClient(transport=transport, base_url="http://test") as c: + allowed = await c.get("/boom", headers={"Origin": _DEMO}) + other = await c.get("/boom", headers={"Origin": "https://evil.example"}) + assert allowed.status_code == 500 + assert allowed.headers["access-control-allow-origin"] == _DEMO + assert allowed.headers["content-type"].startswith("application/problem+json") + assert other.status_code == 500 + assert "access-control-allow-origin" not in other.headers