tontaube-client 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Cremer & Cremer Technologies UG (haftungsbeschränkt)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: tontaube-client
3
+ Version: 0.3.0
4
+ Summary: Python SDK for the Tontaube text-to-speech API
5
+ License: MIT
6
+ Project-URL: Homepage, https://tontaube.ai
7
+ Project-URL: Repository, https://github.com/craitech/tontaube-sdk-python
8
+ Project-URL: API Reference, https://tontaube.ai/api-reference
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: httpx>=0.24
13
+ Requires-Dist: packaging>=21.0
14
+ Requires-Dist: pydantic>=2.0
15
+ Dynamic: license-file
16
+
17
+ # tontaube-client
18
+
19
+ Python SDK for the [Tontaube](https://tontaube.ai) text-to-speech API.
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install tontaube-client
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ```python
30
+ import tontaube_client
31
+
32
+ with tontaube_client.Client(api_key="your-api-key") as client:
33
+ voices = client.list_voices()
34
+ response = client.generate_speech(
35
+ text="Tell me what we are building today, and I will get right to work.",
36
+ voice_id=voices[0].id,
37
+ )
38
+
39
+ with open("speech.m4a", "wb") as f:
40
+ f.write(response.content)
41
+ ```
42
+
43
+ Audio is returned as Opus in an MP4 container. Async client is also available via `tontaube_client.AsyncClient`.
44
+
45
+ ## Your own voices
46
+
47
+ ```python
48
+ voice = client.create_voice(name="My voice", audio="reference.wav", language="en")
49
+ response = client.generate_speech(text="Hello in my own voice.", voice_id=voice.id)
50
+ ```
51
+
52
+ `list_voices()` returns your voices and the Tontaube library voices, `get_voice()` and `delete_voice()` manage them.
53
+ For a one-off voice without storing it, pass the recording directly: `generate_speech(text, voice_audio="reference.wav")`.
54
+
55
+ ## Streaming
56
+
57
+ ```python
58
+ with open("speech.mp3", "wb") as f:
59
+ for chunk in client.stream_speech(text="Hello while it is still being generated.", voice_id=voice.id):
60
+ f.write(chunk)
61
+ ```
62
+
63
+ ## More options
64
+
65
+ - `style` (`audiobook`, `conversational`, `agentic`) and `controls=tontaube_client.Controls(rate=1, pause=3)` shape the delivery.
66
+ - `seed` makes a generation repeatable.
67
+ - `style`, `controls`, `seed` and `prefix` work for streaming too.
68
+ - `include_timestamps=True` returns when each word is spoken (English).
69
+ - `return_context=True` and `prefix` continue earlier speech seamlessly.
70
+
71
+ Errors from the API raise `tontaube_client.APIError` with `status_code`, `code` and `message`.
72
+
73
+ See the [examples/](examples/) folder for more usage patterns.
74
+
75
+ For full API reference see [tontaube.ai/api-reference](https://tontaube.ai/api-reference).
76
+
77
+ ## Coming from `tontaube` 0.2
78
+
79
+ Until version 0.2 this client was published as `tontaube` and imported as `import tontaube`. The PyPI name `tontaube` now belongs to the Tontaube inference server (version 1 and later). To move over:
80
+
81
+ ```bash
82
+ pip uninstall tontaube
83
+ pip install tontaube-client
84
+ ```
85
+
86
+ Then change the import to `import tontaube_client`, or keep your code as it is with one line:
87
+
88
+ ```python
89
+ import tontaube_client as tontaube
90
+ ```
91
+
92
+ To stay on the old package instead, pin `tontaube<1`.
@@ -0,0 +1,76 @@
1
+ # tontaube-client
2
+
3
+ Python SDK for the [Tontaube](https://tontaube.ai) text-to-speech API.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install tontaube-client
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ import tontaube_client
15
+
16
+ with tontaube_client.Client(api_key="your-api-key") as client:
17
+ voices = client.list_voices()
18
+ response = client.generate_speech(
19
+ text="Tell me what we are building today, and I will get right to work.",
20
+ voice_id=voices[0].id,
21
+ )
22
+
23
+ with open("speech.m4a", "wb") as f:
24
+ f.write(response.content)
25
+ ```
26
+
27
+ Audio is returned as Opus in an MP4 container. Async client is also available via `tontaube_client.AsyncClient`.
28
+
29
+ ## Your own voices
30
+
31
+ ```python
32
+ voice = client.create_voice(name="My voice", audio="reference.wav", language="en")
33
+ response = client.generate_speech(text="Hello in my own voice.", voice_id=voice.id)
34
+ ```
35
+
36
+ `list_voices()` returns your voices and the Tontaube library voices, `get_voice()` and `delete_voice()` manage them.
37
+ For a one-off voice without storing it, pass the recording directly: `generate_speech(text, voice_audio="reference.wav")`.
38
+
39
+ ## Streaming
40
+
41
+ ```python
42
+ with open("speech.mp3", "wb") as f:
43
+ for chunk in client.stream_speech(text="Hello while it is still being generated.", voice_id=voice.id):
44
+ f.write(chunk)
45
+ ```
46
+
47
+ ## More options
48
+
49
+ - `style` (`audiobook`, `conversational`, `agentic`) and `controls=tontaube_client.Controls(rate=1, pause=3)` shape the delivery.
50
+ - `seed` makes a generation repeatable.
51
+ - `style`, `controls`, `seed` and `prefix` work for streaming too.
52
+ - `include_timestamps=True` returns when each word is spoken (English).
53
+ - `return_context=True` and `prefix` continue earlier speech seamlessly.
54
+
55
+ Errors from the API raise `tontaube_client.APIError` with `status_code`, `code` and `message`.
56
+
57
+ See the [examples/](examples/) folder for more usage patterns.
58
+
59
+ For full API reference see [tontaube.ai/api-reference](https://tontaube.ai/api-reference).
60
+
61
+ ## Coming from `tontaube` 0.2
62
+
63
+ Until version 0.2 this client was published as `tontaube` and imported as `import tontaube`. The PyPI name `tontaube` now belongs to the Tontaube inference server (version 1 and later). To move over:
64
+
65
+ ```bash
66
+ pip uninstall tontaube
67
+ pip install tontaube-client
68
+ ```
69
+
70
+ Then change the import to `import tontaube_client`, or keep your code as it is with one line:
71
+
72
+ ```python
73
+ import tontaube_client as tontaube
74
+ ```
75
+
76
+ To stay on the old package instead, pin `tontaube<1`.
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "tontaube-client"
3
+ version = "0.3.0"
4
+ description = "Python SDK for the Tontaube text-to-speech API"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = { text = "MIT" }
8
+ dependencies = [
9
+ "httpx>=0.24",
10
+ "packaging>=21.0",
11
+ "pydantic>=2.0",
12
+ ]
13
+
14
+ [project.urls]
15
+ Homepage = "https://tontaube.ai"
16
+ Repository = "https://github.com/craitech/tontaube-sdk-python"
17
+ "API Reference" = "https://tontaube.ai/api-reference"
18
+
19
+ [build-system]
20
+ requires = ["setuptools", "wheel"]
21
+ build-backend = "setuptools.build_meta"
22
+
23
+ [dependency-groups]
24
+ dev = [
25
+ "pytest>=8.0",
26
+ "ruff", # For Formatting
27
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,43 @@
1
+ from ._client import Client
2
+ from ._async_client import AsyncClient
3
+ from .models import (
4
+ Speaker,
5
+ Voice,
6
+ Controls,
7
+ ContextSlice,
8
+ Silence,
9
+ Prefix,
10
+ Word,
11
+ Character,
12
+ Timestamps,
13
+ GenerateRequest,
14
+ StreamRequest,
15
+ GenerateResponse,
16
+ )
17
+ from .core import build_headers
18
+ from ._constants import DEFAULT_BASE_URL, DEFAULT_TIMEOUT
19
+ from ._exceptions import APIError, OutdatedSDKError
20
+ from .version import __version__
21
+
22
+ __all__ = [
23
+ "Client",
24
+ "AsyncClient",
25
+ "Speaker",
26
+ "Voice",
27
+ "Controls",
28
+ "ContextSlice",
29
+ "Silence",
30
+ "Prefix",
31
+ "Word",
32
+ "Character",
33
+ "Timestamps",
34
+ "GenerateRequest",
35
+ "StreamRequest",
36
+ "GenerateResponse",
37
+ "APIError",
38
+ "OutdatedSDKError",
39
+ "build_headers",
40
+ "DEFAULT_BASE_URL",
41
+ "DEFAULT_TIMEOUT",
42
+ "__version__",
43
+ ]
@@ -0,0 +1,136 @@
1
+ from typing import AsyncIterator, List, Optional, Union
2
+
3
+ import httpx
4
+
5
+ from .models import Speaker, Voice, Controls, Prefix, GenerateRequest, GenerateResponse, StreamRequest
6
+ from .core import AudioInput
7
+ from ._base_client import BaseClient
8
+ from ._constants import DEFAULT_BASE_URL, VERSION_CHECK_TIMEOUT
9
+
10
+
11
+ class AsyncClient(BaseClient):
12
+ def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, **kwargs):
13
+ super().__init__(api_key, base_url, **kwargs)
14
+ self._http_client = httpx.AsyncClient(
15
+ base_url=self.base_url,
16
+ headers=self._headers,
17
+ timeout=self._timeout,
18
+ )
19
+
20
+ async def check_version(self) -> None:
21
+ try:
22
+ response = await self._http_client.get("/sdk-status", timeout=VERSION_CHECK_TIMEOUT)
23
+ response.raise_for_status()
24
+ self._evaluate_version(response.json())
25
+ except RuntimeError:
26
+ raise
27
+ except Exception:
28
+ return
29
+
30
+ async def list_speakers(self) -> List[Speaker]:
31
+ response = await self._http_client.get("/speech/speakers")
32
+ self._handle_response(response)
33
+ return [Speaker.model_validate(s) for s in response.json()]
34
+
35
+ async def list_voices(self, type: Optional[str] = None) -> List[Voice]:
36
+ response = await self._http_client.get("/voices", params={"type": type} if type else None)
37
+ self._handle_response(response)
38
+ return [Voice.model_validate(v) for v in response.json()]
39
+
40
+ async def get_voice(self, voice_id: str) -> Voice:
41
+ response = await self._http_client.get(f"/voices/{voice_id}")
42
+ self._handle_response(response)
43
+ return Voice.model_validate(response.json())
44
+
45
+ async def create_voice(self, name: str, audio: AudioInput, language: Optional[str] = None) -> Voice:
46
+ response = await self._http_client.post("/voices", **self._voice_upload(name, audio, language))
47
+ self._handle_response(response)
48
+ return Voice.model_validate(response.json())
49
+
50
+ async def delete_voice(self, voice_id: str) -> None:
51
+ response = await self._http_client.delete(f"/voices/{voice_id}")
52
+ self._handle_response(response)
53
+
54
+ async def generate_speech(
55
+ self,
56
+ text: str,
57
+ voice_id: Optional[str] = None,
58
+ language: Optional[str] = None,
59
+ format: Optional[str] = None,
60
+ temperature: Optional[float] = None,
61
+ speaker_id: Optional[str] = None,
62
+ voice_audio: Optional[AudioInput] = None,
63
+ controls: Optional[Union[Controls, dict]] = None,
64
+ style: Optional[str] = None,
65
+ seed: Optional[int] = None,
66
+ prefix: Optional[Union[Prefix, dict]] = None,
67
+ return_context: Optional[bool] = None,
68
+ include_timestamps: Optional[bool] = None,
69
+ audio_format: Optional[str] = None,
70
+ sample_rate: Optional[int] = None,
71
+ ) -> GenerateResponse:
72
+ payload = self._speech_payload(
73
+ GenerateRequest,
74
+ text=text,
75
+ voice_id=voice_id,
76
+ speaker_id=speaker_id,
77
+ voice_audio=voice_audio,
78
+ language=language,
79
+ format=format,
80
+ temperature=temperature,
81
+ controls=controls,
82
+ style=style,
83
+ seed=seed,
84
+ prefix=prefix,
85
+ return_context=return_context,
86
+ include_timestamps=include_timestamps,
87
+ audio_format=audio_format,
88
+ sample_rate=sample_rate,
89
+ )
90
+
91
+ response = await self._http_client.post("/speech/generate", json=payload)
92
+ self._handle_response(response)
93
+ return self._speech_response(response)
94
+
95
+ async def stream_speech(
96
+ self,
97
+ text: str,
98
+ voice_id: Optional[str] = None,
99
+ language: Optional[str] = None,
100
+ temperature: Optional[float] = None,
101
+ speaker_id: Optional[str] = None,
102
+ voice_audio: Optional[AudioInput] = None,
103
+ controls: Optional[Union[Controls, dict]] = None,
104
+ style: Optional[str] = None,
105
+ seed: Optional[int] = None,
106
+ prefix: Optional[Union[Prefix, dict]] = None,
107
+ ) -> AsyncIterator[bytes]:
108
+ payload = self._speech_payload(
109
+ StreamRequest,
110
+ text=text,
111
+ voice_id=voice_id,
112
+ speaker_id=speaker_id,
113
+ voice_audio=voice_audio,
114
+ language=language,
115
+ temperature=temperature,
116
+ controls=controls,
117
+ style=style,
118
+ seed=seed,
119
+ prefix=prefix,
120
+ )
121
+
122
+ async with self._http_client.stream("POST", "/speech/stream", json=payload) as response:
123
+ if response.is_error:
124
+ await response.aread()
125
+ self._handle_response(response)
126
+ async for chunk in response.aiter_bytes():
127
+ yield chunk
128
+
129
+ async def close(self):
130
+ await self._http_client.aclose()
131
+
132
+ async def __aenter__(self):
133
+ return self
134
+
135
+ async def __aexit__(self, *args):
136
+ await self.close()
@@ -0,0 +1,105 @@
1
+ import base64
2
+ import warnings
3
+
4
+ import httpx
5
+ from packaging.version import Version
6
+ from typing import Optional, Tuple, Type
7
+
8
+ from ._exceptions import APIError, OutdatedSDKError
9
+ from .version import __version__
10
+ from .core import AudioInput, build_headers, read_audio
11
+ from .models import GenerateRequest, GenerateResponse
12
+ from ._constants import DEFAULT_BASE_URL, DEFAULT_TIMEOUT
13
+
14
+
15
+ class BaseClient:
16
+ def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, _check_version: bool = True):
17
+ self.api_key = api_key
18
+ self.base_url = base_url
19
+ self._headers = build_headers(self.api_key)
20
+ self._timeout = DEFAULT_TIMEOUT
21
+ self._should_check_version = _check_version
22
+
23
+ def _evaluate_version(self, data: dict) -> None:
24
+ current = Version(__version__)
25
+ min_version = Version(data["min_version"])
26
+ latest_version = Version(data["latest_version"])
27
+
28
+ if current < min_version:
29
+ raise RuntimeError(
30
+ f"This version of the SDK ({__version__}) is no longer supported. "
31
+ f"Minimum required version is {min_version}. "
32
+ "Please upgrade: pip install --upgrade tontaube-client"
33
+ )
34
+
35
+ if current < latest_version:
36
+ warnings.warn(
37
+ f"A newer version of the SDK is available ({latest_version}). "
38
+ f"You are using {__version__}. "
39
+ "Please upgrade: pip install --upgrade tontaube-client",
40
+ DeprecationWarning,
41
+ stacklevel=3,
42
+ )
43
+
44
+ def _handle_response(self, response: httpx.Response) -> httpx.Response:
45
+ if response.status_code == 426:
46
+ try:
47
+ body = response.json()
48
+ message = body.get("message", "SDK upgrade required.")
49
+ upgrade_command = body.get(
50
+ "upgrade_command", "pip install --upgrade tontaube-client"
51
+ )
52
+ except Exception:
53
+ message = "SDK upgrade required."
54
+ upgrade_command = "pip install --upgrade tontaube-client"
55
+ raise OutdatedSDKError(f"{message} Upgrade with: {upgrade_command}")
56
+ if response.is_error:
57
+ raise APIError(response, *self._error_details(response))
58
+ return response
59
+
60
+ @staticmethod
61
+ def _error_details(response: httpx.Response) -> Tuple[Optional[str], str]:
62
+ try:
63
+ detail = response.json().get("detail")
64
+ except Exception:
65
+ detail = None
66
+ if isinstance(detail, dict):
67
+ return detail.get("error"), detail.get("message") or str(detail)
68
+ if isinstance(detail, list) and detail:
69
+ messages = [item.get("msg", str(item)) if isinstance(item, dict) else str(item) for item in detail]
70
+ return "invalid_request", "; ".join(messages)
71
+ if isinstance(detail, str):
72
+ return None, detail
73
+ return None, response.text or response.reason_phrase
74
+
75
+ @staticmethod
76
+ def _speech_payload(model: Type[GenerateRequest], voice_audio: Optional[AudioInput] = None, **fields) -> dict:
77
+ if voice_audio is not None:
78
+ fields["voice_audio_b64"] = base64.b64encode(read_audio(voice_audio)[1]).decode("ascii")
79
+ return model(**fields).model_dump(mode="json", exclude_none=True)
80
+
81
+ @staticmethod
82
+ def _speech_response(response: httpx.Response) -> GenerateResponse:
83
+ headers = response.headers
84
+ fields = {
85
+ "mime_type": headers.get("content-type"),
86
+ "sample_rate": headers.get("x-sample-rate"),
87
+ "audio_duration": headers.get("x-audio-duration"),
88
+ "cost_usd": headers.get("x-cost-usd"),
89
+ "balance_usd": headers.get("x-balance-usd"),
90
+ "seed": headers.get("x-seed"),
91
+ "request_id": headers.get("x-request-id"),
92
+ }
93
+ if not fields["mime_type"] or not fields["mime_type"].startswith("application/json"):
94
+ return GenerateResponse(content=response.content, **fields)
95
+ body = response.json()
96
+ content = base64.b64decode(body.pop("audio_b64"))
97
+ body["audio_duration"] = body.pop("duration", fields["audio_duration"])
98
+ return GenerateResponse(content=content, **{**fields, **body})
99
+
100
+ @staticmethod
101
+ def _voice_upload(name: str, audio: AudioInput, language: Optional[str]) -> dict:
102
+ data = {"name": name}
103
+ if language is not None:
104
+ data["language"] = language
105
+ return {"data": data, "files": {"file": read_audio(audio)}}
@@ -0,0 +1,135 @@
1
+ from typing import Iterator, List, Optional, Union
2
+
3
+ import httpx
4
+
5
+ from .models import Speaker, Voice, Controls, Prefix, GenerateRequest, GenerateResponse, StreamRequest
6
+ from .core import AudioInput
7
+ from ._base_client import BaseClient
8
+ from ._constants import DEFAULT_BASE_URL, VERSION_CHECK_TIMEOUT
9
+
10
+
11
+ class Client(BaseClient):
12
+ def __init__(self, api_key: str, base_url: str = DEFAULT_BASE_URL, **kwargs):
13
+ super().__init__(api_key, base_url, **kwargs)
14
+ self._http_client = httpx.Client(
15
+ base_url=self.base_url,
16
+ headers=self._headers,
17
+ timeout=self._timeout,
18
+ )
19
+
20
+ def check_version(self) -> None:
21
+ try:
22
+ response = self._http_client.get("/sdk-status", timeout=VERSION_CHECK_TIMEOUT)
23
+ response.raise_for_status()
24
+ self._evaluate_version(response.json())
25
+ except RuntimeError:
26
+ raise
27
+ except Exception:
28
+ return
29
+
30
+ def list_speakers(self) -> List[Speaker]:
31
+ response = self._http_client.get("/speech/speakers")
32
+ self._handle_response(response)
33
+ return [Speaker.model_validate(s) for s in response.json()]
34
+
35
+ def list_voices(self, type: Optional[str] = None) -> List[Voice]:
36
+ response = self._http_client.get("/voices", params={"type": type} if type else None)
37
+ self._handle_response(response)
38
+ return [Voice.model_validate(v) for v in response.json()]
39
+
40
+ def get_voice(self, voice_id: str) -> Voice:
41
+ response = self._http_client.get(f"/voices/{voice_id}")
42
+ self._handle_response(response)
43
+ return Voice.model_validate(response.json())
44
+
45
+ def create_voice(self, name: str, audio: AudioInput, language: Optional[str] = None) -> Voice:
46
+ response = self._http_client.post("/voices", **self._voice_upload(name, audio, language))
47
+ self._handle_response(response)
48
+ return Voice.model_validate(response.json())
49
+
50
+ def delete_voice(self, voice_id: str) -> None:
51
+ response = self._http_client.delete(f"/voices/{voice_id}")
52
+ self._handle_response(response)
53
+
54
+ def generate_speech(
55
+ self,
56
+ text: str,
57
+ voice_id: Optional[str] = None,
58
+ language: Optional[str] = None,
59
+ format: Optional[str] = None,
60
+ temperature: Optional[float] = None,
61
+ speaker_id: Optional[str] = None,
62
+ voice_audio: Optional[AudioInput] = None,
63
+ controls: Optional[Union[Controls, dict]] = None,
64
+ style: Optional[str] = None,
65
+ seed: Optional[int] = None,
66
+ prefix: Optional[Union[Prefix, dict]] = None,
67
+ return_context: Optional[bool] = None,
68
+ include_timestamps: Optional[bool] = None,
69
+ audio_format: Optional[str] = None,
70
+ sample_rate: Optional[int] = None,
71
+ ) -> GenerateResponse:
72
+ payload = self._speech_payload(
73
+ GenerateRequest,
74
+ text=text,
75
+ voice_id=voice_id,
76
+ speaker_id=speaker_id,
77
+ voice_audio=voice_audio,
78
+ language=language,
79
+ format=format,
80
+ temperature=temperature,
81
+ controls=controls,
82
+ style=style,
83
+ seed=seed,
84
+ prefix=prefix,
85
+ return_context=return_context,
86
+ include_timestamps=include_timestamps,
87
+ audio_format=audio_format,
88
+ sample_rate=sample_rate,
89
+ )
90
+
91
+ response = self._http_client.post("/speech/generate", json=payload)
92
+ self._handle_response(response)
93
+ return self._speech_response(response)
94
+
95
+ def stream_speech(
96
+ self,
97
+ text: str,
98
+ voice_id: Optional[str] = None,
99
+ language: Optional[str] = None,
100
+ temperature: Optional[float] = None,
101
+ speaker_id: Optional[str] = None,
102
+ voice_audio: Optional[AudioInput] = None,
103
+ controls: Optional[Union[Controls, dict]] = None,
104
+ style: Optional[str] = None,
105
+ seed: Optional[int] = None,
106
+ prefix: Optional[Union[Prefix, dict]] = None,
107
+ ) -> Iterator[bytes]:
108
+ payload = self._speech_payload(
109
+ StreamRequest,
110
+ text=text,
111
+ voice_id=voice_id,
112
+ speaker_id=speaker_id,
113
+ voice_audio=voice_audio,
114
+ language=language,
115
+ temperature=temperature,
116
+ controls=controls,
117
+ style=style,
118
+ seed=seed,
119
+ prefix=prefix,
120
+ )
121
+
122
+ with self._http_client.stream("POST", "/speech/stream", json=payload) as response:
123
+ if response.is_error:
124
+ response.read()
125
+ self._handle_response(response)
126
+ yield from response.iter_bytes()
127
+
128
+ def close(self):
129
+ self._http_client.close()
130
+
131
+ def __enter__(self):
132
+ return self
133
+
134
+ def __exit__(self, *args):
135
+ self.close()
@@ -0,0 +1,11 @@
1
+ import platform
2
+ from .version import __version__
3
+
4
+ DEFAULT_BASE_URL = "https://api.tontaube.ai/v1"
5
+
6
+ DEFAULT_USER_AGENT = (
7
+ f"tontaube-python/{__version__} (Python/{platform.python_version()})"
8
+ )
9
+
10
+ DEFAULT_TIMEOUT = 600.0
11
+ VERSION_CHECK_TIMEOUT = 2.0
@@ -0,0 +1,16 @@
1
+ from typing import Optional
2
+
3
+ import httpx
4
+
5
+
6
+ class OutdatedSDKError(Exception):
7
+ """Raised when the API returns HTTP 426 Upgrade Required."""
8
+
9
+
10
+ class APIError(httpx.HTTPStatusError):
11
+ def __init__(self, response: httpx.Response, code: Optional[str], message: str):
12
+ prefix = f"{response.status_code} {code}" if code else str(response.status_code)
13
+ super().__init__(f"{prefix}: {message}", request=response.request, response=response)
14
+ self.status_code = response.status_code
15
+ self.code = code
16
+ self.message = message
@@ -0,0 +1,26 @@
1
+ import os
2
+ from pathlib import Path
3
+ from typing import BinaryIO, Optional, Tuple, Union
4
+ from ._constants import DEFAULT_USER_AGENT
5
+ from .version import __version__
6
+
7
+ AudioInput = Union[bytes, str, os.PathLike, BinaryIO]
8
+
9
+
10
+ def build_headers(api_key: Optional[str] = None) -> dict:
11
+ headers = {
12
+ "User-Agent": DEFAULT_USER_AGENT,
13
+ "X-SDK-Version": __version__,
14
+ }
15
+ if api_key is not None:
16
+ headers["X-API-Key"] = api_key
17
+ return headers
18
+
19
+
20
+ def read_audio(audio: AudioInput) -> Tuple[str, bytes]:
21
+ if isinstance(audio, (bytes, bytearray)):
22
+ return "audio", bytes(audio)
23
+ if isinstance(audio, (str, os.PathLike)):
24
+ path = Path(audio)
25
+ return path.name, path.read_bytes()
26
+ return Path(getattr(audio, "name", "audio")).name, audio.read()
@@ -0,0 +1,155 @@
1
+ from datetime import datetime
2
+ from typing import ClassVar, List, Literal, Optional, Union
3
+ from pydantic import BaseModel, ConfigDict, Field, model_validator
4
+
5
+ _MAX_TEXT_LENGTH = 30_000
6
+ _SINGLE_CALL_MAX_TEXT_LENGTH = 2_000
7
+ _STREAM_MAX_TEXT_LENGTH = 6_000
8
+ _ALLOWED_FORMATS = ["wav", "mp3", "opus"]
9
+
10
+ class Speaker(BaseModel):
11
+ id: str
12
+ name: str
13
+ voice_key: str
14
+ gender: Optional[str] = None
15
+ language_restrictions: Optional[List[str]] = None
16
+ voice_style: Optional[str] = None
17
+ preview_url: Optional[str] = None
18
+
19
+ class Voice(BaseModel):
20
+ id: str
21
+ name: str
22
+ type: str
23
+ languages: List[str] = []
24
+ preview_url: Optional[str] = None
25
+ language: Optional[str] = None
26
+ duration_seconds: Optional[float] = None
27
+ created_at: Optional[datetime] = None
28
+ model_version: Optional[str] = None
29
+ n_codebooks: Optional[int] = None
30
+ codec: Optional[str] = None
31
+ gender: Optional[str] = None
32
+ voice_style: Optional[str] = None
33
+
34
+ class Controls(BaseModel):
35
+ model_config = ConfigDict(extra="forbid")
36
+
37
+ rate: Optional[int] = Field(None, ge=0, le=4)
38
+ pause: Optional[int] = Field(None, ge=0, le=4)
39
+ pitch_range: Optional[int] = Field(None, ge=0, le=5)
40
+ pitch_level: Optional[int] = Field(None, ge=0, le=4)
41
+ legato: Optional[int] = Field(None, ge=0, le=2)
42
+
43
+ class ContextSlice(BaseModel):
44
+ model_config = ConfigDict(extra="forbid")
45
+
46
+ ref: str = Field(repr=False)
47
+ start: int = Field(ge=0)
48
+ end: int = Field(ge=1)
49
+
50
+ class Silence(BaseModel):
51
+ model_config = ConfigDict(extra="forbid")
52
+
53
+ silence: int = Field(ge=1, le=25)
54
+
55
+ class Prefix(BaseModel):
56
+ text: str
57
+ context: Optional[List[Union[ContextSlice, Silence]]] = None
58
+
59
+ class Word(BaseModel):
60
+ text: str
61
+ start: Optional[float] = None
62
+ end: Optional[float] = None
63
+ char_start: int
64
+ char_end: int
65
+ confidence: float
66
+
67
+ class Character(BaseModel):
68
+ char: str
69
+ index: int
70
+ start: Optional[float] = None
71
+ end: Optional[float] = None
72
+
73
+ class Timestamps(BaseModel):
74
+ text: str
75
+ words: List[Word] = []
76
+ characters: List[Character] = []
77
+
78
+ class GenerateRequest(BaseModel):
79
+ _single_call_max_text_length: ClassVar[int] = _SINGLE_CALL_MAX_TEXT_LENGTH
80
+
81
+ text: str
82
+ voice_id: Optional[str] = None
83
+ voice_audio_b64: Optional[str] = Field(None, repr=False)
84
+ speaker_id: Optional[str] = None
85
+ language: Optional[str] = None
86
+ format: Optional[str] = None
87
+ temperature: Optional[float] = None
88
+ controls: Optional[Controls] = None
89
+ style: Optional[Literal["audiobook", "conversational", "agentic"]] = None
90
+ seed: Optional[int] = Field(None, ge=0, le=2**32 - 1)
91
+ prefix: Optional[Prefix] = None
92
+ return_context: Optional[bool] = None
93
+ include_timestamps: Optional[bool] = None
94
+ audio_format: Optional[Literal["opus", "wav", "flac"]] = None
95
+ sample_rate: Optional[Literal[24000, 48000]] = None
96
+
97
+ @model_validator(mode="after")
98
+ def validate_request(self):
99
+ sources = [self.voice_id, self.voice_audio_b64, self.speaker_id]
100
+ if sum(source is not None for source in sources) != 1:
101
+ raise ValueError("Provide exactly one of voice_id, voice_audio or speaker_id")
102
+ if len(self.text) > _MAX_TEXT_LENGTH:
103
+ raise ValueError(f"Text length must be at most {_MAX_TEXT_LENGTH} characters")
104
+ if self.single_call and len(self.text) > self._single_call_max_text_length:
105
+ raise ValueError(
106
+ "With prefix, return_context, include_timestamps, seed or style, "
107
+ f"text length must be at most {_SINGLE_CALL_MAX_TEXT_LENGTH} characters"
108
+ )
109
+ if (self.audio_format or self.sample_rate) and not (self.return_context or self.include_timestamps):
110
+ raise ValueError("audio_format and sample_rate need return_context or include_timestamps")
111
+ if self.format and self.format.lower() not in _ALLOWED_FORMATS:
112
+ raise ValueError(f"Format must be one of: {', '.join(_ALLOWED_FORMATS)}")
113
+ if self.temperature is not None and (self.temperature < 0.5 or self.temperature > 2.0):
114
+ raise ValueError("Temperature must be between 0.5 and 2.0")
115
+ return self
116
+
117
+ @property
118
+ def single_call(self) -> bool:
119
+ return bool(
120
+ self.return_context or self.include_timestamps or self.prefix is not None
121
+ or self.seed is not None or self.style
122
+ )
123
+
124
+ class StreamRequest(GenerateRequest):
125
+ _single_call_max_text_length: ClassVar[int] = _STREAM_MAX_TEXT_LENGTH
126
+
127
+ @model_validator(mode="after")
128
+ def validate_stream(self):
129
+ if self.return_context or self.include_timestamps:
130
+ raise ValueError("return_context and include_timestamps are not available when streaming")
131
+ if len(self.text) > _STREAM_MAX_TEXT_LENGTH:
132
+ raise ValueError(f"Text length must be at most {_STREAM_MAX_TEXT_LENGTH} characters when streaming")
133
+ return self
134
+
135
+ class GenerateResponse(BaseModel):
136
+ model_config = ConfigDict(arbitrary_types_allowed=True)
137
+
138
+ content: bytes = Field(repr=False)
139
+ mime_type: Optional[str] = None
140
+ sample_rate: Optional[int] = None
141
+ audio_duration: Optional[float] = None
142
+ cost_usd: Optional[float] = None
143
+ balance_usd: Optional[float] = None
144
+ seed: Optional[int] = None
145
+ request_id: Optional[str] = None
146
+ context: Optional[str] = Field(None, repr=False)
147
+ n_frames: Optional[int] = None
148
+ frame_hz: Optional[float] = None
149
+ model_version: Optional[str] = None
150
+ timestamps: Optional[Timestamps] = None
151
+
152
+ def context_slice(self, start: int = 0, end: Optional[int] = None) -> ContextSlice:
153
+ if self.context is None:
154
+ raise ValueError("This response has no context, generate it with return_context=True")
155
+ return ContextSlice(ref=self.context, start=start, end=self.n_frames if end is None else end)
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: tontaube-client
3
+ Version: 0.3.0
4
+ Summary: Python SDK for the Tontaube text-to-speech API
5
+ License: MIT
6
+ Project-URL: Homepage, https://tontaube.ai
7
+ Project-URL: Repository, https://github.com/craitech/tontaube-sdk-python
8
+ Project-URL: API Reference, https://tontaube.ai/api-reference
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: httpx>=0.24
13
+ Requires-Dist: packaging>=21.0
14
+ Requires-Dist: pydantic>=2.0
15
+ Dynamic: license-file
16
+
17
+ # tontaube-client
18
+
19
+ Python SDK for the [Tontaube](https://tontaube.ai) text-to-speech API.
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ pip install tontaube-client
25
+ ```
26
+
27
+ ## Usage
28
+
29
+ ```python
30
+ import tontaube_client
31
+
32
+ with tontaube_client.Client(api_key="your-api-key") as client:
33
+ voices = client.list_voices()
34
+ response = client.generate_speech(
35
+ text="Tell me what we are building today, and I will get right to work.",
36
+ voice_id=voices[0].id,
37
+ )
38
+
39
+ with open("speech.m4a", "wb") as f:
40
+ f.write(response.content)
41
+ ```
42
+
43
+ Audio is returned as Opus in an MP4 container. Async client is also available via `tontaube_client.AsyncClient`.
44
+
45
+ ## Your own voices
46
+
47
+ ```python
48
+ voice = client.create_voice(name="My voice", audio="reference.wav", language="en")
49
+ response = client.generate_speech(text="Hello in my own voice.", voice_id=voice.id)
50
+ ```
51
+
52
+ `list_voices()` returns your voices and the Tontaube library voices, `get_voice()` and `delete_voice()` manage them.
53
+ For a one-off voice without storing it, pass the recording directly: `generate_speech(text, voice_audio="reference.wav")`.
54
+
55
+ ## Streaming
56
+
57
+ ```python
58
+ with open("speech.mp3", "wb") as f:
59
+ for chunk in client.stream_speech(text="Hello while it is still being generated.", voice_id=voice.id):
60
+ f.write(chunk)
61
+ ```
62
+
63
+ ## More options
64
+
65
+ - `style` (`audiobook`, `conversational`, `agentic`) and `controls=tontaube_client.Controls(rate=1, pause=3)` shape the delivery.
66
+ - `seed` makes a generation repeatable.
67
+ - `style`, `controls`, `seed` and `prefix` work for streaming too.
68
+ - `include_timestamps=True` returns when each word is spoken (English).
69
+ - `return_context=True` and `prefix` continue earlier speech seamlessly.
70
+
71
+ Errors from the API raise `tontaube_client.APIError` with `status_code`, `code` and `message`.
72
+
73
+ See the [examples/](examples/) folder for more usage patterns.
74
+
75
+ For full API reference see [tontaube.ai/api-reference](https://tontaube.ai/api-reference).
76
+
77
+ ## Coming from `tontaube` 0.2
78
+
79
+ Until version 0.2 this client was published as `tontaube` and imported as `import tontaube`. The PyPI name `tontaube` now belongs to the Tontaube inference server (version 1 and later). To move over:
80
+
81
+ ```bash
82
+ pip uninstall tontaube
83
+ pip install tontaube-client
84
+ ```
85
+
86
+ Then change the import to `import tontaube_client`, or keep your code as it is with one line:
87
+
88
+ ```python
89
+ import tontaube_client as tontaube
90
+ ```
91
+
92
+ To stay on the old package instead, pin `tontaube<1`.
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/tontaube_client/__init__.py
5
+ src/tontaube_client/_async_client.py
6
+ src/tontaube_client/_base_client.py
7
+ src/tontaube_client/_client.py
8
+ src/tontaube_client/_constants.py
9
+ src/tontaube_client/_exceptions.py
10
+ src/tontaube_client/core.py
11
+ src/tontaube_client/models.py
12
+ src/tontaube_client/version.py
13
+ src/tontaube_client.egg-info/PKG-INFO
14
+ src/tontaube_client.egg-info/SOURCES.txt
15
+ src/tontaube_client.egg-info/dependency_links.txt
16
+ src/tontaube_client.egg-info/requires.txt
17
+ src/tontaube_client.egg-info/top_level.txt
18
+ tests/test_client.py
@@ -0,0 +1,3 @@
1
+ httpx>=0.24
2
+ packaging>=21.0
3
+ pydantic>=2.0
@@ -0,0 +1 @@
1
+ tontaube_client
@@ -0,0 +1,238 @@
1
+ import asyncio
2
+ import base64
3
+ import json
4
+
5
+ import httpx
6
+ import pytest
7
+
8
+ import tontaube_client
9
+
10
+ VOICE_ID = "6f1c2b9e-0d3a-4c55-9a7e-1f2b3c4d5e6f"
11
+
12
+
13
+ def make_client(handler):
14
+ client = tontaube_client.Client(api_key="ttb_test")
15
+ client._http_client = httpx.Client(
16
+ base_url=client.base_url, headers=client._headers, transport=httpx.MockTransport(handler)
17
+ )
18
+ return client
19
+
20
+
21
+ def make_async_client(handler):
22
+ client = tontaube_client.AsyncClient(api_key="ttb_test")
23
+ client._http_client = httpx.AsyncClient(
24
+ base_url=client.base_url, headers=client._headers, transport=httpx.MockTransport(handler)
25
+ )
26
+ return client
27
+
28
+
29
+ def test_generate_binary_keeps_old_call_style():
30
+ seen = {}
31
+
32
+ def handler(request):
33
+ seen["body"] = json.loads(request.content)
34
+ seen["headers"] = request.headers
35
+ return httpx.Response(
36
+ 200,
37
+ content=b"mp4",
38
+ headers={"content-type": "audio/mp4; codecs=opus", "x-cost-usd": "0.000120", "x-balance-usd": "4.99"},
39
+ )
40
+
41
+ with make_client(handler) as client:
42
+ response = client.generate_speech("Hello", VOICE_ID, "en", None, 0.8)
43
+
44
+ assert seen["body"] == {"text": "Hello", "voice_id": VOICE_ID, "language": "en", "temperature": 0.8}
45
+ assert seen["headers"]["x-api-key"] == "ttb_test"
46
+ assert seen["headers"]["content-type"] == "application/json"
47
+ assert response.content == b"mp4"
48
+ assert response.cost_usd == 0.00012
49
+ assert response.balance_usd == 4.99
50
+
51
+
52
+ def test_generate_json_with_context_and_timestamps():
53
+ def handler(request):
54
+ body = json.loads(request.content)
55
+ assert body["return_context"] is True and body["include_timestamps"] is True
56
+ assert body["controls"] == {"rate": 1}
57
+ assert body["prefix"] == {"text": "Before.", "context": [{"ref": "ttc1.a", "start": 0, "end": 10}, {"silence": 3}]}
58
+ return httpx.Response(
59
+ 200,
60
+ json={
61
+ "audio_b64": base64.b64encode(b"RIFF").decode(),
62
+ "mime_type": "audio/wav",
63
+ "sample_rate": 24000,
64
+ "duration": 0.8,
65
+ "seed": 7,
66
+ "context": "ttc1.b",
67
+ "n_frames": 10,
68
+ "frame_hz": 12.5,
69
+ "model_version": "TontaubeV1.1",
70
+ "cost_usd": "0.000010",
71
+ "balance_usd": "4.000000",
72
+ "request_id": "abc",
73
+ "timestamps": {
74
+ "text": "Hi.",
75
+ "words": [{"text": "Hi.", "start": 0.1, "end": None, "char_start": 0, "char_end": 3, "confidence": 0.9}],
76
+ "characters": [{"char": "H", "index": 0, "start": 0.1, "end": 0.2}],
77
+ },
78
+ },
79
+ headers={"x-seed": "7", "x-request-id": "abc"},
80
+ )
81
+
82
+ with make_client(handler) as client:
83
+ response = client.generate_speech(
84
+ "Hi.",
85
+ voice_id=VOICE_ID,
86
+ controls={"rate": 1},
87
+ prefix=tontaube_client.Prefix(text="Before.", context=[{"ref": "ttc1.a", "start": 0, "end": 10}, tontaube_client.Silence(silence=3)]),
88
+ return_context=True,
89
+ include_timestamps=True,
90
+ )
91
+
92
+ assert response.content == b"RIFF"
93
+ assert response.mime_type == "audio/wav"
94
+ assert response.audio_duration == 0.8
95
+ assert response.seed == 7 and response.n_frames == 10
96
+ assert response.timestamps.words[0].end is None
97
+ assert response.context_slice(2) == tontaube_client.ContextSlice(ref="ttc1.b", start=2, end=10)
98
+
99
+
100
+ def test_voice_audio_is_sent_as_base64(tmp_path):
101
+ path = tmp_path / "reference.wav"
102
+ path.write_bytes(b"voice")
103
+
104
+ def handler(request):
105
+ body = json.loads(request.content)
106
+ assert body["voice_audio_b64"] == base64.b64encode(b"voice").decode()
107
+ assert "voice_id" not in body
108
+ return httpx.Response(200, content=b"mp4")
109
+
110
+ with make_client(handler) as client:
111
+ assert client.generate_speech("Hi", voice_audio=path).content == b"mp4"
112
+
113
+
114
+ def test_request_validation():
115
+ with pytest.raises(ValueError):
116
+ tontaube_client.GenerateRequest(text="Hi")
117
+ with pytest.raises(ValueError):
118
+ tontaube_client.GenerateRequest(text="Hi", voice_id=VOICE_ID, speaker_id=VOICE_ID)
119
+ with pytest.raises(ValueError):
120
+ tontaube_client.GenerateRequest(text="x" * 2001, voice_id=VOICE_ID, seed=1)
121
+ with pytest.raises(ValueError):
122
+ tontaube_client.GenerateRequest(text="Hi", voice_id=VOICE_ID, audio_format="wav")
123
+ with pytest.raises(ValueError):
124
+ tontaube_client.GenerateRequest(text="Hi", voice_id=VOICE_ID, controls={"speed": 1})
125
+ with pytest.raises(ValueError):
126
+ tontaube_client.StreamRequest(text="x" * 6001, voice_id=VOICE_ID)
127
+ with pytest.raises(ValueError):
128
+ tontaube_client.StreamRequest(text="Hi", voice_id=VOICE_ID, return_context=True)
129
+ with pytest.raises(ValueError):
130
+ tontaube_client.StreamRequest(text="Hi", voice_id=VOICE_ID, include_timestamps=True)
131
+ stream = tontaube_client.StreamRequest(
132
+ text="Hi", voice_id=VOICE_ID, style="agentic", seed=3, prefix={"text": "Before.", "context": [{"silence": 2}]}
133
+ )
134
+ assert stream.model_dump(exclude_none=True)["style"] == "agentic"
135
+ assert tontaube_client.GenerateRequest(text="x" * 2001, voice_id=VOICE_ID).text
136
+
137
+
138
+ def test_voices_crud(tmp_path):
139
+ reference = tmp_path / "me.wav"
140
+ reference.write_bytes(b"wav")
141
+ custom = {
142
+ "id": VOICE_ID, "name": "Me", "type": "custom", "languages": ["en"], "language": "en",
143
+ "duration_seconds": 12.0, "created_at": "2026-11-17T10:00:00Z", "model_version": "TontaubeV1.1",
144
+ "n_codebooks": 8, "codec": "dualcodec_12hz_v1",
145
+ }
146
+ library = {"id": "lib", "name": "Narrator", "type": "library", "languages": [], "gender": "female", "voice_style": "Narration"}
147
+
148
+ def handler(request):
149
+ if request.method == "POST":
150
+ content_type = request.headers["content-type"]
151
+ assert content_type.startswith("multipart/form-data")
152
+ assert b'name="name"' in request.content and b"Me" in request.content
153
+ assert b'filename="me.wav"' in request.content
154
+ return httpx.Response(201, json=custom)
155
+ if request.method == "DELETE":
156
+ return httpx.Response(204)
157
+ if request.url.path.endswith("/voices"):
158
+ assert request.url.params.get("type") == "library"
159
+ return httpx.Response(200, json=[library])
160
+ return httpx.Response(200, json=custom)
161
+
162
+ with make_client(handler) as client:
163
+ created = client.create_voice("Me", reference, language="en")
164
+ assert created.type == "custom" and created.n_codebooks == 8
165
+ assert client.list_voices(type="library")[0].voice_style == "Narration"
166
+ assert client.get_voice(VOICE_ID).name == "Me"
167
+ assert client.delete_voice(VOICE_ID) is None
168
+
169
+
170
+ def test_api_error_carries_code():
171
+ def handler(request):
172
+ return httpx.Response(404, json={"detail": {"error": "voice_not_found", "message": "Voice not found"}})
173
+
174
+ with make_client(handler) as client:
175
+ with pytest.raises(tontaube_client.APIError) as error:
176
+ client.get_voice(VOICE_ID)
177
+
178
+ assert error.value.status_code == 404
179
+ assert error.value.code == "voice_not_found"
180
+ assert isinstance(error.value, httpx.HTTPStatusError)
181
+
182
+
183
+ def test_validation_error_message():
184
+ def handler(request):
185
+ return httpx.Response(422, json={"detail": [{"loc": ["body", "text"], "msg": "Field required"}]})
186
+
187
+ with make_client(handler) as client:
188
+ with pytest.raises(tontaube_client.APIError) as error:
189
+ client.generate_speech("Hi", VOICE_ID)
190
+
191
+ assert error.value.code == "invalid_request"
192
+ assert "Field required" in error.value.message
193
+
194
+
195
+ def test_outdated_sdk():
196
+ def handler(request):
197
+ return httpx.Response(426, json={"message": "Too old."})
198
+
199
+ with make_client(handler) as client:
200
+ with pytest.raises(tontaube_client.OutdatedSDKError):
201
+ client.list_voices()
202
+
203
+
204
+ def test_stream_yields_chunks_and_raises_errors():
205
+ def handler(request):
206
+ body = json.loads(request.content)
207
+ if body["text"] == "fail":
208
+ return httpx.Response(402, json={"detail": {"error": "insufficient_balance", "message": "No balance"}})
209
+ return httpx.Response(200, content=b"abcdef", headers={"content-type": "audio/mpeg"})
210
+
211
+ with make_client(handler) as client:
212
+ assert b"".join(client.stream_speech("Hi", VOICE_ID)) == b"abcdef"
213
+ assert b"".join(client.stream_speech("x" * 3000, VOICE_ID, style="conversational", seed=1)) == b"abcdef"
214
+ with pytest.raises(ValueError):
215
+ list(client.stream_speech("x" * 6001, VOICE_ID, style="conversational"))
216
+ with pytest.raises(tontaube_client.APIError) as error:
217
+ list(client.stream_speech("fail", VOICE_ID))
218
+ assert error.value.code == "insufficient_balance"
219
+ with pytest.raises(ValueError):
220
+ list(client.stream_speech("x" * 6001, VOICE_ID))
221
+
222
+
223
+ def test_async_client():
224
+ def handler(request):
225
+ if request.url.path.endswith("/speech/stream"):
226
+ return httpx.Response(200, content=b"mp3")
227
+ if request.url.path.endswith("/voices"):
228
+ return httpx.Response(200, json=[{"id": "lib", "name": "Narrator", "type": "library"}])
229
+ return httpx.Response(200, content=b"mp4")
230
+
231
+ async def run():
232
+ async with make_async_client(handler) as client:
233
+ voices = await client.list_voices()
234
+ response = await client.generate_speech("Hi", voices[0].id)
235
+ chunks = [chunk async for chunk in client.stream_speech("Hi", voices[0].id)]
236
+ return response.content, b"".join(chunks)
237
+
238
+ assert asyncio.run(run()) == (b"mp4", b"mp3")