cartesia 1.4.0__py3-none-any.whl → 2.0.0a2__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.
Files changed (176) hide show
  1. cartesia/__init__.py +292 -3
  2. cartesia/api_status/__init__.py +6 -0
  3. cartesia/api_status/client.py +104 -0
  4. cartesia/api_status/requests/__init__.py +5 -0
  5. cartesia/api_status/requests/api_info.py +8 -0
  6. cartesia/api_status/types/__init__.py +5 -0
  7. cartesia/api_status/types/api_info.py +20 -0
  8. cartesia/base_client.py +160 -0
  9. cartesia/client.py +163 -40
  10. cartesia/core/__init__.py +47 -0
  11. cartesia/core/api_error.py +15 -0
  12. cartesia/core/client_wrapper.py +55 -0
  13. cartesia/core/datetime_utils.py +28 -0
  14. cartesia/core/file.py +67 -0
  15. cartesia/core/http_client.py +499 -0
  16. cartesia/core/jsonable_encoder.py +101 -0
  17. cartesia/core/pydantic_utilities.py +296 -0
  18. cartesia/core/query_encoder.py +58 -0
  19. cartesia/core/remove_none_from_dict.py +11 -0
  20. cartesia/core/request_options.py +35 -0
  21. cartesia/core/serialization.py +272 -0
  22. cartesia/datasets/__init__.py +24 -0
  23. cartesia/datasets/client.py +392 -0
  24. cartesia/datasets/requests/__init__.py +15 -0
  25. cartesia/datasets/requests/create_dataset_request.py +7 -0
  26. cartesia/datasets/requests/dataset.py +9 -0
  27. cartesia/datasets/requests/dataset_file.py +9 -0
  28. cartesia/datasets/requests/paginated_dataset_files.py +10 -0
  29. cartesia/datasets/requests/paginated_datasets.py +10 -0
  30. cartesia/datasets/types/__init__.py +17 -0
  31. cartesia/datasets/types/create_dataset_request.py +19 -0
  32. cartesia/datasets/types/dataset.py +21 -0
  33. cartesia/datasets/types/dataset_file.py +21 -0
  34. cartesia/datasets/types/file_purpose.py +5 -0
  35. cartesia/datasets/types/paginated_dataset_files.py +21 -0
  36. cartesia/datasets/types/paginated_datasets.py +21 -0
  37. cartesia/embedding/__init__.py +5 -0
  38. cartesia/embedding/types/__init__.py +5 -0
  39. cartesia/embedding/types/embedding.py +201 -0
  40. cartesia/environment.py +7 -0
  41. cartesia/infill/__init__.py +2 -0
  42. cartesia/infill/client.py +318 -0
  43. cartesia/tts/__init__.py +167 -0
  44. cartesia/{_async_websocket.py → tts/_async_websocket.py} +159 -84
  45. cartesia/tts/_websocket.py +430 -0
  46. cartesia/tts/client.py +407 -0
  47. cartesia/tts/requests/__init__.py +76 -0
  48. cartesia/tts/requests/cancel_context_request.py +17 -0
  49. cartesia/tts/requests/controls.py +11 -0
  50. cartesia/tts/requests/generation_request.py +53 -0
  51. cartesia/tts/requests/mp_3_output_format.py +11 -0
  52. cartesia/tts/requests/output_format.py +30 -0
  53. cartesia/tts/requests/phoneme_timestamps.py +10 -0
  54. cartesia/tts/requests/raw_output_format.py +11 -0
  55. cartesia/tts/requests/speed.py +7 -0
  56. cartesia/tts/requests/tts_request.py +24 -0
  57. cartesia/tts/requests/tts_request_embedding_specifier.py +16 -0
  58. cartesia/tts/requests/tts_request_id_specifier.py +16 -0
  59. cartesia/tts/requests/tts_request_voice_specifier.py +7 -0
  60. cartesia/tts/requests/wav_output_format.py +7 -0
  61. cartesia/tts/requests/web_socket_base_response.py +11 -0
  62. cartesia/tts/requests/web_socket_chunk_response.py +8 -0
  63. cartesia/tts/requests/web_socket_done_response.py +7 -0
  64. cartesia/tts/requests/web_socket_error_response.py +7 -0
  65. cartesia/tts/requests/web_socket_flush_done_response.py +9 -0
  66. cartesia/tts/requests/web_socket_phoneme_timestamps_response.py +9 -0
  67. cartesia/tts/requests/web_socket_raw_output_format.py +11 -0
  68. cartesia/tts/requests/web_socket_request.py +7 -0
  69. cartesia/tts/requests/web_socket_response.py +69 -0
  70. cartesia/tts/requests/web_socket_stream_options.py +8 -0
  71. cartesia/tts/requests/web_socket_timestamps_response.py +9 -0
  72. cartesia/tts/requests/web_socket_tts_output.py +18 -0
  73. cartesia/tts/requests/web_socket_tts_request.py +24 -0
  74. cartesia/tts/requests/word_timestamps.py +10 -0
  75. cartesia/tts/socket_client.py +302 -0
  76. cartesia/tts/types/__init__.py +90 -0
  77. cartesia/tts/types/cancel_context_request.py +28 -0
  78. cartesia/tts/types/context_id.py +3 -0
  79. cartesia/tts/types/controls.py +22 -0
  80. cartesia/tts/types/emotion.py +29 -0
  81. cartesia/tts/types/flush_id.py +3 -0
  82. cartesia/tts/types/generation_request.py +66 -0
  83. cartesia/tts/types/mp_3_output_format.py +23 -0
  84. cartesia/tts/types/natural_specifier.py +5 -0
  85. cartesia/tts/types/numerical_specifier.py +3 -0
  86. cartesia/tts/types/output_format.py +58 -0
  87. cartesia/tts/types/phoneme_timestamps.py +21 -0
  88. cartesia/tts/types/raw_encoding.py +5 -0
  89. cartesia/tts/types/raw_output_format.py +22 -0
  90. cartesia/tts/types/speed.py +7 -0
  91. cartesia/tts/types/supported_language.py +7 -0
  92. cartesia/tts/types/tts_request.py +35 -0
  93. cartesia/tts/types/tts_request_embedding_specifier.py +27 -0
  94. cartesia/tts/types/tts_request_id_specifier.py +27 -0
  95. cartesia/tts/types/tts_request_voice_specifier.py +7 -0
  96. cartesia/tts/types/wav_output_format.py +17 -0
  97. cartesia/tts/types/web_socket_base_response.py +22 -0
  98. cartesia/tts/types/web_socket_chunk_response.py +20 -0
  99. cartesia/tts/types/web_socket_done_response.py +17 -0
  100. cartesia/tts/types/web_socket_error_response.py +19 -0
  101. cartesia/tts/types/web_socket_flush_done_response.py +21 -0
  102. cartesia/tts/types/web_socket_phoneme_timestamps_response.py +20 -0
  103. cartesia/tts/types/web_socket_raw_output_format.py +22 -0
  104. cartesia/tts/types/web_socket_request.py +7 -0
  105. cartesia/tts/types/web_socket_response.py +124 -0
  106. cartesia/tts/types/web_socket_stream_options.py +19 -0
  107. cartesia/tts/types/web_socket_timestamps_response.py +20 -0
  108. cartesia/tts/types/web_socket_tts_output.py +27 -0
  109. cartesia/tts/types/web_socket_tts_request.py +36 -0
  110. cartesia/tts/types/word_timestamps.py +21 -0
  111. cartesia/tts/utils/tts.py +64 -0
  112. cartesia/tts/utils/types.py +70 -0
  113. cartesia/version.py +3 -1
  114. cartesia/voice_changer/__init__.py +27 -0
  115. cartesia/voice_changer/client.py +395 -0
  116. cartesia/voice_changer/requests/__init__.py +15 -0
  117. cartesia/voice_changer/requests/streaming_response.py +36 -0
  118. cartesia/voice_changer/types/__init__.py +17 -0
  119. cartesia/voice_changer/types/output_format_container.py +5 -0
  120. cartesia/voice_changer/types/streaming_response.py +62 -0
  121. cartesia/voices/__init__.py +71 -0
  122. cartesia/voices/client.py +1053 -0
  123. cartesia/voices/requests/__init__.py +27 -0
  124. cartesia/voices/requests/create_voice_request.py +23 -0
  125. cartesia/voices/requests/embedding_response.py +8 -0
  126. cartesia/voices/requests/embedding_specifier.py +10 -0
  127. cartesia/voices/requests/id_specifier.py +10 -0
  128. cartesia/voices/requests/localize_dialect.py +8 -0
  129. cartesia/voices/requests/localize_voice_request.py +15 -0
  130. cartesia/voices/requests/mix_voice_specifier.py +7 -0
  131. cartesia/voices/requests/mix_voices_request.py +9 -0
  132. cartesia/voices/requests/update_voice_request.py +15 -0
  133. cartesia/voices/requests/voice.py +39 -0
  134. cartesia/voices/requests/voice_metadata.py +36 -0
  135. cartesia/voices/types/__init__.py +45 -0
  136. cartesia/voices/types/base_voice_id.py +5 -0
  137. cartesia/voices/types/clone_mode.py +5 -0
  138. cartesia/voices/types/create_voice_request.py +34 -0
  139. cartesia/voices/types/embedding_response.py +20 -0
  140. cartesia/voices/types/embedding_specifier.py +22 -0
  141. cartesia/voices/types/gender.py +5 -0
  142. cartesia/voices/types/id_specifier.py +22 -0
  143. cartesia/voices/types/localize_dialect.py +8 -0
  144. cartesia/voices/types/localize_english_dialect.py +5 -0
  145. cartesia/voices/types/localize_portuguese_dialect.py +5 -0
  146. cartesia/voices/types/localize_spanish_dialect.py +5 -0
  147. cartesia/voices/types/localize_target_language.py +7 -0
  148. cartesia/voices/types/localize_voice_request.py +26 -0
  149. cartesia/voices/types/mix_voice_specifier.py +7 -0
  150. cartesia/voices/types/mix_voices_request.py +20 -0
  151. cartesia/voices/types/update_voice_request.py +27 -0
  152. cartesia/voices/types/voice.py +50 -0
  153. cartesia/voices/types/voice_id.py +3 -0
  154. cartesia/voices/types/voice_metadata.py +48 -0
  155. cartesia/voices/types/weight.py +3 -0
  156. cartesia-2.0.0a2.dist-info/METADATA +307 -0
  157. cartesia-2.0.0a2.dist-info/RECORD +160 -0
  158. {cartesia-1.4.0.dist-info → cartesia-2.0.0a2.dist-info}/WHEEL +1 -1
  159. cartesia/_async_sse.py +0 -95
  160. cartesia/_logger.py +0 -3
  161. cartesia/_sse.py +0 -143
  162. cartesia/_types.py +0 -70
  163. cartesia/_websocket.py +0 -358
  164. cartesia/async_client.py +0 -82
  165. cartesia/async_tts.py +0 -176
  166. cartesia/resource.py +0 -44
  167. cartesia/tts.py +0 -292
  168. cartesia/utils/deprecated.py +0 -55
  169. cartesia/utils/retry.py +0 -87
  170. cartesia/utils/tts.py +0 -78
  171. cartesia/voices.py +0 -204
  172. cartesia-1.4.0.dist-info/METADATA +0 -663
  173. cartesia-1.4.0.dist-info/RECORD +0 -23
  174. cartesia-1.4.0.dist-info/licenses/LICENSE.md +0 -21
  175. /cartesia/{utils/__init__.py → py.typed} +0 -0
  176. /cartesia/{_constants.py → tts/utils/constants.py} +0 -0
