diff --git a/CLAUDE.md b/CLAUDE.md index 9ff89c7..9feff22 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -56,7 +56,7 @@ aai.settings.api_key = "your-key" - `aai.AsyncTextToSpeech` — Asyncio counterpart of `TextToSpeech`; `synthesize()` is a coroutine and `stream()` returns an `AsyncTTSStream`. Owns an HTTP pool: use `async with` or `await aclose()` - `aai.TTSSession` — Text-to-Speech WebSocket session: one connection, text in as it is written, audio out. `with` connects and waits for `Begin` (`session.begin`); `speak(text)` yields one request's audio; `generate(text)` / `flush()` -> flush_id / `audio(flush_id)` for streamed-in text and pipelining (`audio()` with no id follows the request being written, from another thread); `cancel()` for barge-in (ends the iteration at once); `keep_alive()`; `on(TTSEvents.X, handler(event))` for `Begin`, `Audio` (switches audio from pull to push), `FlushDone`, `WordBoundaries`, `Cancelled`, `Termination`, `Error`. Exit sends `Terminate` and sets `session.termination` (`None` after a failure). Refusals and failures raise `TTSError` (`status_code` None, `request_id` = session id). Raw PCM/G.711 only; 2,000 chars per generate unless `Begin` reports another `limits.max_generate_text_length`; ~100 chars/s sustained. `token=` for temporary tokens - `aai.AsyncTTSSession` — Asyncio counterpart: `async with`, coroutine sends, `async for chunk in session.speak(text)` -- `aai.TTSConfig` — Text-to-Speech options: `voice_id` (a library voice such as `aai-jane`, or a cloned voice by UUID or slug), `model_id` (`assemblyai-tts-1`), `language`, `sample_rate`, `encoding` (`aai.TTSEncoding`: `pcm_s16le` default | `pcm_mulaw` | `pcm_alaw` | `mp3`), `container` (`aai.TTSContainer`: `raw` default | `wav`), `bit_rate`, `extend_biometric_consent` (owner-only consent renewal of a cloned voice). Rejects unknown fields +- `aai.TTSConfig` — Text-to-Speech options: `voice_id` (a library voice such as `aai-jane`, or a cloned voice by UUID or slug; unset, the language's default voice, `aai-kyla` in English), `model_id` (`assemblyai-tts-1-1`, 25 languages, the default in all of them; `assemblyai-tts-1`, 6 languages; leave it out unless a model must be pinned), `language` (English name: `english`, `japanese`, ...; a plain string the API checks), `sample_rate`, `encoding` (`aai.TTSEncoding`: `pcm_s16le` default | `pcm_mulaw` | `pcm_alaw` | `mp3`), `container` (`aai.TTSContainer`: `raw` default | `wav`), `bit_rate`, `extend_biometric_consent` (owner-only consent renewal of a cloned voice). Rejects unknown fields - `aai.TTSResponse` — Text-to-Speech result: `.audio` (bytes) plus the response headers: `.request_id`, `.region`, `.model`, `.voice_id`, `.language`, `.encoding`, `.sample_rate`, `.container`, `.bit_rate`, `.content_type`, `.voice_expires_at`, `.billed_characters`, `.audio_duration_ms`. `TTSStream.info` carries the same fields without `audio`; `audio_duration_ms` is `None` on a stream with audio (`0` when the text had nothing to speak) - `aai.TTSError` — Raised on any Text-to-Speech refusal: `.status_code`, `.error_code` (stable API code; `biometric_terms_not_accepted` 403 until the account accepts the biometric data terms in the dashboard, `auth_unavailable` 503 retryable; on a session these arrive as close 3006 and 1011, with `status_code` None, the close code in `.body["close_code"]` and `.retryable` from the API's Error frame), `.param`, `.request_id`, `.retryable`, `.retry_after`, `.errors`, `.body` (the whole envelope) - `assemblyai.streaming.v3.RealTimeTranscriber` — Real-time streaming with event-based API (threaded) diff --git a/README.md b/README.md index 105d5c5..f095e44 100644 --- a/README.md +++ b/README.md @@ -900,7 +900,7 @@ except aai.DictationError as error: ### **Text-to-Speech Examples** -`aai.TextToSpeech` speaks one text per HTTP request on the Text-to-Speech API. `synthesize()` returns the complete audio; `stream()` returns it as the API generates it, so playback can start long before the sentence ends. A text is 1 to 5,000 characters. Options go in a `TTSConfig`: the `voice_id` (a voice of the AssemblyAI voice library by its slug: `aai-jane` by default, `aai-alba`, `aai-anna`, `aai-charles`, `aai-eve`, `aai-george`, `aai-jean`, `aai-mary`, `aai-michael`, `aai-paul`, `aai-vera` and hundreds more; or a voice cloned by your account, by its UUID or slug), the `model_id` (`assemblyai-tts-1`), the `language` (`english`, `spanish`, `german`, `french`, `italian`, `portuguese`), the `sample_rate` (8000, 16000, 22050, 24000 by default, 44100, 48000), the `encoding` (`pcm_s16le` by default, `pcm_mulaw`/`pcm_alaw` for telephony, `mp3`) and the `container` (`raw` or `wav`). A per-call `TTSConfig` replaces the client's default config whole. Voices are created and managed in the AssemblyAI dashboard. +`aai.TextToSpeech` speaks one text per HTTP request on the Text-to-Speech API. `synthesize()` returns the complete audio; `stream()` returns it as the API generates it, so playback can start long before the sentence ends. A text is 1 to 5,000 characters. Options go in a `TTSConfig`: the `voice_id` (a voice of the AssemblyAI voice library by its slug, such as `aai-kyla`, `aai-jane`, `aai-alba`, `aai-anna`, `aai-charles`, `aai-eve`, `aai-george`, `aai-jean`, `aai-mary`, `aai-michael`, `aai-paul`, `aai-vera` and thousands more; or a voice cloned by your account, by its UUID or slug), the `model_id` (`assemblyai-tts-1-1`, the default, for 25 languages, or `assemblyai-tts-1` for six; best left out), the `language` by its English name (`english`, `spanish`, `german`, `french`, `italian` and `portuguese` on both models; `japanese`, `vietnamese`, `chinese`, `swedish`, `dutch`, `russian`, `danish`, `hindi`, `arabic`, `norwegian`, `romanian`, `finnish`, `korean`, `urdu`, `catalan`, `hebrew`, `turkish`, `cantonese` and `afrikaans` on `assemblyai-tts-1-1`), the `sample_rate` (8000, 16000, 22050, 24000 by default, 44100, 48000), the `encoding` (`pcm_s16le` by default, `pcm_mulaw`/`pcm_alaw` for telephony, `mp3`) and the `container` (`raw` or `wav`). A per-call `TTSConfig` replaces the client's default config whole. Without a `voice_id`, a request speaks with the default voice of its language: `aai-kyla` in English (also when `language` is left out), `aai-antonioluis` in Spanish, `aai-magdalena` in German, `aai-giada` in Italian, `aai-nelson` in Portuguese and `aai-donatien` in French. The defaults may change: name a voice with `voice_id` to keep the same one. Voices are created and managed in the AssemblyAI dashboard. Requests go to `aai.settings.tts_base_url`, `https://tts.us.assemblyai.com` by default; set it to `https://tts.eu.assemblyai.com` to keep them in the EU data zone. They share a connection pool of their own that keeps an idle connection for 120 seconds by default, so a request that follows the previous one within that time, such as a voice agent's next sentence, reuses its connection instead of opening a new one. If you set `aai.settings.keepalive_expiry` shorter than that, this pool uses it too; `aai.settings.tts_keepalive_expiry` sets this pool's idle time on its own. A client you pass as `client=` stays yours to close: `client.close()` closes both of its pools. @@ -930,6 +930,28 @@ print(response.model, response.voice_id, response.audio_duration_ms, "ms") +
+ Speak another language with assemblyai-tts-1-1 + +```python +import assemblyai as aai + +aai.settings.api_key = "" + +tts = aai.TextToSpeech() + +response = tts.synthesize( + "こんにちは、AssemblyAIです。", + aai.TTSConfig(voice_id="aai-jane", language="japanese"), +) + +print(response.model, response.language) # assemblyai-tts-1-1 japanese +``` + +`assemblyai-tts-1-1` speaks 25 languages and is the default model in every one of them, so leave `model_id` out unless you need a particular model. `assemblyai-tts-1` speaks `english`, `spanish`, `german`, `french`, `italian` and `portuguese`: set `model_id="assemblyai-tts-1"` to keep one of them on that model. A library voice of the nineteen newer languages works only on `assemblyai-tts-1-1`. The voice library in the AssemblyAI dashboard lists the voices of each language. + +
+
Stream audio as it is generated diff --git a/assemblyai/__version__.py b/assemblyai/__version__.py index f5d43bc..cbdbd05 100644 --- a/assemblyai/__version__.py +++ b/assemblyai/__version__.py @@ -1 +1 @@ -__version__ = "1.10.14" +__version__ = "1.10.15" diff --git a/assemblyai/tts/v1/models.py b/assemblyai/tts/v1/models.py index 4d00239..cff91c2 100644 --- a/assemblyai/tts/v1/models.py +++ b/assemblyai/tts/v1/models.py @@ -137,34 +137,50 @@ class TTSConfig(BaseModel): """ Options for a Text-to-Speech request. - Every field is optional: the API speaks English with its default voice - (`aai-jane`) at 24 kHz as raw 16-bit PCM when nothing is set. Every voice - is named by `voice_id`. Unknown fields are rejected rather than silently - dropped, so a typo surfaces as a validation error. `speed` (only 1 is - supported) and `word_boundaries` (served by `/v1/speech/events`) are - left out on purpose. + Every field is optional: the API speaks English with the default voice of + English (`aai-kyla`) at 24 kHz as raw 16-bit PCM when nothing is set. + Every voice is named by `voice_id`. Unknown fields are rejected rather + than silently dropped, so a typo surfaces as a validation error. `speed` + (only 1 is supported) and `word_boundaries` (served by + `/v1/speech/events`) are left out on purpose. """ voice_id: Optional[str] = None """The voice: a voice of the AssemblyAI voice library by its slug, such as - `aai-jane` (the default), `aai-alba` or `aai-michael`; a voice's ID (a - UUID); or the slug of one of the account's own cloned voices. The - dashboard shows the value that names each voice. A voice belongs to the - data zone it was created in: on the other zone's host it is - `voice_not_found`.""" + `aai-kyla`, `aai-alba` or `aai-michael`; a voice's ID (a UUID); or the + slug of one of the account's own cloned voices. The dashboard shows the + value that names each voice. A voice belongs to the data zone it was + created in: on the other zone's host it is `voice_not_found`. Defaults + to the default voice of the request's language: `aai-kyla` in English + (also when `language` is left out), `aai-antonioluis` in Spanish, + `aai-magdalena` in German, `aai-giada` in Italian, `aai-nelson` in + Portuguese and `aai-donatien` in French. The defaults may change: name a + voice to keep the same one.""" model_id: Optional[str] = None - """The model to run the request on, such as `assemblyai-tts-1`. Defaults to - the region's default model of the request's language. A cloned voice must - be paired with it.""" + """The model to run the request on: `assemblyai-tts-1-1` (25 languages) or + `assemblyai-tts-1` (6 languages). Defaults to the region's default model + of the request's language, `assemblyai-tts-1-1` in every language. Leave + it out unless you need a particular model, such as `assemblyai-tts-1` for + one of the six languages it speaks. A cloned voice must be paired with + it.""" language: Optional[str] = None - """The language, by its English name: `english`, `spanish`, `german`, - `french`, `italian` or `portuguese`. Case-insensitive. Defaults to the - voice's own language. The eleven built-in voices (`aai-jane`, `aai-alba`, - `aai-anna`, `aai-charles`, `aai-eve`, `aai-george`, `aai-jean`, - `aai-mary`, `aai-michael`, `aai-paul`, `aai-vera`) speak all six; another - voice speaks a language other than its own only where its model can.""" + """The language, by its English name, such as `english` or `japanese`. + Case-insensitive. Defaults to the voice's own language. + `assemblyai-tts-1` speaks `english`, `spanish`, `german`, `french`, + `italian` and `portuguese`. `assemblyai-tts-1-1` speaks those six and + `japanese`, `vietnamese`, `chinese`, `swedish`, `dutch`, `russian`, + `danish`, `hindi`, `arabic`, `norwegian`, `romanian`, `finnish`, + `korean`, `urdu`, `catalan`, `hebrew`, `turkish`, `cantonese` and + `afrikaans`. Each model speaks a voice in any of its languages, usually + best in the voice's own. The library voices of the first six languages, + the eleven built-in voices (`aai-jane`, `aai-alba`, `aai-anna`, + `aai-charles`, `aai-eve`, `aai-george`, `aai-jean`, `aai-mary`, + `aai-michael`, `aai-paul`, `aai-vera`) included, work on both models. A + library voice of the other nineteen works only on `assemblyai-tts-1-1`, + in any of its 25 languages: with `model_id="assemblyai-tts-1"` it is + refused `voice_not_paired`.""" sample_rate: Optional[int] = None "Output sample rate in Hz: 8000, 16000, 22050, 24000 (the default), 44100 or 48000." @@ -223,11 +239,12 @@ class TTSResponseInfo(BaseModel): "The region that served the request, such as `us-east-1`." model: Optional[str] = None - "The model that spoke, such as `assemblyai-tts-1`." + "The model that spoke, such as `assemblyai-tts-1` or `assemblyai-tts-1-1`." voice_id: Optional[str] = None - """The voice that spoke: the request's `voice_id`, or the default voice's - slug (`aai-jane`) when the request named none.""" + """The voice that spoke: the request's `voice_id`, or the slug of the + language's default voice (such as `aai-kyla` in English) when the request + named none.""" language: Optional[str] = None "The language used, lowercase." diff --git a/assemblyai/tts/v1/ws_models.py b/assemblyai/tts/v1/ws_models.py index 27c3ebc..dafc683 100644 --- a/assemblyai/tts/v1/ws_models.py +++ b/assemblyai/tts/v1/ws_models.py @@ -107,7 +107,12 @@ class TTSFlushDoneEvent(BaseModel): class TTSWord(BaseModel): word: str - "One whitespace-delimited token of the request's text, verbatim." + """One unit of the request's text, verbatim, punctuation attached: a + whitespace-delimited token, except in `japanese`, `chinese` and + `cantonese`, where each Han, hiragana or katakana character is a unit of + its own and a run of other letters or digits stays whole (`我用iPhone15` + gives `我`, `用`, `iPhone15`). In every language the words joined give + the text without its whitespace.""" start: int """Milliseconds on the session's whole audio timeline, not the request's: subtract the event's `audio_start_ms` for a time within the request.""" @@ -123,6 +128,8 @@ class TTSWordBoundariesEvent(BaseModel): iteration has ended, and possibly after the next request's first audio; match it by `flush_id`. `start` and `end` count from the start of the session's audio; `start - audio_start_ms` is the time within the request. + In Japanese, Chinese and Cantonese a long request often gets no timings: + flush every sentence or two to keep them. """ flush_id: int diff --git a/tests/unit/test_tts.py b/tests/unit/test_tts.py index 20f0b28..7877ae8 100644 --- a/tests/unit/test_tts.py +++ b/tests/unit/test_tts.py @@ -138,6 +138,31 @@ def test_config_fields_go_in_the_body_and_unset_ones_stay_out(httpx_mock: HTTPXM } +@pytest.mark.parametrize("language", ["japanese", "cantonese", "afrikaans"]) +def test_model_id_and_language_reach_the_api_as_given( + httpx_mock: HTTPXMock, language: str +): + # GIVEN a language that only the 25-language model speaks + _mock_ok( + httpx_mock, + **{"x-tts-model": "assemblyai-tts-1-1", "x-tts-language": language}, + ) + + # WHEN a request names both + response = aai.TextToSpeech().synthesize( + "Hi.", + aai.TTSConfig( + voice_id="aai-jane", model_id="assemblyai-tts-1-1", language=language + ), + ) + + # THEN the SDK sends them unchanged (the API checks them) and reports + # what the API used + body = _sent_body(httpx_mock) + assert (body["model_id"], body["language"]) == ("assemblyai-tts-1-1", language) + assert (response.model, response.language) == ("assemblyai-tts-1-1", language) + + def test_default_config_is_used_when_no_per_call_config(httpx_mock: HTTPXMock): _mock_ok(httpx_mock) aai.TextToSpeech(config=aai.TTSConfig(voice_id="aai-alba")).synthesize("Hi.") diff --git a/tests/unit/test_tts_session.py b/tests/unit/test_tts_session.py index bbb804a..beb8ad9 100644 --- a/tests/unit/test_tts_session.py +++ b/tests/unit/test_tts_session.py @@ -228,6 +228,18 @@ def test_with_connects_waits_for_begin_and_terminates_on_exit(server): assert server.closed +def test_model_id_and_language_go_in_the_query_as_given(server): + config = aai.TTSConfig( + voice_id="aai-jane", model_id="assemblyai-tts-1-1", language="korean" + ) + with aai.TTSSession(config=config): + pass + + query = parse_qs(urlsplit(server.connect.call_args.args[0]).query) + assert query["model_id"] == ["assemblyai-tts-1-1"] + assert query["language"] == ["korean"] + + def test_speak_sends_generate_and_flush_and_yields_the_audio(server): with aai.TTSSession() as session: chunks = _drain(session.speak("Hello there."))