cartesia 0.1.1__py2.py3-none-any.whl → 1.0.1__py2.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/client.py ADDED
@@ -0,0 +1,889 @@
1
+ import asyncio
2
+ import base64
3
+ import json
4
+ import os
5
+ import uuid
6
+ from types import TracebackType
7
+ from typing import Any, AsyncGenerator, Dict, Generator, List, Optional, Tuple, Union, Callable
8
+
9
+ import aiohttp
10
+ import httpx
11
+ import logging
12
+ import requests
13
+ from websockets.sync.client import connect
14
+
15
+ from cartesia.utils.retry import retry_on_connection_error, retry_on_connection_error_async
16
+ from cartesia.utils.deprecated import deprecated
17
+ from cartesia._types import (
18
+ OutputFormat,
19
+ OutputFormatMapping,
20
+ DeprecatedOutputFormatMapping,
21
+ VoiceMetadata,
22
+ )
23
+
24
+
25
+ DEFAULT_MODEL_ID = "sonic-english" # latest default model
26
+ MULTILINGUAL_MODEL_ID = "sonic-multilingual" # latest multilingual model
27
+ DEFAULT_BASE_URL = "api.cartesia.ai"
28
+ DEFAULT_CARTESIA_VERSION = "2024-06-10" # latest version
29
+ DEFAULT_TIMEOUT = 30 # seconds
30
+ DEFAULT_NUM_CONNECTIONS = 10 # connections per client
31
+
32
+ BACKOFF_FACTOR = 1
33
+ MAX_RETRIES = 3
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+
38
+ class BaseClient:
39
+ def __init__(self, *, api_key: Optional[str] = None, timeout: float = DEFAULT_TIMEOUT):
40
+ """Constructor for the BaseClient. Used by the Cartesia and AsyncCartesia clients."""
41
+ self.api_key = api_key or os.environ.get("CARTESIA_API_KEY")
42
+ self.timeout = timeout
43
+
44
+
45
+ class Resource:
46
+ def __init__(
47
+ self,
48
+ api_key: str,
49
+ timeout: float,
50
+ ):
51
+ """Constructor for the Resource class. Used by the Voices and TTS classes."""
52
+ self.api_key = api_key
53
+ self.timeout = timeout
54
+ self.base_url = os.environ.get("CARTESIA_BASE_URL", DEFAULT_BASE_URL)
55
+ self.cartesia_version = DEFAULT_CARTESIA_VERSION
56
+ self.headers = {
57
+ "X-API-Key": self.api_key,
58
+ "Cartesia-Version": self.cartesia_version,
59
+ "Content-Type": "application/json",
60
+ }
61
+
62
+ def _http_url(self):
63
+ """Returns the HTTP URL for the Cartesia API.
64
+ If the base URL is localhost, the URL will start with 'http'. Otherwise, it will start with 'https'.
65
+ """
66
+ if self.base_url.startswith("http://") or self.base_url.startswith("https://"):
67
+ return self.base_url
68
+ else:
69
+ prefix = "http" if "localhost" in self.base_url else "https"
70
+ return f"{prefix}://{self.base_url}"
71
+
72
+ def _ws_url(self):
73
+ """Returns the WebSocket URL for the Cartesia API.
74
+ If the base URL is localhost, the URL will start with 'ws'. Otherwise, it will start with 'wss'.
75
+ """
76
+ if self.base_url.startswith("ws://") or self.base_url.startswith("wss://"):
77
+ return self.base_url
78
+ else:
79
+ prefix = "ws" if "localhost" in self.base_url else "wss"
80
+ return f"{prefix}://{self.base_url}"
81
+
82
+
83
+ class Cartesia(BaseClient):
84
+ """
85
+ The client for Cartesia's text-to-speech library.
86
+
87
+ This client contains methods to interact with the Cartesia text-to-speech API.
88
+ The client can be used to manage your voice library and generate speech from text.
89
+
90
+ The client supports generating audio using both Server-Sent Events and WebSocket for lower latency.
91
+ """
92
+
93
+ def __init__(self, *, api_key: Optional[str] = None, timeout: float = DEFAULT_TIMEOUT):
94
+ """Constructor for the Cartesia client.
95
+
96
+ Args:
97
+ api_key: The API key to use for authorization.
98
+ If not specified, the API key will be read from the environment variable
99
+ `CARTESIA_API_KEY`.
100
+ timeout: The timeout for the HTTP requests in seconds. Defaults to 30 seconds.
101
+ """
102
+ super().__init__(api_key=api_key, timeout=timeout)
103
+ self.voices = Voices(api_key=self.api_key, timeout=self.timeout)
104
+ self.tts = TTS(api_key=self.api_key, timeout=self.timeout)
105
+
106
+ def __enter__(self):
107
+ return self
108
+
109
+ def __exit__(
110
+ self,
111
+ exc_type: Union[type, None],
112
+ exc: Union[BaseException, None],
113
+ exc_tb: Union[TracebackType, None],
114
+ ):
115
+ pass
116
+
117
+
118
+ class Voices(Resource):
119
+ """This resource contains methods to list, get, clone, and create voices in your Cartesia voice library.
120
+
121
+ Usage:
122
+ >>> client = Cartesia(api_key="your_api_key")
123
+ >>> voices = client.voices.list()
124
+ >>> voice = client.voices.get(id="a0e99841-438c-4a64-b679-ae501e7d6091")
125
+ >>> print("Voice Name:", voice["name"], "Voice Description:", voice["description"])
126
+ >>> embedding = client.voices.clone(filepath="path/to/clip.wav")
127
+ >>> new_voice = client.voices.create(
128
+ ... name="My Voice", description="A new voice", embedding=embedding
129
+ ... )
130
+ """
131
+
132
+ def list(self) -> List[VoiceMetadata]:
133
+ """List all voices in your voice library.
134
+
135
+ Returns:
136
+ This method returns a list of VoiceMetadata objects.
137
+ """
138
+ response = httpx.get(
139
+ f"{self._http_url()}/voices",
140
+ headers=self.headers,
141
+ timeout=self.timeout,
142
+ )
143
+
144
+ if not response.is_success:
145
+ raise ValueError(f"Failed to get voices. Error: {response.text}")
146
+
147
+ voices = response.json()
148
+ return voices
149
+
150
+ def get(self, id: str) -> VoiceMetadata:
151
+ """Get a voice by its ID.
152
+
153
+ Args:
154
+ id: The ID of the voice.
155
+
156
+ Returns:
157
+ A VoiceMetadata object containing the voice metadata.
158
+ """
159
+ url = f"{self._http_url()}/voices/{id}"
160
+ response = httpx.get(url, headers=self.headers, timeout=self.timeout)
161
+
162
+ if not response.is_success:
163
+ raise ValueError(
164
+ f"Failed to get voice. Status Code: {response.status_code}\n"
165
+ f"Error: {response.text}"
166
+ )
167
+
168
+ return response.json()
169
+
170
+ def clone(self, filepath: Optional[str] = None, link: Optional[str] = None) -> List[float]:
171
+ """Clone a voice from a clip or a URL.
172
+
173
+ Args:
174
+ filepath: The path to the clip file.
175
+ link: The URL to the clip
176
+
177
+ Returns:
178
+ The embedding of the cloned voice as a list of floats.
179
+ """
180
+ # TODO: Python has a bytes object, use that instead of a filepath
181
+ if not filepath and not link:
182
+ raise ValueError("At least one of 'filepath' or 'link' must be specified.")
183
+ if filepath and link:
184
+ raise ValueError("Only one of 'filepath' or 'link' should be specified.")
185
+ if filepath:
186
+ url = f"{self._http_url()}/voices/clone/clip"
187
+ with open(filepath, "rb") as file:
188
+ files = {"clip": file}
189
+ headers = self.headers.copy()
190
+ headers.pop("Content-Type", None)
191
+ headers["Content-Type"] = "multipart/form-data"
192
+ response = httpx.post(url, headers=headers, files=files, timeout=self.timeout)
193
+ if not response.is_success:
194
+ raise ValueError(f"Failed to clone voice from clip. Error: {response.text}")
195
+ elif link:
196
+ url = f"{self._http_url()}/voices/clone/url"
197
+ params = {"link": link}
198
+ headers = self.headers.copy()
199
+ headers.pop("Content-Type") # The content type header is not required for URLs
200
+ response = httpx.post(url, headers=self.headers, params=params, timeout=self.timeout)
201
+ if not response.is_success:
202
+ raise ValueError(f"Failed to clone voice from URL. Error: {response.text}")
203
+
204
+ return response.json()["embedding"]
205
+
206
+ def create(self, name: str, description: str, embedding: List[float]) -> VoiceMetadata:
207
+ """Create a new voice.
208
+
209
+ Args:
210
+ name: The name of the voice.
211
+ description: The description of the voice.
212
+ embedding: The embedding of the voice. This should be generated with :meth:`clone`.
213
+
214
+ Returns:
215
+ A dictionary containing the voice metadata.
216
+ """
217
+ response = httpx.post(
218
+ f"{self._http_url()}/voices",
219
+ headers=self.headers,
220
+ json={"name": name, "description": description, "embedding": embedding},
221
+ timeout=self.timeout,
222
+ )
223
+
224
+ if not response.is_success:
225
+ raise ValueError(f"Failed to create voice. Error: {response.text}")
226
+
227
+ return response.json()
228
+
229
+
230
+ class _WebSocket:
231
+ """This class contains methods to generate audio using WebSocket. Ideal for low-latency audio generation.
232
+
233
+ Usage:
234
+ >>> ws = client.tts.websocket()
235
+ >>> for audio_chunk in ws.send(
236
+ ... model_id="upbeat-moon", transcript="Hello world!", voice_embedding=embedding,
237
+ ... output_format={"container": "raw", "encoding": "pcm_f32le", "sample_rate": 44100}, stream=True
238
+ ... ):
239
+ ... audio = audio_chunk["audio"]
240
+ """
241
+
242
+ def __init__(
243
+ self,
244
+ ws_url: str,
245
+ api_key: str,
246
+ cartesia_version: str,
247
+ ):
248
+ self.ws_url = ws_url
249
+ self.api_key = api_key
250
+ self.cartesia_version = cartesia_version
251
+ self.websocket = None
252
+
253
+ def connect(self):
254
+ """This method connects to the WebSocket if it is not already connected."""
255
+ if self.websocket is None or self._is_websocket_closed():
256
+ route = "tts/websocket"
257
+ self.websocket = connect(
258
+ f"{self.ws_url}/{route}?api_key={self.api_key}&cartesia_version={self.cartesia_version}"
259
+ )
260
+
261
+ def _is_websocket_closed(self):
262
+ return self.websocket.socket.fileno() == -1
263
+
264
+ def close(self):
265
+ """This method closes the WebSocket connection. *Highly* recommended to call this method when done using the WebSocket."""
266
+ if self.websocket is not None and not self._is_websocket_closed():
267
+ self.websocket.close()
268
+
269
+ def _convert_response(
270
+ self, response: Dict[str, any], include_context_id: bool
271
+ ) -> Dict[str, Any]:
272
+ audio = base64.b64decode(response["data"])
273
+
274
+ optional_kwargs = {}
275
+ if include_context_id:
276
+ optional_kwargs["context_id"] = response["context_id"]
277
+
278
+ return {
279
+ "audio": audio,
280
+ **optional_kwargs,
281
+ }
282
+
283
+ def _validate_and_construct_voice(
284
+ self, voice_id: Optional[str] = None, voice_embedding: Optional[List[float]] = None
285
+ ) -> dict:
286
+ """Validate and construct the voice dictionary for the request.
287
+
288
+ Args:
289
+ voice_id: The ID of the voice to use for generating audio.
290
+ voice_embedding: The embedding of the voice to use for generating audio.
291
+
292
+ Returns:
293
+ A dictionary representing the voice configuration.
294
+
295
+ Raises:
296
+ ValueError: If neither or both voice_id and voice_embedding are specified.
297
+ """
298
+ if voice_id is None and voice_embedding is None:
299
+ raise ValueError("Either voice_id or voice_embedding must be specified.")
300
+
301
+ if voice_id is not None and voice_embedding is not None:
302
+ raise ValueError("Only one of voice_id or voice_embedding should be specified.")
303
+
304
+ if voice_id:
305
+ return {"mode": "id", "id": voice_id}
306
+
307
+ return {"mode": "embedding", "embedding": voice_embedding}
308
+
309
+ def send(
310
+ self,
311
+ model_id: str,
312
+ transcript: str,
313
+ output_format: dict,
314
+ voice_id: Optional[str] = None,
315
+ voice_embedding: Optional[List[float]] = None,
316
+ context_id: Optional[str] = None,
317
+ duration: Optional[int] = None,
318
+ language: Optional[str] = None,
319
+ stream: bool = True,
320
+ ) -> Union[bytes, Generator[bytes, None, None]]:
321
+ """Send a request to the WebSocket to generate audio.
322
+
323
+ Args:
324
+ model_id: The ID of the model to use for generating audio.
325
+ transcript: The text to convert to speech.
326
+ output_format: A dictionary containing the details of the output format.
327
+ voice_id: The ID of the voice to use for generating audio.
328
+ voice_embedding: The embedding of the voice to use for generating audio.
329
+ context_id: The context ID to use for the request. If not specified, a random context ID will be generated.
330
+ duration: The duration of the audio in seconds.
331
+ language: The language code for the audio request. This can only be used with `model_id = sonic-multilingual`
332
+ stream: Whether to stream the audio or not. (Default is True)
333
+
334
+ Returns:
335
+ If `stream` is True, the method returns a generator that yields chunks. Each chunk is a dictionary.
336
+ If `stream` is False, the method returns a dictionary.
337
+ Both the generator and the dictionary contain the following key(s):
338
+ - audio: The audio as bytes.
339
+ - context_id: The context ID for the request.
340
+ """
341
+ self.connect()
342
+
343
+ if context_id is None:
344
+ context_id = uuid.uuid4().hex
345
+
346
+ voice = self._validate_and_construct_voice(voice_id, voice_embedding)
347
+
348
+ request_body = {
349
+ "model_id": model_id,
350
+ "transcript": transcript,
351
+ "voice": voice,
352
+ "output_format": {
353
+ "container": output_format["container"],
354
+ "encoding": output_format["encoding"],
355
+ "sample_rate": output_format["sample_rate"],
356
+ },
357
+ "context_id": context_id,
358
+ "language": language,
359
+ }
360
+
361
+ if duration is not None:
362
+ request_body["duration"] = duration
363
+
364
+ generator = self._websocket_generator(request_body)
365
+
366
+ if stream:
367
+ return generator
368
+
369
+ chunks = []
370
+ for chunk in generator:
371
+ chunks.append(chunk["audio"])
372
+
373
+ return {"audio": b"".join(chunks), "context_id": context_id}
374
+
375
+ def _websocket_generator(self, request_body: Dict[str, Any]):
376
+ self.websocket.send(json.dumps(request_body))
377
+
378
+ try:
379
+ while True:
380
+ response = json.loads(self.websocket.recv())
381
+ if "error" in response:
382
+ raise RuntimeError(f"Error generating audio:\n{response['error']}")
383
+ if response["done"]:
384
+ break
385
+ yield self._convert_response(response=response, include_context_id=True)
386
+ except Exception as e:
387
+ # Close the websocket connection if an error occurs.
388
+ if self.websocket and not self._is_websocket_closed():
389
+ self.websocket.close()
390
+ raise RuntimeError(f"Failed to generate audio. {response}") from e
391
+
392
+
393
+ class _SSE:
394
+ """This class contains methods to generate audio using Server-Sent Events.
395
+
396
+ Usage:
397
+ >>> for audio_chunk in client.tts.sse(
398
+ ... model_id="upbeat-moon", transcript="Hello world!", voice_embedding=embedding,
399
+ ... output_format={"container": "raw", "encoding": "pcm_f32le", "sample_rate": 44100}, stream=True
400
+ ... ):
401
+ ... audio = audio_chunk["audio"]
402
+ """
403
+
404
+ def __init__(
405
+ self,
406
+ http_url: str,
407
+ headers: Dict[str, str],
408
+ timeout: float,
409
+ ):
410
+ self.http_url = http_url
411
+ self.headers = headers
412
+ self.timeout = timeout
413
+
414
+ def _update_buffer(self, buffer: str, chunk_bytes: bytes) -> Tuple[str, List[Dict[str, Any]]]:
415
+ buffer += chunk_bytes.decode("utf-8")
416
+ outputs = []
417
+ while "{" in buffer and "}" in buffer:
418
+ start_index = buffer.find("{")
419
+ end_index = buffer.find("}", start_index)
420
+ if start_index != -1 and end_index != -1:
421
+ try:
422
+ chunk_json = json.loads(buffer[start_index : end_index + 1])
423
+ if "error" in chunk_json:
424
+ raise RuntimeError(f"Error generating audio:\n{chunk_json['error']}")
425
+ if chunk_json["done"]:
426
+ break
427
+ audio = base64.b64decode(chunk_json["data"])
428
+ outputs.append({"audio": audio})
429
+ buffer = buffer[end_index + 1 :]
430
+ except json.JSONDecodeError:
431
+ break
432
+ return buffer, outputs
433
+
434
+ def _validate_and_construct_voice(
435
+ self, voice_id: Optional[str] = None, voice_embedding: Optional[List[float]] = None
436
+ ) -> dict:
437
+ """Validate and construct the voice dictionary for the request.
438
+
439
+ Args:
440
+ voice_id: The ID of the voice to use for generating audio.
441
+ voice_embedding: The embedding of the voice to use for generating audio.
442
+
443
+ Returns:
444
+ A dictionary representing the voice configuration.
445
+
446
+ Raises:
447
+ ValueError: If neither or both voice_id and voice_embedding are specified.
448
+ """
449
+ if voice_id is None and voice_embedding is None:
450
+ raise ValueError("Either voice_id or voice_embedding must be specified.")
451
+
452
+ if voice_id is not None and voice_embedding is not None:
453
+ raise ValueError("Only one of voice_id or voice_embedding should be specified.")
454
+
455
+ if voice_id:
456
+ return {"mode": "id", "id": voice_id}
457
+
458
+ return {"mode": "embedding", "embedding": voice_embedding}
459
+
460
+ def send(
461
+ self,
462
+ model_id: str,
463
+ transcript: str,
464
+ output_format: OutputFormat,
465
+ voice_id: Optional[str] = None,
466
+ voice_embedding: Optional[List[float]] = None,
467
+ duration: Optional[int] = None,
468
+ language: Optional[str] = None,
469
+ stream: bool = True,
470
+ ) -> Union[bytes, Generator[bytes, None, None]]:
471
+ """Send a request to the server to generate audio using Server-Sent Events.
472
+
473
+ Args:
474
+ model_id: The ID of the model to use for generating audio.
475
+ transcript: The text to convert to speech.
476
+ voice_id: The ID of the voice to use for generating audio.
477
+ voice_embedding: The embedding of the voice to use for generating audio.
478
+ output_format: A dictionary containing the details of the output format.
479
+ duration: The duration of the audio in seconds.
480
+ language: The language code for the audio request. This can only be used with `model_id = sonic-multilingual`
481
+ stream: Whether to stream the audio or not.
482
+
483
+ Returns:
484
+ If `stream` is True, the method returns a generator that yields chunks. Each chunk is a dictionary.
485
+ If `stream` is False, the method returns a dictionary.
486
+ Both the generator and the dictionary contain the following key(s):
487
+ - audio: The audio as bytes.
488
+ """
489
+ voice = self._validate_and_construct_voice(voice_id, voice_embedding)
490
+
491
+ request_body = {
492
+ "model_id": model_id,
493
+ "transcript": transcript,
494
+ "voice": voice,
495
+ "output_format": {
496
+ "container": output_format["container"],
497
+ "encoding": output_format["encoding"],
498
+ "sample_rate": output_format["sample_rate"],
499
+ },
500
+ "language": language,
501
+ }
502
+
503
+ if duration is not None:
504
+ request_body["duration"] = duration
505
+
506
+ generator = self._sse_generator_wrapper(request_body)
507
+
508
+ if stream:
509
+ return generator
510
+
511
+ chunks = []
512
+ for chunk in generator:
513
+ chunks.append(chunk["audio"])
514
+
515
+ return {"audio": b"".join(chunks)}
516
+
517
+ @retry_on_connection_error(
518
+ max_retries=MAX_RETRIES, backoff_factor=BACKOFF_FACTOR, logger=logger
519
+ )
520
+ def _sse_generator_wrapper(self, request_body: Dict[str, Any]):
521
+ """Need to wrap the sse generator in a function for the retry decorator to work."""
522
+ try:
523
+ for chunk in self._sse_generator(request_body):
524
+ yield chunk
525
+ except Exception as e:
526
+ logger.error(f"Failed to generate audio. {e}")
527
+ raise e
528
+
529
+ def _sse_generator(self, request_body: Dict[str, Any]):
530
+ response = requests.post(
531
+ f"{self.http_url}/tts/sse",
532
+ stream=True,
533
+ data=json.dumps(request_body),
534
+ headers=self.headers,
535
+ timeout=(self.timeout, self.timeout),
536
+ )
537
+ if not response.ok:
538
+ raise ValueError(f"Failed to generate audio. {response.text}")
539
+
540
+ buffer = ""
541
+ for chunk_bytes in response.iter_content(chunk_size=None):
542
+ buffer, outputs = self._update_buffer(buffer=buffer, chunk_bytes=chunk_bytes)
543
+ for output in outputs:
544
+ yield output
545
+
546
+ if buffer:
547
+ try:
548
+ chunk_json = json.loads(buffer)
549
+ audio = base64.b64decode(chunk_json["data"])
550
+ yield {"audio": audio}
551
+ except json.JSONDecodeError:
552
+ pass
553
+
554
+
555
+ class TTS(Resource):
556
+ """This resource contains methods to generate audio using Cartesia's text-to-speech API."""
557
+
558
+ def __init__(self, api_key, timeout):
559
+ super().__init__(
560
+ api_key=api_key,
561
+ timeout=timeout,
562
+ )
563
+ self._sse_class = _SSE(self._http_url(), self.headers, self.timeout)
564
+ self.sse = self._sse_class.send
565
+
566
+ def websocket(self) -> _WebSocket:
567
+ """This method returns a WebSocket object that can be used to generate audio using WebSocket.
568
+
569
+ Returns:
570
+ _WebSocket: A WebSocket object that can be used to generate audio using WebSocket.
571
+ """
572
+ ws = _WebSocket(self._ws_url(), self.api_key, self.cartesia_version)
573
+ ws.connect()
574
+ return ws
575
+
576
+ def get_output_format(self, output_format_name: str) -> OutputFormat:
577
+ """Convenience method to get the output_format dictionary from a given output format name.
578
+
579
+ Args:
580
+ output_format_name (str): The name of the output format.
581
+
582
+ Returns:
583
+ OutputFormat: A dictionary containing the details of the output format to be passed into tts.sse() or tts.websocket().send()
584
+
585
+ Raises:
586
+ ValueError: If the output_format name is not supported
587
+ """
588
+ if output_format_name in OutputFormatMapping._format_mapping:
589
+ output_format_obj = OutputFormatMapping.get_format(output_format_name)
590
+ elif output_format_name in DeprecatedOutputFormatMapping._format_mapping:
591
+ output_format_obj = DeprecatedOutputFormatMapping.get_format_deprecated(
592
+ output_format_name
593
+ )
594
+ else:
595
+ raise ValueError(f"Unsupported format: {output_format_name}")
596
+
597
+ return OutputFormat(
598
+ container=output_format_obj["container"],
599
+ encoding=output_format_obj["encoding"],
600
+ sample_rate=output_format_obj["sample_rate"],
601
+ )
602
+
603
+ def get_sample_rate(self, output_format_name: str) -> int:
604
+ """Convenience method to get the sample rate for a given output format.
605
+
606
+ Args:
607
+ output_format_name (str): The name of the output format.
608
+
609
+ Returns:
610
+ int: The sample rate for the output format.
611
+
612
+ Raises:
613
+ ValueError: If the output_format name is not supported
614
+ """
615
+ if output_format_name in OutputFormatMapping._format_mapping:
616
+ output_format_obj = OutputFormatMapping.get_format(output_format_name)
617
+ elif output_format_name in DeprecatedOutputFormatMapping._format_mapping:
618
+ output_format_obj = DeprecatedOutputFormatMapping.get_format_deprecated(
619
+ output_format_name
620
+ )
621
+ else:
622
+ raise ValueError(f"Unsupported format: {output_format_name}")
623
+
624
+ return output_format_obj["sample_rate"]
625
+
626
+
627
+ class AsyncCartesia(Cartesia):
628
+ """The asynchronous version of the Cartesia client."""
629
+
630
+ def __init__(
631
+ self,
632
+ *,
633
+ api_key: Optional[str] = None,
634
+ timeout: float = DEFAULT_TIMEOUT,
635
+ max_num_connections: int = DEFAULT_NUM_CONNECTIONS,
636
+ ):
637
+ """
638
+ Args:
639
+ api_key: See :class:`Cartesia`.
640
+ timeout: See :class:`Cartesia`.
641
+ max_num_connections: The maximum number of concurrent connections to use for the client.
642
+ This is used to limit the number of connections that can be made to the server.
643
+ """
644
+ self._session = None
645
+ self._loop = None
646
+ super().__init__(api_key=api_key, timeout=timeout)
647
+ self.max_num_connections = max_num_connections
648
+ self.tts = AsyncTTS(
649
+ api_key=self.api_key, timeout=self.timeout, get_session=self._get_session
650
+ )
651
+
652
+ async def _get_session(self):
653
+ current_loop = asyncio.get_event_loop()
654
+ if self._loop is not current_loop:
655
+ # If the loop has changed, close the session and create a new one.
656
+ await self.close()
657
+ if self._session is None or self._session.closed:
658
+ timeout = aiohttp.ClientTimeout(total=self.timeout)
659
+ connector = aiohttp.TCPConnector(limit=self.max_num_connections)
660
+ self._session = aiohttp.ClientSession(timeout=timeout, connector=connector)
661
+ self._loop = current_loop
662
+ return self._session
663
+
664
+ async def close(self):
665
+ """This method closes the session.
666
+
667
+ It is *strongly* recommended to call this method when you are done using the client.
668
+ """
669
+ if self._session is not None and not self._session.closed:
670
+ await self._session.close()
671
+
672
+ def __del__(self):
673
+ try:
674
+ loop = asyncio.get_running_loop()
675
+ except RuntimeError:
676
+ loop = None
677
+
678
+ if loop is None:
679
+ asyncio.run(self.close())
680
+ else:
681
+ loop.create_task(self.close())
682
+
683
+ async def __aenter__(self):
684
+ return self
685
+
686
+ async def __aexit__(
687
+ self,
688
+ exc_type: Union[type, None],
689
+ exc: Union[BaseException, None],
690
+ exc_tb: Union[TracebackType, None],
691
+ ):
692
+ await self.close()
693
+
694
+
695
+ class _AsyncSSE(_SSE):
696
+ """This class contains methods to generate audio using Server-Sent Events asynchronously."""
697
+
698
+ def __init__(
699
+ self,
700
+ http_url: str,
701
+ headers: Dict[str, str],
702
+ timeout: float,
703
+ get_session: Callable[[], Optional[aiohttp.ClientSession]],
704
+ ):
705
+ super().__init__(http_url, headers, timeout)
706
+ self._get_session = get_session
707
+
708
+ async def send(
709
+ self,
710
+ model_id: str,
711
+ transcript: str,
712
+ output_format: OutputFormat,
713
+ voice_id: Optional[str] = None,
714
+ voice_embedding: Optional[List[float]] = None,
715
+ duration: Optional[int] = None,
716
+ language: Optional[str] = None,
717
+ stream: bool = True,
718
+ ) -> Union[bytes, AsyncGenerator[bytes, None]]:
719
+ voice = self._validate_and_construct_voice(voice_id, voice_embedding)
720
+
721
+ request_body = {
722
+ "model_id": model_id,
723
+ "transcript": transcript,
724
+ "voice": voice,
725
+ "output_format": {
726
+ "container": output_format["container"],
727
+ "encoding": output_format["encoding"],
728
+ "sample_rate": output_format["sample_rate"],
729
+ },
730
+ "language": language,
731
+ }
732
+
733
+ if duration is not None:
734
+ request_body["duration"] = duration
735
+
736
+ generator = self._sse_generator_wrapper(request_body)
737
+
738
+ if stream:
739
+ return generator
740
+
741
+ chunks = []
742
+ async for chunk in generator:
743
+ chunks.append(chunk["audio"])
744
+
745
+ return {"audio": b"".join(chunks)}
746
+
747
+ @retry_on_connection_error_async(
748
+ max_retries=MAX_RETRIES, backoff_factor=BACKOFF_FACTOR, logger=logger
749
+ )
750
+ async def _sse_generator_wrapper(self, request_body: Dict[str, Any]):
751
+ """Need to wrap the sse generator in a function for the retry decorator to work."""
752
+ try:
753
+ async for chunk in self._sse_generator(request_body):
754
+ yield chunk
755
+ except Exception as e:
756
+ logger.error(f"Failed to generate audio. {e}")
757
+ raise e
758
+
759
+ async def _sse_generator(self, request_body: Dict[str, Any]):
760
+ session = await self._get_session()
761
+ async with session.post(
762
+ f"{self.http_url}/tts/sse", data=json.dumps(request_body), headers=self.headers
763
+ ) as response:
764
+ if not response.ok:
765
+ raise ValueError(f"Failed to generate audio. {await response.text()}")
766
+
767
+ buffer = ""
768
+ async for chunk_bytes in response.content.iter_any():
769
+ buffer, outputs = self._update_buffer(buffer=buffer, chunk_bytes=chunk_bytes)
770
+ for output in outputs:
771
+ yield output
772
+
773
+ if buffer:
774
+ try:
775
+ chunk_json = json.loads(buffer)
776
+ audio = base64.b64decode(chunk_json["data"])
777
+ yield {"audio": audio}
778
+ except json.JSONDecodeError:
779
+ pass
780
+
781
+
782
+ class _AsyncWebSocket(_WebSocket):
783
+ """This class contains methods to generate audio using WebSocket asynchronously."""
784
+
785
+ def __init__(
786
+ self,
787
+ ws_url: str,
788
+ api_key: str,
789
+ cartesia_version: str,
790
+ get_session: Callable[[], Optional[aiohttp.ClientSession]],
791
+ ):
792
+ super().__init__(ws_url, api_key, cartesia_version)
793
+ self._get_session = get_session
794
+ self.websocket = None
795
+
796
+ async def connect(self):
797
+ if self.websocket is None or self._is_websocket_closed():
798
+ route = "tts/websocket"
799
+ session = await self._get_session()
800
+ self.websocket = await session.ws_connect(
801
+ f"{self.ws_url}/{route}?api_key={self.api_key}&cartesia_version={self.cartesia_version}"
802
+ )
803
+
804
+ def _is_websocket_closed(self):
805
+ return self.websocket.closed
806
+
807
+ async def close(self):
808
+ """This method closes the websocket connection. *Highly* recommended to call this method when done."""
809
+ if self.websocket is not None and not self._is_websocket_closed():
810
+ await self.websocket.close()
811
+
812
+ async def send(
813
+ self,
814
+ model_id: str,
815
+ transcript: str,
816
+ output_format: OutputFormat,
817
+ voice_id: Optional[str] = None,
818
+ voice_embedding: Optional[List[float]] = None,
819
+ context_id: Optional[str] = None,
820
+ duration: Optional[int] = None,
821
+ language: Optional[str] = None,
822
+ stream: Optional[bool] = True,
823
+ ) -> Union[bytes, AsyncGenerator[bytes, None]]:
824
+ await self.connect()
825
+
826
+ if context_id is None:
827
+ context_id = uuid.uuid4().hex
828
+
829
+ voice = self._validate_and_construct_voice(voice_id, voice_embedding)
830
+
831
+ request_body = {
832
+ "model_id": model_id,
833
+ "transcript": transcript,
834
+ "voice": voice,
835
+ "output_format": {
836
+ "container": output_format["container"],
837
+ "encoding": output_format["encoding"],
838
+ "sample_rate": output_format["sample_rate"],
839
+ },
840
+ "context_id": context_id,
841
+ "language": language,
842
+ }
843
+
844
+ if duration is not None:
845
+ request_body["duration"] = duration
846
+
847
+ generator = self._websocket_generator(request_body)
848
+
849
+ if stream:
850
+ return generator
851
+
852
+ chunks = []
853
+ async for chunk in generator:
854
+ chunks.append(chunk["audio"])
855
+
856
+ return {"audio": b"".join(chunks), "context_id": context_id}
857
+
858
+ async def _websocket_generator(self, request_body: Dict[str, Any]):
859
+ await self.websocket.send_json(request_body)
860
+
861
+ try:
862
+ response = None
863
+ while True:
864
+ response = await self.websocket.receive_json()
865
+ if "error" in response:
866
+ raise RuntimeError(f"Error generating audio:\n{response['error']}")
867
+ if response["done"]:
868
+ break
869
+
870
+ yield self._convert_response(response=response, include_context_id=True)
871
+ except Exception as e:
872
+ # Close the websocket connection if an error occurs.
873
+ if self.websocket and not self._is_websocket_closed():
874
+ await self.websocket.close()
875
+ error_msg_end = "" if response is None else f": {await response.text()}"
876
+ raise RuntimeError(f"Failed to generate audio. {error_msg_end}") from e
877
+
878
+
879
+ class AsyncTTS(TTS):
880
+ def __init__(self, api_key, timeout, get_session):
881
+ super().__init__(api_key, timeout)
882
+ self._get_session = get_session
883
+ self._sse_class = _AsyncSSE(self._http_url(), self.headers, self.timeout, get_session)
884
+ self.sse = self._sse_class.send
885
+
886
+ async def websocket(self) -> _AsyncWebSocket:
887
+ ws = _AsyncWebSocket(self._ws_url(), self.api_key, self.cartesia_version, self._get_session)
888
+ await ws.connect()
889
+ return ws