cartesia/client.py CHANGED
@@ -1,69 +1,192 @@
1
- import os
1
+ import asyncio
2
+ import typing
2
3
  from types import TracebackType
3
- from typing import Optional, Union
4
+ from typing import Union
4
5
 
5
- from cartesia._constants import DEFAULT_BASE_URL, DEFAULT_TIMEOUT
6
- from cartesia.tts import TTS
7
- from cartesia.voices import Voices
6
+ import aiohttp
7
+ import httpx
8
8
 
9
+ from .base_client import AsyncBaseCartesia, BaseCartesia
10
+ from .environment import CartesiaEnvironment
11
+ from .tts.socket_client import AsyncTtsClientWithWebsocket, TtsClientWithWebsocket
12
+
13
+
14
+ class Cartesia(BaseCartesia):
15
+ """
16
+ Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.
17
+
18
+ Parameters
19
+ ----------
20
+ base_url : typing.Optional[str]
21
+ The base url to use for requests from the client.
22
+
23
+ environment : CartesiaEnvironment
24
+ The environment to use for requests from the client. from .environment import CartesiaEnvironment
25
+
26
+
27
+
28
+ Defaults to CartesiaEnvironment.PRODUCTION
29
+
30
+
31
+
32
+ api_key : str
33
+ timeout : typing.Optional[float]
34
+ The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced.
35
+
36
+ follow_redirects : typing.Optional[bool]
37
+ Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.
38
+
39
+ httpx_client : typing.Optional[httpx.Client]
40
+ The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
41
+
42
+ Examples
43
+ --------
44
+ from cartesia import Cartesia
45
+
46
+ client = Cartesia(
47
+ api_key="YOUR_API_KEY",
48
+ )
49
+ """
9
50
 
