cartesia 1.1.0.dev0__py3-none-any.whl

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.
cartesia/_websocket.py ADDED
@@ -0,0 +1,355 @@
1
+ import base64
2
+ import json
3
+ import uuid
4
+ from collections import defaultdict
5
+ from typing import Any, Dict, Generator, Iterator, List, Optional, Set, Union
6
+
7
+ try:
8
+ from websockets.sync.client import connect
9
+
10
+ IS_WEBSOCKET_SYNC_AVAILABLE = True
11
+ except ImportError:
12
+ IS_WEBSOCKET_SYNC_AVAILABLE = False
13
+
14
+ from iterators import TimeoutIterator
15
+
16
+ from cartesia._types import EventType, OutputFormat, VoiceControls
17
+ from cartesia.utils.tts import _construct_tts_request
18
+
19
+
20
+ class _TTSContext:
21
+ """Manage a single context over a WebSocket.
22
+
23
+ This class can be used to stream inputs, as they become available, to a specific `context_id`. See README for usage.
24
+
25
+ See :class:`_AsyncTTSContext` for asynchronous use cases.
26
+
27
+ Each TTSContext will close automatically when a done message is received for that context. It also closes if there is an error.
28
+ """
29
+
30
+ def __init__(self, context_id: str, websocket: "_WebSocket"):
31
+ self._context_id = context_id
32
+ self._websocket = websocket
33
+ self._error = None
34
+
35
+ def __del__(self):
36
+ self._close()
37
+
38
+ @property
39
+ def context_id(self) -> str:
40
+ return self._context_id
41
+
42
+ def send(
43
+ self,
44
+ model_id: str,
45
+ transcript: Iterator[str],
46
+ output_format: OutputFormat,
47
+ voice_id: Optional[str] = None,
48
+ voice_embedding: Optional[List[float]] = None,
49
+ context_id: Optional[str] = None,
50
+ duration: Optional[int] = None,
51
+ language: Optional[str] = None,
52
+ add_timestamps: bool = False,
53
+ _experimental_voice_controls: Optional[VoiceControls] = None,
54
+ ) -> Generator[bytes, None, None]:
55
+ """Send audio generation requests to the WebSocket and yield responses.
56
+
57
+ Args:
58
+ model_id: The ID of the model to use for generating audio.
59
+ transcript: Iterator over text chunks with <1s latency.
60
+ output_format: A dictionary containing the details of the output format.
61
+ voice_id: The ID of the voice to use for generating audio.
62
+ voice_embedding: The embedding of the voice to use for generating audio.
63
+ context_id: The context ID to use for the request. If not specified, a random context ID will be generated.
64
+ duration: The duration of the audio in seconds.
65
+ language: The language code for the audio request. This can only be used with `model_id = sonic-multilingual`
66
+ add_timestamps: Whether to return word-level timestamps.
67
+ _experimental_voice_controls: Experimental voice controls for controlling speed and emotion.
68
+ Note: This is an experimental feature and may change rapidly in future releases.
69
+
70
+ Yields:
71
+ Dictionary containing the following key(s):
72
+ - audio: The audio as bytes.
73
+ - context_id: The context ID for the request.
74
+
75
+ Raises:
76
+ ValueError: If provided context_id doesn't match the current context.
77
+ RuntimeError: If there's an error generating audio.
78
+ """
79
+ if context_id is not None and context_id != self._context_id:
80
+ raise ValueError("Context ID does not match the context ID of the current context.")
81
+
82
+ self._websocket.connect()
83
+
84
+ # Create the initial request body
85
+ request_body = _construct_tts_request(
86
+ model_id=model_id,
87
+ transcript=transcript,
88
+ output_format=output_format,
89
+ voice_id=voice_id,
90
+ voice_embedding=voice_embedding,
91
+ duration=duration,
92
+ language=language,
93
+ context_id=self._context_id,
94
+ add_timestamps=add_timestamps,
95
+ _experimental_voice_controls=_experimental_voice_controls,
96
+ )
97
+
98
+ try:
99
+ # Create an iterator with a timeout to get text chunks
100
+ text_iterator = TimeoutIterator(
101
+ transcript, timeout=0.001
102
+ ) # 1ms timeout for nearly non-blocking receive
103
+ next_chunk = next(text_iterator, None)
104
+
105
+ while True:
106
+ # Send the next text chunk to the WebSocket if available
107
+ if next_chunk is not None and next_chunk != text_iterator.get_sentinel():
108
+ request_body["transcript"] = next_chunk
109
+ request_body["continue"] = True
110
+ self._websocket.websocket.send(json.dumps(request_body))
111
+ next_chunk = next(text_iterator, None)
112
+
113
+ try:
114
+ # Receive responses from the WebSocket with a small timeout
115
+ response = json.loads(
116
+ self._websocket.websocket.recv(timeout=0.001)
117
+ ) # 1ms timeout for nearly non-blocking receive
118
+ if response["context_id"] != self._context_id:
119
+ pass
120
+ if "error" in response:
121
+ raise RuntimeError(f"Error generating audio:\n{response['error']}")
122
+ if response["done"]:
123
+ break
124
+ if response["data"]:
125
+ yield self._websocket._convert_response(
126
+ response=response, include_context_id=True
127
+ )
128
+ except TimeoutError:
129
+ pass
130
+
131
+ # Continuously receive from WebSocket until the next text chunk is available
132
+ while next_chunk == text_iterator.get_sentinel():
133
+ try:
134
+ response = json.loads(self._websocket.websocket.recv(timeout=0.001))
135
+ if response["context_id"] != self._context_id:
136
+ continue
137
+ if "error" in response:
138
+ raise RuntimeError(f"Error generating audio:\n{response['error']}")
139
+ if response["done"]:
140
+ break
141
+ if response["data"]:
142
+ yield self._websocket._convert_response(
143
+ response=response, include_context_id=True
144
+ )
145
+ except TimeoutError:
146
+ pass
147
+ next_chunk = next(text_iterator, None)
148
+
149
+ # Send final message if all input text chunks are exhausted
150
+ if next_chunk is None:
151
+ request_body["transcript"] = ""
152
+ request_body["continue"] = False
153
+ self._websocket.websocket.send(json.dumps(request_body))
154
+ break
155
+
156
+ # Receive remaining messages from the WebSocket until "done" is received
157
+ while True:
158
+ response = json.loads(self._websocket.websocket.recv())
159
+ if response["context_id"] != self._context_id:
160
+ continue
161
+ if "error" in response:
162
+ raise RuntimeError(f"Error generating audio:\n{response['error']}")
163
+ if response["done"]:
164
+ break
165
+ yield self._websocket._convert_response(response=response, include_context_id=True)
166
+
167
+ except Exception as e:
168
+ self._websocket.close()
169
+ raise RuntimeError(f"Failed to generate audio. {e}")
170
+
171
+ def _close(self):
172
+ """Closes the context. Automatically called when a done message is received for this context."""
173
+ self._websocket._remove_context(self._context_id)
174
+
175
+ def is_closed(self):
176
+ """Check if the context is closed or not. Returns True if closed."""
177
+ return self._context_id not in self._websocket._contexts
178
+
179
+
180
+ class _WebSocket:
181
+ """This class contains methods to generate audio using WebSocket. Ideal for low-latency audio generation.
182
+
183
+ Usage:
184
+ >>> ws = client.tts.websocket()
185
+ >>> for audio_chunk in ws.send(
186
+ ... model_id="sonic-english", transcript="Hello world!", voice_embedding=embedding,
187
+ ... output_format={"container": "raw", "encoding": "pcm_f32le", "sample_rate": 44100},
188
+ ... context_id=context_id, stream=True
189
+ ... ):
190
+ ... audio = audio_chunk["audio"]
191
+ """
192
+
193
+ def __init__(
194
+ self,
195
+ ws_url: str,
196
+ api_key: str,
197
+ cartesia_version: str,
198
+ ):
199
+ self.ws_url = ws_url
200
+ self.api_key = api_key
201
+ self.cartesia_version = cartesia_version
202
+ self.websocket = None
203
+ self._contexts: Set[str] = set()
204
+
205
+ def __del__(self):
206
+ try:
207
+ self.close()
208
+ except Exception as e:
209
+ raise RuntimeError("Failed to close WebSocket: ", e)
210
+
211
+ def connect(self):
212
+ """This method connects to the WebSocket if it is not already connected.
213
+
214
+ Raises:
215
+ RuntimeError: If the connection to the WebSocket fails.
216
+ """
217
+ if not IS_WEBSOCKET_SYNC_AVAILABLE:
218
+ raise ImportError(
219
+ "The synchronous WebSocket client is not available. Please ensure that you have 'websockets>=12.0' or compatible version installed."
220
+ )
221
+ if self.websocket is None or self._is_websocket_closed():
222
+ route = "tts/websocket"
223
+ try:
224
+ self.websocket = connect(
225
+ f"{self.ws_url}/{route}?api_key={self.api_key}&cartesia_version={self.cartesia_version}"
226
+ )
227
+ except Exception as e:
228
+ raise RuntimeError(f"Failed to connect to WebSocket. {e}")
229
+
230
+ def _is_websocket_closed(self):
231
+ return self.websocket.socket.fileno() == -1
232
+
233
+ def close(self):
234
+ """This method closes the WebSocket connection. *Highly* recommended to call this method when done using the WebSocket."""
235
+ if self.websocket and not self._is_websocket_closed():
236
+ self.websocket.close()
237
+
238
+ if self._contexts:
239
+ self._contexts.clear()
240
+
241
+ def _convert_response(
242
+ self, response: Dict[str, any], include_context_id: bool
243
+ ) -> Dict[str, Any]:
244
+ out = {}
245
+ if response["type"] == EventType.AUDIO:
246
+ out["audio"] = base64.b64decode(response["data"])
247
+ elif response["type"] == EventType.TIMESTAMPS:
248
+ out["word_timestamps"] = response["word_timestamps"]
249
+
250
+ if include_context_id:
251
+ out["context_id"] = response["context_id"]
252
+
253
+ return out
254
+
255
+ def send(
256
+ self,
257
+ model_id: str,
258
+ transcript: str,
259
+ output_format: dict,
260
+ voice_id: Optional[str] = None,
261
+ voice_embedding: Optional[List[float]] = None,
262
+ context_id: Optional[str] = None,
263
+ duration: Optional[int] = None,
264
+ language: Optional[str] = None,
265
+ stream: bool = True,
266
+ add_timestamps: bool = False,
267
+ _experimental_voice_controls: Optional[VoiceControls] = None,
268
+ ) -> Union[bytes, Generator[bytes, None, None]]:
269
+ """Send a request to the WebSocket to generate audio.
270
+
271
+ Args:
272
+ model_id: The ID of the model to use for generating audio.
273
+ transcript: The text to convert to speech.
274
+ output_format: A dictionary containing the details of the output format.
275
+ voice_id: The ID of the voice to use for generating audio.
276
+ voice_embedding: The embedding of the voice to use for generating audio.
277
+ context_id: The context ID to use for the request. If not specified, a random context ID will be generated.
278
+ duration: The duration of the audio in seconds.
279
+ language: The language code for the audio request. This can only be used with `model_id = sonic-multilingual`
280
+ stream: Whether to stream the audio or not.
281
+ add_timestamps: Whether to return word-level timestamps.
282
+ _experimental_voice_controls: Experimental voice controls for controlling speed and emotion.
283
+ Note: This is an experimental feature and may change rapidly in future releases.
284
+
285
+ Returns:
286
+ If `stream` is True, the method returns a generator that yields chunks. Each chunk is a dictionary.
287
+ If `stream` is False, the method returns a dictionary.
288
+ Both the generator and the dictionary contain the following key(s):
289
+ - audio: The audio as bytes.
290
+ - context_id: The context ID for the request.
291
+ """
292
+ self.connect()
293
+
294
+ if context_id is None:
295
+ context_id = str(uuid.uuid4())
296
+
297
+ request_body = _construct_tts_request(
298
+ model_id=model_id,
299
+ transcript=transcript,
300
+ output_format=output_format,
301
+ voice_id=voice_id,
302
+ voice_embedding=voice_embedding,
303
+ context_id=context_id,
304
+ duration=duration,
305
+ language=language,
306
+ add_timestamps=add_timestamps,
307
+ _experimental_voice_controls=_experimental_voice_controls,
308
+ )
309
+
310
+ generator = self._websocket_generator(request_body)
311
+
312
+ if stream:
313
+ return generator
314
+
315
+ chunks = []
316
+ word_timestamps = defaultdict(list)
317
+ for chunk in generator:
318
+ if "audio" in chunk:
319
+ chunks.append(chunk["audio"])
320
+ if add_timestamps and "word_timestamps" in chunk:
321
+ for k, v in chunk["word_timestamps"].items():
322
+ word_timestamps[k].extend(v)
323
+ out = {"audio": b"".join(chunks), "context_id": context_id}
324
+ if add_timestamps:
325
+ out["word_timestamps"] = word_timestamps
326
+ return out
327
+
328
+ def _websocket_generator(self, request_body: Dict[str, Any]):
329
+ self.websocket.send(json.dumps(request_body))
330
+
331
+ try:
332
+ while True:
333
+ response = json.loads(self.websocket.recv())
334
+ if "error" in response:
335
+ raise RuntimeError(f"Error generating audio:\n{response['error']}")
336
+ if response["done"]:
337
+ break
338
+ yield self._convert_response(response=response, include_context_id=True)
339
+ except Exception as e:
340
+ # Close the websocket connection if an error occurs.
341
+ self.close()
342
+ raise RuntimeError(f"Failed to generate audio. {response}") from e
343
+
344
+ def _remove_context(self, context_id: str):
345
+ if context_id in self._contexts:
346
+ self._contexts.remove(context_id)
347
+
348
+ def context(self, context_id: Optional[str] = None) -> _TTSContext:
349
+ if context_id in self._contexts:
350
+ raise ValueError(f"Context for context ID {context_id} already exists.")
351
+ if context_id is None:
352
+ context_id = str(uuid.uuid4())
353
+ if context_id not in self._contexts:
354
+ self._contexts.add(context_id)
355
+ return _TTSContext(context_id, self)
@@ -0,0 +1,82 @@
1
+ import asyncio
2
+ from types import TracebackType
3
+ from typing import Optional, Union
4
+
5
+ import aiohttp
6
+
7
+ from cartesia._constants import DEFAULT_NUM_CONNECTIONS, DEFAULT_TIMEOUT
8
+ from cartesia.async_tts import AsyncTTS
9
+ from cartesia.client import Cartesia
10
+
11
+
12
+ class AsyncCartesia(Cartesia):
13
+ """The asynchronous version of the Cartesia client."""
14
+
15
+ def __init__(
16
+ self,
17
+ *,
18
+ api_key: Optional[str] = None,
19
+ base_url: Optional[str] = None,
20
+ timeout: float = DEFAULT_TIMEOUT,
21
+ max_num_connections: int = DEFAULT_NUM_CONNECTIONS,
22
+ ):
23
+ """
24
+ Args:
25
+ api_key: See :class:`Cartesia`.
26
+ base_url: See :class:`Cartesia`.
27
+ timeout: See :class:`Cartesia`.
28
+ max_num_connections: The maximum number of concurrent connections to use for the client.
29
+ This is used to limit the number of connections that can be made to the server.
30
+ """
31
+ self._session = None
32
+ self._loop = None
33
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout)
34
+ self.max_num_connections = max_num_connections
35
+ self.tts = AsyncTTS(
36
+ api_key=self.api_key,
37
+ base_url=self._base_url,
38
+ timeout=self.timeout,
39
+ get_session=self._get_session,
40
+ )
41
+
42
+ async def _get_session(self):
43
+ current_loop = asyncio.get_event_loop()
44
+ if self._loop is not current_loop:
45
+ # If the loop has changed, close the session and create a new one.
46
+ await self.close()
47
+ if self._session is None or self._session.closed:
48
+ timeout = aiohttp.ClientTimeout(total=self.timeout)
49
+ connector = aiohttp.TCPConnector(limit=self.max_num_connections)
50
+ self._session = aiohttp.ClientSession(timeout=timeout, connector=connector)
51
+ self._loop = current_loop
52
+ return self._session
53
+
54
+ async def close(self):
55
+ """This method closes the session.
56
+
57
+ It is *strongly* recommended to call this method when you are done using the client.
58
+ """
59
+ if self._session is not None and not self._session.closed:
60
+ await self._session.close()
61
+
62
+ def __del__(self):
63
+ try:
64
+ loop = asyncio.get_running_loop()
65
+ except RuntimeError:
66
+ loop = None
67
+
68
+ if loop is None:
69
+ asyncio.run(self.close())
70
+ elif loop.is_running():
71
+ loop.create_task(self.close())
72
+
73
+ async def __aenter__(self):
74
+ return self
75
+
76
+ async def __aexit__(
77
+ self,
78
+ exc_type: Union[type, None],
79
+ exc: Union[BaseException, None],
80
+ exc_tb: Union[TracebackType, None],
81
+ ):
82
+ await self.close()
cartesia/async_tts.py ADDED
@@ -0,0 +1,63 @@
1
+ from typing import Iterator, List, Optional
2
+
3
+ import httpx
4
+ from cartesia._async_sse import _AsyncSSE
5
+ from cartesia._async_websocket import _AsyncWebSocket
6
+ from cartesia._types import OutputFormat, VoiceControls
7
+ from cartesia.tts import TTS
8
+ from cartesia.utils.tts import _construct_tts_request
9
+
10
+
11
+ class AsyncTTS(TTS):
12
+ def __init__(self, api_key, base_url, timeout, get_session):
13
+ super().__init__(api_key, base_url, timeout)
14
+ self._get_session = get_session
15
+ self._sse_class = _AsyncSSE(self._http_url(), self.headers, self.timeout, get_session)
16
+ self.sse = self._sse_class.send
17
+
18
+ async def websocket(self) -> _AsyncWebSocket:
19
+ ws = _AsyncWebSocket(
20
+ self._ws_url(),
21
+ self.api_key,
22
+ self.cartesia_version,
23
+ self.timeout,
24
+ self._get_session,
25
+ )
26
+ await ws.connect()
27
+ return ws
28
+
29
+ async def bytes(
30
+ self,
31
+ *,
32
+ model_id: str,
33
+ transcript: str,
34
+ output_format: OutputFormat,
35
+ voice_id: Optional[str] = None,
36
+ voice_embedding: Optional[List[float]] = None,
37
+ duration: Optional[int] = None,
38
+ language: Optional[str] = None,
39
+ _experimental_voice_controls: Optional[VoiceControls] = None,
40
+ ) -> bytes:
41
+ request_body = _construct_tts_request(
42
+ model_id=model_id,
43
+ transcript=transcript,
44
+ output_format=output_format,
45
+ voice_id=voice_id,
46
+ voice_embedding=voice_embedding,
47
+ duration=duration,
48
+ language=language,
49
+ _experimental_voice_controls=_experimental_voice_controls,
50
+ )
51
+
52
+ async with httpx.AsyncClient() as client:
53
+ response = await client.post(
54
+ f"{self._http_url()}/tts/bytes",
55
+ headers=self.headers,
56
+ timeout=self.timeout,
57
+ json=request_body,
58
+ )
59
+
60
+ if not response.is_success:
61
+ raise ValueError(f"Failed to generate audio. Error: {response.text}")
62
+
63
+ return response.content
cartesia/client.py ADDED
@@ -0,0 +1,69 @@
1
+ import os
2
+ from types import TracebackType
3
+ from typing import Optional, Union
4
+
5
+ from cartesia._constants import DEFAULT_BASE_URL, DEFAULT_TIMEOUT
6
+ from cartesia.tts import TTS
7
+ from cartesia.voices import Voices
8
+
9
+
10
+ class BaseClient:
11
+ def __init__(
12
+ self,
13
+ *,
14
+ api_key: Optional[str] = None,
15
+ base_url: Optional[str] = None,
16
+ timeout: float = DEFAULT_TIMEOUT,
17
+ ):
18
+ """Constructor for the BaseClient. Used by the Cartesia and AsyncCartesia clients."""
19
+ self.api_key = api_key or os.environ.get("CARTESIA_API_KEY")
20
+ self._base_url = base_url or os.environ.get("CARTESIA_BASE_URL", DEFAULT_BASE_URL)
21
+ self.timeout = timeout
22
+
23
+ @property
24
+ def base_url(self):
25
+ return self._base_url
26
+
27
+
28
+ class Cartesia(BaseClient):
29
+ """
30
+ The client for Cartesia's text-to-speech library.
31
+
32
+ This client contains methods to interact with the Cartesia text-to-speech API.
33
+ The client can be used to manage your voice library and generate speech from text.
34
+
35
+ The client supports generating audio using both Server-Sent Events and WebSocket for lower latency.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ *,
41
+ api_key: Optional[str] = None,
42
+ base_url: Optional[str] = None,
43
+ timeout: float = DEFAULT_TIMEOUT,
44
+ ):
45
+ """Constructor for the Cartesia client.
46
+
47
+ Args:
48
+ api_key: The API key to use for authorization.
49
+ If not specified, the API key will be read from the environment variable
50
+ `CARTESIA_API_KEY`.
51
+ base_url: The base URL for the Cartesia API.
52
+ If not specified, the base URL will be read from the enviroment variable
53
+ `CARTESIA_BASE_URL`. Defaults to `api.cartesia.ai`.
54
+ timeout: The timeout for HTTP and WebSocket requests in seconds. Defaults to 30 seconds.
55
+ """
56
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout)
57
+ self.voices = Voices(api_key=self.api_key, base_url=self._base_url, timeout=self.timeout)
58
+ self.tts = TTS(api_key=self.api_key, base_url=self._base_url, timeout=self.timeout)
59
+
60
+ def __enter__(self):
61
+ return self
62
+
63
+ def __exit__(
64
+ self,
65
+ exc_type: Union[type, None],
66
+ exc: Union[BaseException, None],
67
+ exc_tb: Union[TracebackType, None],
68
+ ):
69
+ pass
cartesia/resource.py ADDED
@@ -0,0 +1,44 @@
1
+ from cartesia._constants import DEFAULT_CARTESIA_VERSION
2
+
3
+
4
+ class Resource:
5
+ def __init__(
6
+ self,
7
+ api_key: str,
8
+ base_url: str,
9
+ timeout: float,
10
+ ):
11
+ """Constructor for the Resource class. Used by the Voices and TTS classes."""
12
+ self.api_key = api_key
13
+ self.timeout = timeout
14
+ self._base_url = base_url
15
+ self.cartesia_version = DEFAULT_CARTESIA_VERSION
16
+ self.headers = {
17
+ "X-API-Key": self.api_key,
18
+ "Cartesia-Version": self.cartesia_version,
19
+ "Content-Type": "application/json",
20
+ }
21
+
22
+ @property
23
+ def base_url(self):
24
+ return self._base_url
25
+
26
+ def _http_url(self):
27
+ """Returns the HTTP URL for the Cartesia API.
28
+ If the base URL is localhost, the URL will start with 'http'. Otherwise, it will start with 'https'.
29
+ """
30
+ if self._base_url.startswith("http://") or self._base_url.startswith("https://"):
31
+ return self._base_url
32
+ else:
33
+ prefix = "http" if "localhost" in self._base_url else "https"
34
+ return f"{prefix}://{self._base_url}"
35
+
36
+ def _ws_url(self):
37
+ """Returns the WebSocket URL for the Cartesia API.
38
+ If the base URL is localhost, the URL will start with 'ws'. Otherwise, it will start with 'wss'.
39
+ """
40
+ if self._base_url.startswith("ws://") or self._base_url.startswith("wss://"):
41
+ return self._base_url
42
+ else:
43
+ prefix = "ws" if "localhost" in self._base_url else "wss"
44
+ return f"{prefix}://{self._base_url}"