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/tts.py ADDED
@@ -0,0 +1,146 @@
1
+ from typing import Iterator, List, Optional
2
+
3
+ import httpx
4
+
5
+ from cartesia._sse import _SSE
6
+ from cartesia._types import (
7
+ DeprecatedOutputFormatMapping,
8
+ OutputFormat,
9
+ OutputFormatMapping,
10
+ VoiceControls,
11
+ )
12
+ from cartesia._websocket import _WebSocket
13
+ from cartesia.resource import Resource
14
+ from cartesia.utils.tts import _construct_tts_request, _validate_and_construct_voice
15
+
16
+
17
+ class TTS(Resource):
18
+ """This resource contains methods to generate audio using Cartesia's text-to-speech API."""
19
+
20
+ def __init__(self, api_key: str, base_url: str, timeout: float):
21
+ super().__init__(
22
+ api_key=api_key,
23
+ base_url=base_url,
24
+ timeout=timeout,
25
+ )
26
+ self._sse_class = _SSE(self._http_url(), self.headers, self.timeout)
27
+ self.sse = self._sse_class.send
28
+
29
+ def websocket(self) -> _WebSocket:
30
+ """This method returns a WebSocket object that can be used to generate audio using WebSocket.
31
+
32
+ Returns:
33
+ _WebSocket: A WebSocket object that can be used to generate audio using WebSocket.
34
+ """
35
+ ws = _WebSocket(self._ws_url(), self.api_key, self.cartesia_version)
36
+ ws.connect()
37
+ return ws
38
+
39
+ def bytes(
40
+ self,
41
+ *,
42
+ model_id: str,
43
+ transcript: str,
44
+ output_format: OutputFormat,
45
+ voice_id: Optional[str] = None,
46
+ voice_embedding: Optional[List[float]] = None,
47
+ duration: Optional[int] = None,
48
+ language: Optional[str] = None,
49
+ _experimental_voice_controls: Optional[VoiceControls] = None,
50
+ ) -> bytes:
51
+ request_body = _construct_tts_request(
52
+ model_id=model_id,
53
+ transcript=transcript,
54
+ output_format=output_format,
55
+ voice_id=voice_id,
56
+ voice_embedding=voice_embedding,
57
+ duration=duration,
58
+ language=language,
59
+ _experimental_voice_controls=_experimental_voice_controls,
60
+ )
61
+
62
+ response = httpx.post(
63
+ f"{self._http_url()}/tts/bytes",
64
+ headers=self.headers,
65
+ timeout=self.timeout,
66
+ json=request_body,
67
+ )
68
+
69
+ if not response.is_success:
70
+ raise ValueError(f"Failed to generate audio. Error: {response.text}")
71
+
72
+ return response.content
73
+
74
+ @staticmethod
75
+ def get_output_format(output_format_name: str) -> OutputFormat:
76
+ """Convenience method to get the output_format dictionary from a given output format name.
77
+
78
+ Args:
79
+ output_format_name (str): The name of the output format.
80
+
81
+ Returns:
82
+ OutputFormat: A dictionary containing the details of the output format to be passed into tts.sse() or tts.websocket().send()
83
+
84
+ Raises:
85
+ ValueError: If the output_format name is not supported
86
+ """
87
+ if output_format_name in OutputFormatMapping._format_mapping:
88
+ output_format_obj = OutputFormatMapping.get_format(output_format_name)
89
+ elif output_format_name in DeprecatedOutputFormatMapping._format_mapping:
90
+ output_format_obj = DeprecatedOutputFormatMapping.get_format_deprecated(
91
+ output_format_name
92
+ )
93
+ else:
94
+ raise ValueError(f"Unsupported format: {output_format_name}")
95
+
96
+ return OutputFormat(
97
+ container=output_format_obj["container"],
98
+ encoding=output_format_obj["encoding"],
99
+ sample_rate=output_format_obj["sample_rate"],
100
+ )
101
+
102
+ @staticmethod
103
+ def get_sample_rate(output_format_name: str) -> int:
104
+ """Convenience method to get the sample rate for a given output format.
105
+
106
+ Args:
107
+ output_format_name (str): The name of the output format.
108
+
109
+ Returns:
110
+ int: The sample rate for the output format.
111
+
112
+ Raises:
113
+ ValueError: If the output_format name is not supported
114
+ """
115
+ if output_format_name in OutputFormatMapping._format_mapping:
116
+ output_format_obj = OutputFormatMapping.get_format(output_format_name)
117
+ elif output_format_name in DeprecatedOutputFormatMapping._format_mapping:
118
+ output_format_obj = DeprecatedOutputFormatMapping.get_format_deprecated(
119
+ output_format_name
120
+ )
121
+ else:
122
+ raise ValueError(f"Unsupported format: {output_format_name}")
123
+
124
+ return output_format_obj["sample_rate"]
125
+
126
+ @staticmethod
127
+ def _validate_and_construct_voice(
128
+ voice_id: Optional[str] = None,
129
+ voice_embedding: Optional[List[float]] = None,
130
+ experimental_voice_controls: Optional[VoiceControls] = None,
131
+ ) -> dict:
132
+ """Validate and construct the voice dictionary for the request.
133
+
134
+ Args:
135
+ voice_id: The ID of the voice to use for generating audio.
136
+ voice_embedding: The embedding of the voice to use for generating audio.
137
+ experimental_voice_controls: Voice controls for emotion and speed.
138
+ Note: This is an experimental feature and may rapidly change in the future.
139
+
140
+ Returns:
141
+ A dictionary representing the voice configuration.
142
+
143
+ Raises:
144
+ ValueError: If neither or both voice_id and voice_embedding are specified.
145
+ """
146
+ return _validate_and_construct_voice(voice_id, voice_embedding, experimental_voice_controls)
File without changes
@@ -0,0 +1,55 @@
1
+ import os
2
+ import warnings
3
+ from typing import Any, Callable, TypeVar
4
+
5
+ TCallable = TypeVar("TCallable", bound=Callable[..., Any])
6
+
7
+ # List of statistics of deprecated functions.
8
+ # This should only be used by the test suite to find any deprecated functions
9
+ # that should be removed for this version.
10
+ _TRACK_DEPRECATED_FUNCTION_STATS = os.environ.get("CARTESIA_TEST_DEPRECATED", "").lower() == "true"
11
+ _DEPRECATED_FUNCTION_STATS = []
12
+
13
+
14
+ def deprecated(
15
+ reason=None, vdeprecated=None, vremove=None, replacement=None
16
+ ) -> Callable[[TCallable], TCallable]:
17
+ local_vars = locals()
18
+
19
+ def fn(func: TCallable) -> TCallable:
20
+ if isinstance(func, classmethod):
21
+ func = func.__func__
22
+ msg = _get_deprecated_msg(func, reason, vdeprecated, vremove, replacement)
23
+ warnings.warn(msg, DeprecationWarning)
24
+ return func
25
+
26
+ if _TRACK_DEPRECATED_FUNCTION_STATS: # pragma: no cover
27
+ _DEPRECATED_FUNCTION_STATS.append(local_vars)
28
+
29
+ return fn
30
+
31
+
32
+ def _get_deprecated_msg(wrapped, reason, vdeprecated, vremoved, replacement=None):
33
+ fmt = "{name} is deprecated"
34
+ if vdeprecated:
35
+ fmt += " since v{vdeprecated}"
36
+ if vremoved:
37
+ fmt += " and will be removed in v{vremoved}"
38
+ fmt += "."
39
+
40
+ if reason:
41
+ fmt += " ({reason})"
42
+ if replacement:
43
+ fmt += " -- Use {replacement} instead."
44
+
45
+ return fmt.format(
46
+ name=wrapped.__name__,
47
+ reason=reason or "",
48
+ vdeprecated=vdeprecated or "",
49
+ vremoved=vremoved or "",
50
+ replacement=replacement or "",
51
+ )
52
+
53
+
54
+ # This method is taken from the following source:
55
+ # https://github.com/ad12/meddlr/blob/main/meddlr/utils/deprecated.py
@@ -0,0 +1,87 @@
1
+ import asyncio
2
+ import time
3
+ from functools import wraps
4
+ from http.client import RemoteDisconnected
5
+
6
+ from aiohttp.client_exceptions import ServerDisconnectedError
7
+ from httpx import TimeoutException
8
+ from requests.exceptions import ConnectionError
9
+
10
+
11
+ def retry_on_connection_error(max_retries=3, backoff_factor=1, logger=None):
12
+ """Retry a function if a ConnectionError, RemoteDisconnected, ServerDisconnectedError, or TimeoutException occurs.
13
+
14
+ Args:
15
+ max_retries (int): The maximum number of retries.
16
+ backoff_factor (int): The factor to increase the delay between retries.
17
+ logger (logging.Logger): The logger to use for logging.
18
+ """
19
+
20
+ def decorator(func):
21
+ @wraps(func)
22
+ def wrapper(*args, **kwargs):
23
+ retry_count = 0
24
+ while retry_count < max_retries:
25
+ try:
26
+ return func(*args, **kwargs)
27
+ except (
28
+ ConnectionError,
29
+ RemoteDisconnected,
30
+ ServerDisconnectedError,
31
+ TimeoutException,
32
+ ) as e:
33
+ logger.info(f"Retrying after exception: {e}")
34
+ retry_count += 1
35
+ if retry_count < max_retries:
36
+ delay = backoff_factor * (2 ** (retry_count - 1))
37
+ logger.warn(
38
+ f"Attempt {retry_count + 1}/{max_retries} in {delay} seconds..."
39
+ )
40
+ time.sleep(delay)
41
+ else:
42
+ raise Exception(f"Exception occurred after {max_retries} tries.") from e
43
+
44
+ return wrapper
45
+
46
+ return decorator
47
+
48
+
49
+ def retry_on_connection_error_async(max_retries=3, backoff_factor=1, logger=None):
50
+ """Retry an asynchronous function if a ConnectionError, RemoteDisconnected, ServerDisconnectedError, or TimeoutException occurs.
51
+
52
+ Args:
53
+ max_retries (int): The maximum number of retries.
54
+ backoff_factor (int): The factor to increase the delay between retries.
55
+ logger (logging.Logger): The logger to use for logging.
56
+ """
57
+
58
+ def decorator(func):
59
+ @wraps(func)
60
+ async def wrapper(*args, **kwargs):
61
+ retry_count = 0
62
+ while retry_count < max_retries:
63
+ try:
64
+ async for chunk in func(*args, **kwargs):
65
+ yield chunk
66
+ # If the function completes without raising an exception return
67
+ return
68
+ except (
69
+ ConnectionError,
70
+ RemoteDisconnected,
71
+ ServerDisconnectedError,
72
+ TimeoutException,
73
+ ) as e:
74
+ logger.info(f"Retrying after exception: {e}")
75
+ retry_count += 1
76
+ if retry_count < max_retries:
77
+ delay = backoff_factor * (2 ** (retry_count - 1))
78
+ logger.warn(
79
+ f"Attempt {retry_count + 1}/{max_retries} in {delay} seconds..."
80
+ )
81
+ await asyncio.sleep(delay)
82
+ else:
83
+ raise Exception(f"Exception occurred after {max_retries} tries.") from e
84
+
85
+ return wrapper
86
+
87
+ return decorator
cartesia/utils/tts.py ADDED
@@ -0,0 +1,74 @@
1
+ from typing import List, Optional
2
+
3
+ from cartesia._types import OutputFormat, VoiceControls
4
+
5
+
6
+ def _validate_and_construct_voice(
7
+ voice_id: Optional[str] = None,
8
+ voice_embedding: Optional[List[float]] = None,
9
+ experimental_voice_controls: Optional[VoiceControls] = None,
10
+ ) -> dict:
11
+ if voice_id is None and voice_embedding is None:
12
+ raise ValueError("Either voice_id or voice_embedding must be specified.")
13
+
14
+ voice = {}
15
+
16
+ if voice_id is not None:
17
+ voice["id"] = voice_id
18
+
19
+ if voice_embedding is not None:
20
+ voice["embedding"] = voice_embedding
21
+
22
+ if experimental_voice_controls is not None:
23
+ voice["__experimental_controls"] = experimental_voice_controls
24
+
25
+ return voice
26
+
27
+
28
+ def _construct_tts_request(
29
+ *,
30
+ model_id: str,
31
+ output_format: OutputFormat,
32
+ transcript: Optional[str] = None,
33
+ voice_id: Optional[str] = None,
34
+ voice_embedding: Optional[List[float]] = None,
35
+ duration: Optional[int] = None,
36
+ language: Optional[str] = None,
37
+ add_timestamps: bool = False,
38
+ context_id: Optional[str] = None,
39
+ continue_: bool = False,
40
+ _experimental_voice_controls: Optional[VoiceControls] = None,
41
+ ):
42
+ tts_request = {
43
+ "model_id": model_id,
44
+ "voice": _validate_and_construct_voice(
45
+ voice_id,
46
+ voice_embedding=voice_embedding,
47
+ experimental_voice_controls=_experimental_voice_controls,
48
+ ),
49
+ "output_format": {
50
+ "container": output_format["container"],
51
+ "encoding": output_format["encoding"],
52
+ "sample_rate": output_format["sample_rate"],
53
+ },
54
+ }
55
+
56
+ if language is not None:
57
+ tts_request["language"] = language
58
+
59
+ if transcript is not None:
60
+ tts_request["transcript"] = transcript
61
+
62
+ if duration is not None:
63
+ tts_request["duration"] = duration
64
+
65
+ if add_timestamps:
66
+ tts_request["add_timestamps"] = add_timestamps
67
+
68
+ if context_id is not None:
69
+ tts_request["context_id"] = context_id
70
+
71
+ if continue_:
72
+ tts_request["continue"] = continue_
73
+
74
+ return tts_request
cartesia/version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "1.1.0-dev0"
cartesia/voices.py ADDED
@@ -0,0 +1,170 @@
1
+ from typing import Dict, List, Optional, Union
2
+
3
+ import httpx
4
+
5
+ from cartesia._types import VoiceMetadata
6
+ from cartesia.resource import Resource
7
+
8
+
9
+ class Voices(Resource):
10
+ """This resource contains methods to list, get, clone, and create voices in your Cartesia voice library.
11
+
12
+ Usage:
13
+ >>> client = Cartesia(api_key="your_api_key")
14
+ >>> voices = client.voices.list()
15
+ >>> voice = client.voices.get(id="a0e99841-438c-4a64-b679-ae501e7d6091")
16
+ >>> print("Voice Name:", voice["name"], "Voice Description:", voice["description"])
17
+ >>> embedding = client.voices.clone(filepath="path/to/clip.wav")
18
+ >>> new_voice = client.voices.create(
19
+ ... name="My Voice", description="A new voice", embedding=embedding
20
+ ... )
21
+ """
22
+
23
+ def list(self) -> List[VoiceMetadata]:
24
+ """List all voices in your voice library.
25
+
26
+ Returns:
27
+ This method returns a list of VoiceMetadata objects.
28
+ """
29
+ response = httpx.get(
30
+ f"{self._http_url()}/voices",
31
+ headers=self.headers,
32
+ timeout=self.timeout,
33
+ )
34
+
35
+ if not response.is_success:
36
+ raise ValueError(f"Failed to get voices. Error: {response.text}")
37
+
38
+ voices = response.json()
39
+ return voices
40
+
41
+ def get(self, id: str) -> VoiceMetadata:
42
+ """Get a voice by its ID.
43
+
44
+ Args:
45
+ id: The ID of the voice.
46
+
47
+ Returns:
48
+ A VoiceMetadata object containing the voice metadata.
49
+ """
50
+ url = f"{self._http_url()}/voices/{id}"
51
+ response = httpx.get(url, headers=self.headers, timeout=self.timeout)
52
+
53
+ if not response.is_success:
54
+ raise ValueError(
55
+ f"Failed to get voice. Status Code: {response.status_code}\n"
56
+ f"Error: {response.text}"
57
+ )
58
+
59
+ return response.json()
60
+
61
+ def clone(self, filepath: Optional[str] = None, enhance: str = True) -> List[float]:
62
+ """Clone a voice from a clip.
63
+
64
+ Args:
65
+ filepath: The path to the clip file.
66
+ enhance: Whether to enhance the clip before cloning the voice (highly recommended). Defaults to True.
67
+
68
+ Returns:
69
+ The embedding of the cloned voice as a list of floats.
70
+ """
71
+ if not filepath:
72
+ raise ValueError("Filepath must be specified.")
73
+ url = f"{self._http_url()}/voices/clone/clip"
74
+ with open(filepath, "rb") as file:
75
+ files = {"clip": file}
76
+ files["enhance"] = str(enhance).lower()
77
+ headers = self.headers.copy()
78
+ headers.pop("Content-Type", None)
79
+ response = httpx.post(url, headers=headers, files=files, timeout=self.timeout)
80
+ if not response.is_success:
81
+ raise ValueError(f"Failed to clone voice from clip. Error: {response.text}")
82
+
83
+ return response.json()["embedding"]
84
+
85
+ def create(
86
+ self,
87
+ name: str,
88
+ description: str,
89
+ embedding: List[float],
90
+ base_voice_id: Optional[str] = None,
91
+ ) -> VoiceMetadata:
92
+ """Create a new voice.
93
+
94
+ Args:
95
+ name: The name of the voice.
96
+ description: The description of the voice.
97
+ embedding: The embedding of the voice. This should be generated with :meth:`clone`.
98
+ base_voice_id: The ID of the base voice. This should be a valid voice ID if specified.
99
+
100
+ Returns:
101
+ A dictionary containing the voice metadata.
102
+ """
103
+ response = httpx.post(
104
+ f"{self._http_url()}/voices",
105
+ headers=self.headers,
106
+ json={
107
+ "name": name,
108
+ "description": description,
109
+ "embedding": embedding,
110
+ "base_voice_id": base_voice_id,
111
+ },
112
+ timeout=self.timeout,
113
+ )
114
+
115
+ if not response.is_success:
116
+ raise ValueError(f"Failed to create voice. Error: {response.text}")
117
+
118
+ return response.json()
119
+
120
+ def delete(self, id: str) -> bool:
121
+ """Delete a voice by its ID.
122
+
123
+ Args:
124
+ id: The ID of the voice.
125
+
126
+ Raises:
127
+ ValueError: If the request fails.
128
+ """
129
+ response = httpx.delete(
130
+ f"{self._http_url()}/voices/{id}",
131
+ headers=self.headers,
132
+ timeout=self.timeout,
133
+ )
134
+
135
+ if not response.is_success:
136
+ raise ValueError(f"Failed to delete voice. Error: {response.text}")
137
+
138
+ def mix(self, voices: List[Dict[str, Union[str, float]]]) -> List[float]:
139
+ """Mix multiple voices together.
140
+
141
+ Args:
142
+ voices: A list of dictionaries, each containing either:
143
+ - 'id': The ID of an existing voice
144
+ - 'embedding': A voice embedding
145
+ AND
146
+ - 'weight': The weight of the voice in the mix (0.0 to 1.0)
147
+
148
+ Returns:
149
+ The embedding of the mixed voice as a list of floats.
150
+
151
+ Raises:
152
+ ValueError: If the request fails or if the input is invalid.
153
+ """
154
+ url = f"{self._http_url()}/voices/mix"
155
+
156
+ if not voices or not isinstance(voices, list):
157
+ raise ValueError("voices must be a non-empty list")
158
+
159
+ response = httpx.post(
160
+ url,
161
+ headers=self.headers,
162
+ json={"voices": voices},
163
+ timeout=self.timeout,
164
+ )
165
+
166
+ if not response.is_success:
167
+ raise ValueError(f"Failed to mix voices. Error: {response.text}")
168
+
169
+ result = response.json()
170
+ return result["embedding"]
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Cartesia AI, Inc.
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.