10
- class BaseClient:
11
51
  def __init__(
12
52
  self,
13
53
  *,
14
- api_key: Optional[str] = None,
15
- base_url: Optional[str] = None,
16
- timeout: float = DEFAULT_TIMEOUT,
54
+ base_url: typing.Optional[str] = None,
55
+ environment: CartesiaEnvironment = CartesiaEnvironment.PRODUCTION,
56
+ api_key: str,
57
+ timeout: typing.Optional[float] = None,
58
+ follow_redirects: typing.Optional[bool] = True,
59
+ httpx_client: typing.Optional[httpx.Client] = None,
17
60
  ):
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
61
+ super().__init__(
62
+ base_url=base_url,
63
+ environment=environment,
64
+ api_key=api_key,
65
+ timeout=timeout,
66
+ follow_redirects=follow_redirects,
67
+ httpx_client=httpx_client,
68
+ )
69
+ self.tts = TtsClientWithWebsocket(client_wrapper=self._client_wrapper)
70
+
71
+ def __enter__(self):
72
+ return self
73
+
74
+ def __exit__(
75
+ self,
76
+ exc_type: Union[type, None],
77
+ exc: Union[BaseException, None],
78
+ exc_tb: Union[TracebackType, None],
79
+ ):
80
+ pass
22
81
 
23
- @property
24
- def base_url(self):
25
- return self._base_url
82
+ def __del__(self):
83
+ pass
26
84
 
27
85
 
28
- class Cartesia(BaseClient):
86
+ class AsyncCartesia(AsyncBaseCartesia):
29
87
  """
30
- The client for Cartesia's text-to-speech library.
88
+ Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.
89
+
90
+ Parameters
91
+ ----------
92
+ base_url : typing.Optional[str]
93
+ The base url to use for requests from the client.
94
+
95
+ environment : CartesiaEnvironment
96
+ The environment to use for requests from the client. from .environment import CartesiaEnvironment
97
+
98
+
99
+
100
+ Defaults to CartesiaEnvironment.PRODUCTION
101
+
102
+
103
+
104
+ api_key : str
105
+ timeout : typing.Optional[float]
106
+ The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced.
107
+
108
+ follow_redirects : typing.Optional[bool]
109
+ Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.
31
110
 
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.
111
+ httpx_client : typing.Optional[httpx.AsyncClient]
112
+ The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.
34
113
 
35
- The client supports generating audio using both Server-Sent Events and WebSocket for lower latency.
114
+ Examples
115
+ --------
116
+ from cartesia import AsyncCartesia
117
+
118
+ client = AsyncCartesia(
119
+ api_key="YOUR_API_KEY",
120
+ )
36
121
  """
37
122
 
38
123
  def __init__(
39
124
  self,
40
125
  *,
41
- api_key: Optional[str] = None,
42
- base_url: Optional[str] = None,
43
- timeout: float = DEFAULT_TIMEOUT,
126
+ base_url: typing.Optional[str] = None,
127
+ environment: CartesiaEnvironment = CartesiaEnvironment.PRODUCTION,
128
+ api_key: str,
129
+ follow_redirects: typing.Optional[bool] = True,
130
+ httpx_client: typing.Optional[httpx.AsyncClient] = None,
131
+ timeout: typing.Optional[float] = 30,
132
+ max_num_connections: typing.Optional[int] = 10,
44
133
  ):
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.
134
+ super().__init__(
135
+ base_url=base_url,
136
+ environment=environment,
137
+ api_key=api_key,
138
+ timeout=timeout,
139
+ follow_redirects=follow_redirects,
140
+ httpx_client=httpx_client,
141
+ )
142
+ self.timeout = timeout
143
+ self._session = None
144
+ self._loop = None
145
+ self.max_num_connections = max_num_connections
146
+ self.tts = AsyncTtsClientWithWebsocket(
147
+ client_wrapper=self._client_wrapper, get_session=self._get_session
148
+ )
149
+
150
+ async def _get_session(self):
55
151
  """
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)
152
+ This method is used to get a session for the client.
153
+ """
154
+ current_loop = asyncio.get_event_loop()
155
+ if self._loop is not current_loop:
156
+ await self.close()
157
+ if self._session is None or self._session.closed:
158
+ timeout = aiohttp.ClientTimeout(total=self.timeout)
159
+ connector = aiohttp.TCPConnector(limit=self.max_num_connections)
160
+ self._session = aiohttp.ClientSession(timeout=timeout, connector=connector)
161
+ self._loop = current_loop
162
+ return self._session
59
163
 
60
- def __enter__(self):
164
+ async def close(self):
165
+ """This method closes the session.
166
+
167
+ It is *strongly* recommended to call this method when you are done using the client.
168
+ """
169
+ if self._session is not None and not self._session.closed:
170
+ await self._session.close()
171
+
172
+ def __del__(self):
173
+ try:
174
+ loop = asyncio.get_running_loop()
175
+ except RuntimeError:
176
+ loop = None
177
+
178
+ if loop is None:
179
+ asyncio.run(self.close())
180
+ elif loop.is_running():
181
+ loop.create_task(self.close())
182
+
183
+ async def __aenter__(self):
61
184
  return self
62
185
 
63
- def __exit__(
186
+ async def __aexit__(
64
187
  self,
65
188
  exc_type: Union[type, None],
66
189
  exc: Union[BaseException, None],
67
190
  exc_tb: Union[TracebackType, None],
68
191
  ):
69
- pass
192
+ await self.close()
@@ -0,0 +1,47 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from .api_error import ApiError
4
+ from .client_wrapper import AsyncClientWrapper, BaseClientWrapper, SyncClientWrapper
5
+ from .datetime_utils import serialize_datetime
6
+ from .file import File, convert_file_dict_to_httpx_tuples, with_content_type
7
+ from .http_client import AsyncHttpClient, HttpClient
8
+ from .jsonable_encoder import jsonable_encoder
9
+ from .pydantic_utilities import (
10
+ IS_PYDANTIC_V2,
11
+ UniversalBaseModel,
12
+ UniversalRootModel,
13
+ parse_obj_as,
14
+ universal_field_validator,
15
+ universal_root_validator,
16
+ update_forward_refs,
17
+ )
18
+ from .query_encoder import encode_query
19
+ from .remove_none_from_dict import remove_none_from_dict
20
+ from .request_options import RequestOptions
21
+ from .serialization import FieldMetadata, convert_and_respect_annotation_metadata
22
+
23
+ __all__ = [
24
+ "ApiError",
25
+ "AsyncClientWrapper",
26
+ "AsyncHttpClient",
27
+ "BaseClientWrapper",
28
+ "FieldMetadata",
29
+ "File",
30
+ "HttpClient",
31
+ "IS_PYDANTIC_V2",
32
+ "RequestOptions",
33
+ "SyncClientWrapper",
34
+ "UniversalBaseModel",
35
+ "UniversalRootModel",
36
+ "convert_and_respect_annotation_metadata",
37
+ "convert_file_dict_to_httpx_tuples",
38
+ "encode_query",
39
+ "jsonable_encoder",
40
+ "parse_obj_as",
41
+ "remove_none_from_dict",
42
+ "serialize_datetime",
43
+ "universal_field_validator",
44
+ "universal_root_validator",
45
+ "update_forward_refs",
46
+ "with_content_type",
47
+ ]
@@ -0,0 +1,15 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+
6
+ class ApiError(Exception):
7
+ status_code: typing.Optional[int]
8
+ body: typing.Any
9
+
10
+ def __init__(self, *, status_code: typing.Optional[int] = None, body: typing.Any = None):
11
+ self.status_code = status_code
12
+ self.body = body
13
+
14
+ def __str__(self) -> str:
15
+ return f"status_code: {self.status_code}, body: {self.body}"
@@ -0,0 +1,55 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+ import httpx
5
+ from .http_client import HttpClient
6
+ from .http_client import AsyncHttpClient
7
+
8
+
9
+ class BaseClientWrapper:
10
+ def __init__(self, *, api_key: str, base_url: str, timeout: typing.Optional[float] = None):
11
+ self.api_key = api_key
12
+ self._base_url = base_url
13
+ self._timeout = timeout
14
+
15
+ def get_headers(self) -> typing.Dict[str, str]:
16
+ headers: typing.Dict[str, str] = {
17
+ "X-Fern-Language": "Python",
18
+ "X-Fern-SDK-Name": "cartesia",
19
+ "X-Fern-SDK-Version": "2.0.0a2",
20
+ }
21
+ headers["X-API-Key"] = self.api_key
22
+ headers["Cartesia-Version"] = "2024-06-10"
23
+ return headers
24
+
25
+ def get_base_url(self) -> str:
26
+ return self._base_url
27
+
28
+ def get_timeout(self) -> typing.Optional[float]:
29
+ return self._timeout
30
+
31
+
32
+ class SyncClientWrapper(BaseClientWrapper):
33
+ def __init__(
34
+ self, *, api_key: str, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.Client
35
+ ):
36
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout)
37
+ self.httpx_client = HttpClient(
38
+ httpx_client=httpx_client,
39
+ base_headers=self.get_headers,
40
+ base_timeout=self.get_timeout,
41
+ base_url=self.get_base_url,
42
+ )
43
+
44
+
45
+ class AsyncClientWrapper(BaseClientWrapper):
46
+ def __init__(
47
+ self, *, api_key: str, base_url: str, timeout: typing.Optional[float] = None, httpx_client: httpx.AsyncClient
48
+ ):
49
+ super().__init__(api_key=api_key, base_url=base_url, timeout=timeout)
50
+ self.httpx_client = AsyncHttpClient(
51
+ httpx_client=httpx_client,
52
+ base_headers=self.get_headers,
53
+ base_timeout=self.get_timeout,
54
+ base_url=self.get_base_url,
55
+ )
@@ -0,0 +1,28 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import datetime as dt
4
+
5
+
6
+ def serialize_datetime(v: dt.datetime) -> str:
7
+ """
8
+ Serialize a datetime including timezone info.
9
+
10
+ Uses the timezone info provided if present, otherwise uses the current runtime's timezone info.
11
+
12
+ UTC datetimes end in "Z" while all other timezones are represented as offset from UTC, e.g. +05:00.
13
+ """
14
+
15
+ def _serialize_zoned_datetime(v: dt.datetime) -> str:
16
+ if v.tzinfo is not None and v.tzinfo.tzname(None) == dt.timezone.utc.tzname(None):
17
+ # UTC is a special case where we use "Z" at the end instead of "+00:00"
18
+ return v.isoformat().replace("+00:00", "Z")
19
+ else:
20
+ # Delegate to the typical +/- offset format
21
+ return v.isoformat()
22
+
23
+ if v.tzinfo is not None:
24
+ return _serialize_zoned_datetime(v)
25
+ else:
26
+ local_tz = dt.datetime.now().astimezone().tzinfo
27
+ localized_dt = v.replace(tzinfo=local_tz)
28
+ return _serialize_zoned_datetime(localized_dt)
cartesia/core/file.py ADDED
@@ -0,0 +1,67 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from typing import IO, Dict, List, Mapping, Optional, Tuple, Union, cast
4
+
5
+ # File typing inspired by the flexibility of types within the httpx library
6
+ # https://github.com/encode/httpx/blob/master/httpx/_types.py
7
+ FileContent = Union[IO[bytes], bytes, str]
8
+ File = Union[
9
+ # file (or bytes)
10
+ FileContent,
11
+ # (filename, file (or bytes))
12
+ Tuple[Optional[str], FileContent],
13
+ # (filename, file (or bytes), content_type)
14
+ Tuple[Optional[str], FileContent, Optional[str]],
15
+ # (filename, file (or bytes), content_type, headers)
16
+ Tuple[
17
+ Optional[str],
18
+ FileContent,
19
+ Optional[str],
20
+ Mapping[str, str],
21
+ ],
22
+ ]
23
+
24
+
25
+ def convert_file_dict_to_httpx_tuples(
26
+ d: Dict[str, Union[File, List[File]]],
27
+ ) -> List[Tuple[str, File]]:
28
+ """
29
+ The format we use is a list of tuples, where the first element is the
30
+ name of the file and the second is the file object. Typically HTTPX wants
31
+ a dict, but to be able to send lists of files, you have to use the list
32
+ approach (which also works for non-lists)
33
+ https://github.com/encode/httpx/pull/1032
34
+ """
35
+
36
+ httpx_tuples = []
37
+ for key, file_like in d.items():
38
+ if isinstance(file_like, list):
39
+ for file_like_item in file_like:
40
+ httpx_tuples.append((key, file_like_item))
41
+ else:
42
+ httpx_tuples.append((key, file_like))
43
+ return httpx_tuples
44
+
45
+
46
+ def with_content_type(*, file: File, default_content_type: str) -> File:
47
+ """
48
+ This function resolves to the file's content type, if provided, and defaults
49
+ to the default_content_type value if not.
50
+ """
51
+ if isinstance(file, tuple):
52
+ if len(file) == 2:
53
+ filename, content = cast(Tuple[Optional[str], FileContent], file) # type: ignore
54
+ return (filename, content, default_content_type)
55
+ elif len(file) == 3:
56
+ filename, content, file_content_type = cast(Tuple[Optional[str], FileContent, Optional[str]], file) # type: ignore
57
+ out_content_type = file_content_type or default_content_type
58
+ return (filename, content, out_content_type)
59
+ elif len(file) == 4:
60
+ filename, content, file_content_type, headers = cast( # type: ignore
61
+ Tuple[Optional[str], FileContent, Optional[str], Mapping[str, str]], file
62
+ )
63
+ out_content_type = file_content_type or default_content_type
64
+ return (filename, content, out_content_type, headers)
65
+ else:
66
+ raise ValueError(f"Unexpected tuple length: {len(file)}")
67
+ return (None, file, default_content_type)