bakbak-python 1.0.0rc2__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.
- bakbak/__init__.py +77 -0
- bakbak/_base_client.py +642 -0
- bakbak/_client.py +219 -0
- bakbak/_constants.py +43 -0
- bakbak/_exceptions.py +410 -0
- bakbak/_models.py +93 -0
- bakbak/_response.py +51 -0
- bakbak/_retry.py +52 -0
- bakbak/_sse.py +68 -0
- bakbak/_streaming.py +432 -0
- bakbak/_types.py +79 -0
- bakbak/_utils.py +62 -0
- bakbak/_version.py +3 -0
- bakbak/_ws/__init__.py +1 -0
- bakbak/_ws/_async.py +657 -0
- bakbak/_ws/_common.py +176 -0
- bakbak/_ws/_core.py +819 -0
- bakbak/_ws/_sync.py +649 -0
- bakbak/_ws/events.py +67 -0
- bakbak/audio.py +75 -0
- bakbak/py.typed +0 -0
- bakbak/resources/__init__.py +6 -0
- bakbak/resources/tts.py +339 -0
- bakbak/resources/voices.py +139 -0
- bakbak/text.py +463 -0
- bakbak/types.py +100 -0
- bakbak/websocket.py +23 -0
- bakbak_python-1.0.0rc2.dist-info/METADATA +416 -0
- bakbak_python-1.0.0rc2.dist-info/RECORD +31 -0
- bakbak_python-1.0.0rc2.dist-info/WHEEL +4 -0
- bakbak_python-1.0.0rc2.dist-info/licenses/LICENSE +202 -0
bakbak/_base_client.py
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
"""The HTTP core: configuration, headers, and the one retry loop per client.
|
|
2
|
+
|
|
3
|
+
Every HTTP call goes through ``_request``: build the request, send it, map
|
|
4
|
+
failures onto the error hierarchy, and retry what BEHAVIOR.md §4.2 allows,
|
|
5
|
+
waiting as §4.3 says. What happens to a successful response is up to the
|
|
6
|
+
``handle`` callback of the call, which may itself raise a retryable error, for
|
|
7
|
+
example an SSE ``error`` event that arrives before any audio.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import binascii
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import time
|
|
17
|
+
from collections import deque
|
|
18
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import TypeVar, cast
|
|
21
|
+
from urllib.parse import urlsplit
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from ._constants import (
|
|
26
|
+
API_KEY_ENV,
|
|
27
|
+
BASE_URL_ENV,
|
|
28
|
+
DEFAULT_BASE_URL,
|
|
29
|
+
KEEPALIVE_EXPIRY,
|
|
30
|
+
WEBSOCKET_PATH,
|
|
31
|
+
)
|
|
32
|
+
from ._exceptions import (
|
|
33
|
+
APIConnectionError,
|
|
34
|
+
APIError,
|
|
35
|
+
APIStatusError,
|
|
36
|
+
APITimeoutError,
|
|
37
|
+
BakbakError,
|
|
38
|
+
StreamInterruptedError,
|
|
39
|
+
event_status,
|
|
40
|
+
make_interrupted_error,
|
|
41
|
+
make_status_error,
|
|
42
|
+
)
|
|
43
|
+
from ._models import Audio
|
|
44
|
+
from ._retry import retry_delay
|
|
45
|
+
from ._sse import SSEDecoder
|
|
46
|
+
from ._streaming import OpenStream, decode_audio, parse_events
|
|
47
|
+
from ._types import NotGiven, Timeout, TimeoutLike, coerce_timeout
|
|
48
|
+
from ._utils import as_mapping, client_header, logger, user_agent, websocket_url
|
|
49
|
+
from .types import Voice
|
|
50
|
+
|
|
51
|
+
__all__ = ["AsyncAPIClient", "SyncAPIClient"]
|
|
52
|
+
|
|
53
|
+
T = TypeVar("T")
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
@dataclass(slots=True)
|
|
57
|
+
class CallOptions:
|
|
58
|
+
"""The options of one call, resolved against the client's defaults."""
|
|
59
|
+
|
|
60
|
+
timeout: Timeout
|
|
61
|
+
max_retries: int
|
|
62
|
+
extra_headers: Mapping[str, str] | None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _key_problem(key: str) -> str | None:
|
|
66
|
+
"""What is wrong with a key that cannot be a header value, if anything."""
|
|
67
|
+
if not isinstance(key, str): # pyright: ignore[reportUnnecessaryIsInstance]
|
|
68
|
+
return "is not a string"
|
|
69
|
+
if any(ch.isspace() for ch in key):
|
|
70
|
+
return "contains whitespace"
|
|
71
|
+
if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in key):
|
|
72
|
+
return "contains control characters"
|
|
73
|
+
if not key.isascii():
|
|
74
|
+
return "contains non-ASCII characters"
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _check_max_retries(value: int) -> int:
|
|
79
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0: # pyright: ignore[reportUnnecessaryIsInstance]
|
|
80
|
+
raise BakbakError("max_retries must be a non-negative int")
|
|
81
|
+
return value
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _httpx_timeout(timeout: Timeout, deadline: float | None) -> httpx.Timeout:
|
|
85
|
+
read = timeout.read
|
|
86
|
+
connect = timeout.connect
|
|
87
|
+
if deadline is not None:
|
|
88
|
+
remaining = max(deadline - time.monotonic(), 0.001)
|
|
89
|
+
read = remaining if read is None else min(read, remaining)
|
|
90
|
+
connect = remaining if connect is None else min(connect, remaining)
|
|
91
|
+
return httpx.Timeout(connect=connect, read=read, write=read, pool=read)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _header_int(headers: httpx.Headers, name: str) -> int | None:
|
|
95
|
+
value = headers.get(name)
|
|
96
|
+
try:
|
|
97
|
+
return int(value) if value is not None else None
|
|
98
|
+
except ValueError:
|
|
99
|
+
return None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _audio(response: httpx.Response, data: bytes) -> Audio:
|
|
103
|
+
headers = response.headers
|
|
104
|
+
return Audio(
|
|
105
|
+
data=data,
|
|
106
|
+
request_id=headers.get("x-request-id"),
|
|
107
|
+
content_type=headers.get("content-type"),
|
|
108
|
+
encoding=headers.get("x-audio-format"),
|
|
109
|
+
sample_rate=_header_int(headers, "x-audio-sample-rate"),
|
|
110
|
+
)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _voices(response: httpx.Response, content: bytes) -> list[Voice]:
|
|
114
|
+
try:
|
|
115
|
+
body = as_mapping(json.loads(content))
|
|
116
|
+
except ValueError:
|
|
117
|
+
body = None
|
|
118
|
+
entries = body.get("voices") if body is not None else None
|
|
119
|
+
if not isinstance(entries, list):
|
|
120
|
+
raise APIError(
|
|
121
|
+
"The API returned a voice list the SDK cannot read.",
|
|
122
|
+
status=response.status_code,
|
|
123
|
+
request_id=response.headers.get("x-request-id"),
|
|
124
|
+
)
|
|
125
|
+
voices: list[Voice] = []
|
|
126
|
+
for item in cast("list[object]", entries):
|
|
127
|
+
entry = as_mapping(item)
|
|
128
|
+
if entry is None:
|
|
129
|
+
continue
|
|
130
|
+
voices.append(
|
|
131
|
+
Voice(
|
|
132
|
+
id=str(entry.get("id", "")),
|
|
133
|
+
name=str(entry.get("name", "")),
|
|
134
|
+
language=str(entry.get("language", "")),
|
|
135
|
+
model=str(entry.get("model", "")),
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
return voices
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def filter_voices(voices: list[Voice], model: str | None, language: str | None) -> list[Voice]:
|
|
142
|
+
return [
|
|
143
|
+
v
|
|
144
|
+
for v in voices
|
|
145
|
+
if (model is None or v.model == model) and (language is None or v.language == language)
|
|
146
|
+
]
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
class _StreamStart:
|
|
150
|
+
"""Finds the first audio event of an SSE response (or its ``done``).
|
|
151
|
+
|
|
152
|
+
An ``error`` event before any audio is an ordinary, possibly retryable,
|
|
153
|
+
``APIStatusError``; a stream that ends before any audio is a retryable
|
|
154
|
+
connection error.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
__slots__ = ("decoder", "pending", "response")
|
|
158
|
+
|
|
159
|
+
def __init__(self, response: httpx.Response) -> None:
|
|
160
|
+
self.response = response
|
|
161
|
+
self.decoder = SSEDecoder()
|
|
162
|
+
self.pending: deque[tuple[Mapping[str, object], bytes | None]] = deque()
|
|
163
|
+
|
|
164
|
+
def feed(self, raw: bytes) -> bool:
|
|
165
|
+
"""Parse ``raw``; True once the first audio or ``done`` is pending."""
|
|
166
|
+
events = parse_events(self.decoder, raw)
|
|
167
|
+
for i, event in enumerate(events):
|
|
168
|
+
kind = event.get("type")
|
|
169
|
+
if kind == "chunk" and event.get("data"):
|
|
170
|
+
try:
|
|
171
|
+
audio = decode_audio(event) # decoded once, here
|
|
172
|
+
except (binascii.Error, ValueError):
|
|
173
|
+
# The stream broke before any audio: retried (§6.4 note).
|
|
174
|
+
raise make_interrupted_error(
|
|
175
|
+
None,
|
|
176
|
+
audio_bytes=0,
|
|
177
|
+
header_request_id=self.response.headers.get("x-request-id"),
|
|
178
|
+
default_message="The server sent audio that is not valid base64.",
|
|
179
|
+
) from None
|
|
180
|
+
self.pending.append((event, audio))
|
|
181
|
+
self.pending.extend((e, None) for e in events[i + 1 :])
|
|
182
|
+
return True
|
|
183
|
+
if kind == "done":
|
|
184
|
+
self.pending.extend((e, None) for e in events[i:])
|
|
185
|
+
return True
|
|
186
|
+
if kind == "error":
|
|
187
|
+
raise make_status_error(
|
|
188
|
+
event_status(event),
|
|
189
|
+
event,
|
|
190
|
+
header_request_id=self.response.headers.get("x-request-id"),
|
|
191
|
+
)
|
|
192
|
+
return False
|
|
193
|
+
|
|
194
|
+
def ended(self) -> StreamInterruptedError:
|
|
195
|
+
"""The body ended with no audio and no ``done``: a connection failure,
|
|
196
|
+
retried like one (§5.1)."""
|
|
197
|
+
return make_interrupted_error(
|
|
198
|
+
None,
|
|
199
|
+
audio_bytes=0,
|
|
200
|
+
header_request_id=self.response.headers.get("x-request-id"),
|
|
201
|
+
default_message="The stream ended before any audio arrived.",
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _transport_error(exc: Exception, phase: str) -> APIConnectionError:
|
|
206
|
+
"""The SDK error for an httpx failure. It is raised without its cause:
|
|
207
|
+
httpx exceptions hold the request, and so the X-API-Key header (§8)."""
|
|
208
|
+
if isinstance(exc, httpx.TimeoutException):
|
|
209
|
+
return APITimeoutError(f"The request timed out {phase}.")
|
|
210
|
+
detail = str(exc)[:200]
|
|
211
|
+
return APIConnectionError(
|
|
212
|
+
f"Connection error {phase}: {type(exc).__name__}" + (f": {detail}" if detail else ".")
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _body_failure(exc: Exception, received: int, response: httpx.Response) -> BakbakError:
|
|
217
|
+
"""A whole-file body broke: interrupted after its first byte, else a
|
|
218
|
+
connection error that can be retried."""
|
|
219
|
+
if received:
|
|
220
|
+
return make_interrupted_error(
|
|
221
|
+
None,
|
|
222
|
+
audio_bytes=received,
|
|
223
|
+
header_request_id=response.headers.get("x-request-id"),
|
|
224
|
+
default_message="The audio ended before it was complete.",
|
|
225
|
+
)
|
|
226
|
+
return _transport_error(exc, "before the audio started")
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _past(deadline: float | None) -> bool:
|
|
230
|
+
return deadline is not None and time.monotonic() > deadline
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class _BaseClient:
|
|
234
|
+
"""Configuration shared by ``Bakbak`` and ``AsyncBakbak``."""
|
|
235
|
+
|
|
236
|
+
api_key: str
|
|
237
|
+
base_url: str
|
|
238
|
+
timeout: Timeout
|
|
239
|
+
max_retries: int
|
|
240
|
+
|
|
241
|
+
def __init__(
|
|
242
|
+
self,
|
|
243
|
+
*,
|
|
244
|
+
api_key: str | None,
|
|
245
|
+
base_url: str | None,
|
|
246
|
+
timeout: TimeoutLike | NotGiven,
|
|
247
|
+
max_retries: int,
|
|
248
|
+
default_headers: Mapping[str, str] | None,
|
|
249
|
+
) -> None:
|
|
250
|
+
if api_key is None:
|
|
251
|
+
api_key = os.environ.get(API_KEY_ENV) or None
|
|
252
|
+
if not api_key:
|
|
253
|
+
raise BakbakError(
|
|
254
|
+
"No API key was found: pass api_key= to the client, or set the "
|
|
255
|
+
f"{API_KEY_ENV} environment variable."
|
|
256
|
+
)
|
|
257
|
+
problem = _key_problem(api_key)
|
|
258
|
+
if problem:
|
|
259
|
+
# Never echo the key: it could end up in a log.
|
|
260
|
+
raise BakbakError(
|
|
261
|
+
f"The API key {problem}, so it cannot be sent in a header; check for a "
|
|
262
|
+
"stray space, line break or quote where it was copied."
|
|
263
|
+
)
|
|
264
|
+
if base_url is None:
|
|
265
|
+
base_url = os.environ.get(BASE_URL_ENV) or DEFAULT_BASE_URL
|
|
266
|
+
base_url = base_url.strip().rstrip("/")
|
|
267
|
+
if urlsplit(base_url).scheme not in ("http", "https"):
|
|
268
|
+
raise BakbakError("base_url must start with https:// (or http://)")
|
|
269
|
+
self.api_key = api_key
|
|
270
|
+
self.base_url = base_url
|
|
271
|
+
self.timeout = Timeout() if isinstance(timeout, NotGiven) else coerce_timeout(timeout)
|
|
272
|
+
self.max_retries = _check_max_retries(max_retries)
|
|
273
|
+
self._default_headers: dict[str, str] = dict(default_headers or {})
|
|
274
|
+
|
|
275
|
+
def __repr__(self) -> str:
|
|
276
|
+
return f"{type(self).__name__}(base_url={self.base_url!r})"
|
|
277
|
+
|
|
278
|
+
@property
|
|
279
|
+
def websocket_url(self) -> str:
|
|
280
|
+
"""The URL of the synthesis WebSocket."""
|
|
281
|
+
return websocket_url(self.base_url, WEBSOCKET_PATH)
|
|
282
|
+
|
|
283
|
+
def _options(
|
|
284
|
+
self,
|
|
285
|
+
timeout: TimeoutLike | NotGiven,
|
|
286
|
+
max_retries: int | NotGiven,
|
|
287
|
+
extra_headers: Mapping[str, str] | None,
|
|
288
|
+
) -> CallOptions:
|
|
289
|
+
return CallOptions(
|
|
290
|
+
timeout=self.timeout if isinstance(timeout, NotGiven) else coerce_timeout(timeout),
|
|
291
|
+
max_retries=(
|
|
292
|
+
self.max_retries
|
|
293
|
+
if isinstance(max_retries, NotGiven)
|
|
294
|
+
else _check_max_retries(max_retries)
|
|
295
|
+
),
|
|
296
|
+
extra_headers=extra_headers,
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
def _identity_headers(self) -> dict[str, str]:
|
|
300
|
+
return {"X-API-Key": self.api_key, "X-Bakbak-Client": client_header()}
|
|
301
|
+
|
|
302
|
+
def _headers(self, options: CallOptions, *, accept: str, has_body: bool) -> dict[str, str]:
|
|
303
|
+
headers = {"User-Agent": user_agent(), "Accept": accept, **self._identity_headers()}
|
|
304
|
+
if has_body:
|
|
305
|
+
headers["Content-Type"] = "application/json"
|
|
306
|
+
headers.update(self._default_headers)
|
|
307
|
+
if options.extra_headers:
|
|
308
|
+
headers.update(options.extra_headers)
|
|
309
|
+
return headers
|
|
310
|
+
|
|
311
|
+
def websocket_headers(self) -> dict[str, str]:
|
|
312
|
+
"""Headers of the WebSocket upgrade (the User-Agent is set separately)."""
|
|
313
|
+
return {**self._identity_headers(), **self._default_headers}
|
|
314
|
+
|
|
315
|
+
@staticmethod
|
|
316
|
+
def _body(params: Mapping[str, object], extra_body: Mapping[str, object] | None) -> bytes:
|
|
317
|
+
payload = {**params, **extra_body} if extra_body else params
|
|
318
|
+
return json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode()
|
|
319
|
+
|
|
320
|
+
@staticmethod
|
|
321
|
+
def _deadline(options: CallOptions) -> float | None:
|
|
322
|
+
total = options.timeout.total
|
|
323
|
+
return time.monotonic() + total if total is not None else None
|
|
324
|
+
|
|
325
|
+
@staticmethod
|
|
326
|
+
def _status_error(response: httpx.Response, content: bytes | None) -> APIStatusError:
|
|
327
|
+
body: object = None
|
|
328
|
+
if content:
|
|
329
|
+
try:
|
|
330
|
+
body = json.loads(content)
|
|
331
|
+
except ValueError:
|
|
332
|
+
body = None
|
|
333
|
+
return make_status_error(
|
|
334
|
+
response.status_code,
|
|
335
|
+
body,
|
|
336
|
+
header_request_id=response.headers.get("x-request-id"),
|
|
337
|
+
reason=response.reason_phrase,
|
|
338
|
+
)
|
|
339
|
+
|
|
340
|
+
def _next_wait(
|
|
341
|
+
self,
|
|
342
|
+
error: BakbakError,
|
|
343
|
+
retries: int,
|
|
344
|
+
options: CallOptions,
|
|
345
|
+
deadline: float | None,
|
|
346
|
+
retry_after: str | None,
|
|
347
|
+
) -> float | None:
|
|
348
|
+
"""Seconds to wait before the next attempt, or None to give up."""
|
|
349
|
+
if not getattr(error, "retryable", False):
|
|
350
|
+
return None
|
|
351
|
+
if isinstance(error, StreamInterruptedError) and error.audio_bytes:
|
|
352
|
+
return None # never retry once audio has been delivered (§4.1)
|
|
353
|
+
if retries >= options.max_retries:
|
|
354
|
+
return None
|
|
355
|
+
delay = retry_delay(retries + 1, retry_after)
|
|
356
|
+
if deadline is not None and time.monotonic() + delay >= deadline:
|
|
357
|
+
return None
|
|
358
|
+
return delay
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
class SyncAPIClient(_BaseClient):
|
|
362
|
+
"""The synchronous HTTP core."""
|
|
363
|
+
|
|
364
|
+
_client: httpx.Client
|
|
365
|
+
_owns_client: bool
|
|
366
|
+
_sleep: Callable[[float], None]
|
|
367
|
+
|
|
368
|
+
def __init__(
|
|
369
|
+
self,
|
|
370
|
+
*,
|
|
371
|
+
api_key: str | None,
|
|
372
|
+
base_url: str | None,
|
|
373
|
+
timeout: TimeoutLike | NotGiven,
|
|
374
|
+
max_retries: int,
|
|
375
|
+
default_headers: Mapping[str, str] | None,
|
|
376
|
+
http_client: httpx.Client | None,
|
|
377
|
+
) -> None:
|
|
378
|
+
super().__init__(
|
|
379
|
+
api_key=api_key,
|
|
380
|
+
base_url=base_url,
|
|
381
|
+
timeout=timeout,
|
|
382
|
+
max_retries=max_retries,
|
|
383
|
+
default_headers=default_headers,
|
|
384
|
+
)
|
|
385
|
+
self._owns_client = http_client is None
|
|
386
|
+
self._client = http_client or httpx.Client(
|
|
387
|
+
limits=httpx.Limits(keepalive_expiry=KEEPALIVE_EXPIRY),
|
|
388
|
+
follow_redirects=False,
|
|
389
|
+
)
|
|
390
|
+
self._sleep = time.sleep
|
|
391
|
+
|
|
392
|
+
def close(self) -> None:
|
|
393
|
+
"""Close the connection pool, unless it was passed in as ``http_client``."""
|
|
394
|
+
if self._owns_client:
|
|
395
|
+
self._client.close()
|
|
396
|
+
|
|
397
|
+
def _request(
|
|
398
|
+
self,
|
|
399
|
+
method: str,
|
|
400
|
+
path: str,
|
|
401
|
+
*,
|
|
402
|
+
body: bytes | None,
|
|
403
|
+
accept: str,
|
|
404
|
+
options: CallOptions,
|
|
405
|
+
handle: Callable[[httpx.Response, float | None], T],
|
|
406
|
+
) -> tuple[T, httpx.Response, int]:
|
|
407
|
+
headers = self._headers(options, accept=accept, has_body=body is not None)
|
|
408
|
+
deadline = self._deadline(options)
|
|
409
|
+
url = self.base_url + path
|
|
410
|
+
retries = 0
|
|
411
|
+
while True:
|
|
412
|
+
retry_after: str | None = None
|
|
413
|
+
started = time.monotonic()
|
|
414
|
+
logger.debug("%s %s (attempt %d)", method, path, retries + 1)
|
|
415
|
+
try:
|
|
416
|
+
request = self._client.build_request(
|
|
417
|
+
method, url, headers=headers, content=body,
|
|
418
|
+
timeout=_httpx_timeout(options.timeout, deadline),
|
|
419
|
+
) # fmt: skip
|
|
420
|
+
# Never follow a redirect, even with a caller's http_client:
|
|
421
|
+
# it would carry X-API-Key to another origin (§8).
|
|
422
|
+
response = self._client.send(request, stream=True, follow_redirects=False)
|
|
423
|
+
except httpx.HTTPError as exc:
|
|
424
|
+
error: BakbakError = _transport_error(exc, "before any response")
|
|
425
|
+
else:
|
|
426
|
+
logger.debug(
|
|
427
|
+
"%s %s -> %d (request_id %s) in %.0f ms",
|
|
428
|
+
method, path, response.status_code,
|
|
429
|
+
response.headers.get("x-request-id"), (time.monotonic() - started) * 1000,
|
|
430
|
+
) # fmt: skip
|
|
431
|
+
try:
|
|
432
|
+
if not 200 <= response.status_code < 300:
|
|
433
|
+
retry_after = response.headers.get("retry-after")
|
|
434
|
+
try:
|
|
435
|
+
content = response.read()
|
|
436
|
+
except httpx.HTTPError:
|
|
437
|
+
content = None
|
|
438
|
+
raise self._status_error(response, content)
|
|
439
|
+
return handle(response, deadline), response, retries
|
|
440
|
+
except (APIStatusError, APIConnectionError, StreamInterruptedError) as exc:
|
|
441
|
+
response.close()
|
|
442
|
+
error = exc
|
|
443
|
+
except BaseException:
|
|
444
|
+
response.close()
|
|
445
|
+
raise
|
|
446
|
+
wait = self._next_wait(error, retries, options, deadline, retry_after)
|
|
447
|
+
if wait is None:
|
|
448
|
+
raise error
|
|
449
|
+
retries += 1
|
|
450
|
+
logger.debug("retrying %s %s in %.2f s after: %s", method, path, wait, error.message)
|
|
451
|
+
self._sleep(wait)
|
|
452
|
+
|
|
453
|
+
# Handlers: what to do with a successful response.
|
|
454
|
+
|
|
455
|
+
@staticmethod
|
|
456
|
+
def _read_audio(response: httpx.Response, deadline: float | None) -> Audio:
|
|
457
|
+
parts: list[bytes] = []
|
|
458
|
+
received = 0
|
|
459
|
+
failure: BakbakError | None = None
|
|
460
|
+
try:
|
|
461
|
+
for piece in response.iter_bytes():
|
|
462
|
+
parts.append(piece)
|
|
463
|
+
received += len(piece)
|
|
464
|
+
if _past(deadline):
|
|
465
|
+
raise httpx.ReadTimeout("total timeout")
|
|
466
|
+
except httpx.HTTPError as exc:
|
|
467
|
+
failure = _body_failure(exc, received, response)
|
|
468
|
+
finally:
|
|
469
|
+
response.close()
|
|
470
|
+
if failure is not None:
|
|
471
|
+
raise failure # outside the except block: no httpx exception in its chain
|
|
472
|
+
return _audio(response, b"".join(parts))
|
|
473
|
+
|
|
474
|
+
@staticmethod
|
|
475
|
+
def _start_stream(
|
|
476
|
+
response: httpx.Response, deadline: float | None
|
|
477
|
+
) -> OpenStream[Iterator[bytes]]:
|
|
478
|
+
start = _StreamStart(response)
|
|
479
|
+
raw = response.iter_bytes()
|
|
480
|
+
failure: BakbakError | None = None
|
|
481
|
+
try:
|
|
482
|
+
for piece in raw:
|
|
483
|
+
if start.feed(piece):
|
|
484
|
+
return OpenStream(response, start.pending, start.decoder, raw, deadline)
|
|
485
|
+
if _past(deadline):
|
|
486
|
+
raise httpx.ReadTimeout("total timeout")
|
|
487
|
+
except httpx.HTTPError as exc:
|
|
488
|
+
failure = _transport_error(exc, "before any audio")
|
|
489
|
+
raise failure or start.ended()
|
|
490
|
+
|
|
491
|
+
@staticmethod
|
|
492
|
+
def _read_voices(response: httpx.Response, deadline: float | None) -> list[Voice]:
|
|
493
|
+
failure: BakbakError | None = None
|
|
494
|
+
content = b""
|
|
495
|
+
try:
|
|
496
|
+
content = response.read()
|
|
497
|
+
except httpx.HTTPError as exc:
|
|
498
|
+
failure = _transport_error(exc, "while reading the voice list")
|
|
499
|
+
if failure is not None:
|
|
500
|
+
raise failure
|
|
501
|
+
return _voices(response, content)
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
class AsyncAPIClient(_BaseClient):
|
|
505
|
+
"""The asynchronous HTTP core."""
|
|
506
|
+
|
|
507
|
+
_client: httpx.AsyncClient
|
|
508
|
+
_owns_client: bool
|
|
509
|
+
_sleep: Callable[[float], Awaitable[None]]
|
|
510
|
+
|
|
511
|
+
def __init__(
|
|
512
|
+
self,
|
|
513
|
+
*,
|
|
514
|
+
api_key: str | None,
|
|
515
|
+
base_url: str | None,
|
|
516
|
+
timeout: TimeoutLike | NotGiven,
|
|
517
|
+
max_retries: int,
|
|
518
|
+
default_headers: Mapping[str, str] | None,
|
|
519
|
+
http_client: httpx.AsyncClient | None,
|
|
520
|
+
) -> None:
|
|
521
|
+
super().__init__(
|
|
522
|
+
api_key=api_key,
|
|
523
|
+
base_url=base_url,
|
|
524
|
+
timeout=timeout,
|
|
525
|
+
max_retries=max_retries,
|
|
526
|
+
default_headers=default_headers,
|
|
527
|
+
)
|
|
528
|
+
self._owns_client = http_client is None
|
|
529
|
+
self._client = http_client or httpx.AsyncClient(
|
|
530
|
+
limits=httpx.Limits(keepalive_expiry=KEEPALIVE_EXPIRY),
|
|
531
|
+
follow_redirects=False,
|
|
532
|
+
)
|
|
533
|
+
self._sleep = asyncio.sleep
|
|
534
|
+
|
|
535
|
+
async def close(self) -> None:
|
|
536
|
+
"""Close the connection pool, unless it was passed in as ``http_client``."""
|
|
537
|
+
if self._owns_client:
|
|
538
|
+
await self._client.aclose()
|
|
539
|
+
|
|
540
|
+
async def _request(
|
|
541
|
+
self,
|
|
542
|
+
method: str,
|
|
543
|
+
path: str,
|
|
544
|
+
*,
|
|
545
|
+
body: bytes | None,
|
|
546
|
+
accept: str,
|
|
547
|
+
options: CallOptions,
|
|
548
|
+
handle: Callable[[httpx.Response, float | None], Awaitable[T]],
|
|
549
|
+
) -> tuple[T, httpx.Response, int]:
|
|
550
|
+
headers = self._headers(options, accept=accept, has_body=body is not None)
|
|
551
|
+
deadline = self._deadline(options)
|
|
552
|
+
url = self.base_url + path
|
|
553
|
+
retries = 0
|
|
554
|
+
while True:
|
|
555
|
+
retry_after: str | None = None
|
|
556
|
+
started = time.monotonic()
|
|
557
|
+
logger.debug("%s %s (attempt %d)", method, path, retries + 1)
|
|
558
|
+
try:
|
|
559
|
+
request = self._client.build_request(
|
|
560
|
+
method, url, headers=headers, content=body,
|
|
561
|
+
timeout=_httpx_timeout(options.timeout, deadline),
|
|
562
|
+
) # fmt: skip
|
|
563
|
+
# Never follow a redirect, even with a caller's http_client:
|
|
564
|
+
# it would carry X-API-Key to another origin (§8).
|
|
565
|
+
response = await self._client.send(request, stream=True, follow_redirects=False)
|
|
566
|
+
except httpx.HTTPError as exc:
|
|
567
|
+
error: BakbakError = _transport_error(exc, "before any response")
|
|
568
|
+
else:
|
|
569
|
+
logger.debug(
|
|
570
|
+
"%s %s -> %d (request_id %s) in %.0f ms",
|
|
571
|
+
method, path, response.status_code,
|
|
572
|
+
response.headers.get("x-request-id"), (time.monotonic() - started) * 1000,
|
|
573
|
+
) # fmt: skip
|
|
574
|
+
try:
|
|
575
|
+
if not 200 <= response.status_code < 300:
|
|
576
|
+
retry_after = response.headers.get("retry-after")
|
|
577
|
+
try:
|
|
578
|
+
content = await response.aread()
|
|
579
|
+
except httpx.HTTPError:
|
|
580
|
+
content = None
|
|
581
|
+
raise self._status_error(response, content)
|
|
582
|
+
return await handle(response, deadline), response, retries
|
|
583
|
+
except (APIStatusError, APIConnectionError, StreamInterruptedError) as exc:
|
|
584
|
+
await response.aclose()
|
|
585
|
+
error = exc
|
|
586
|
+
except BaseException:
|
|
587
|
+
await response.aclose()
|
|
588
|
+
raise
|
|
589
|
+
wait = self._next_wait(error, retries, options, deadline, retry_after)
|
|
590
|
+
if wait is None:
|
|
591
|
+
raise error
|
|
592
|
+
retries += 1
|
|
593
|
+
logger.debug("retrying %s %s in %.2f s after: %s", method, path, wait, error.message)
|
|
594
|
+
await self._sleep(wait)
|
|
595
|
+
|
|
596
|
+
@staticmethod
|
|
597
|
+
async def _read_audio(response: httpx.Response, deadline: float | None) -> Audio:
|
|
598
|
+
parts: list[bytes] = []
|
|
599
|
+
received = 0
|
|
600
|
+
failure: BakbakError | None = None
|
|
601
|
+
try:
|
|
602
|
+
async for piece in response.aiter_bytes():
|
|
603
|
+
parts.append(piece)
|
|
604
|
+
received += len(piece)
|
|
605
|
+
if _past(deadline):
|
|
606
|
+
raise httpx.ReadTimeout("total timeout")
|
|
607
|
+
except httpx.HTTPError as exc:
|
|
608
|
+
failure = _body_failure(exc, received, response)
|
|
609
|
+
finally:
|
|
610
|
+
await response.aclose()
|
|
611
|
+
if failure is not None:
|
|
612
|
+
raise failure # outside the except block: no httpx exception in its chain
|
|
613
|
+
return _audio(response, b"".join(parts))
|
|
614
|
+
|
|
615
|
+
@staticmethod
|
|
616
|
+
async def _start_stream(
|
|
617
|
+
response: httpx.Response, deadline: float | None
|
|
618
|
+
) -> OpenStream[AsyncIterator[bytes]]:
|
|
619
|
+
start = _StreamStart(response)
|
|
620
|
+
raw = response.aiter_bytes()
|
|
621
|
+
failure: BakbakError | None = None
|
|
622
|
+
try:
|
|
623
|
+
async for piece in raw:
|
|
624
|
+
if start.feed(piece):
|
|
625
|
+
return OpenStream(response, start.pending, start.decoder, raw, deadline)
|
|
626
|
+
if _past(deadline):
|
|
627
|
+
raise httpx.ReadTimeout("total timeout")
|
|
628
|
+
except httpx.HTTPError as exc:
|
|
629
|
+
failure = _transport_error(exc, "before any audio")
|
|
630
|
+
raise failure or start.ended()
|
|
631
|
+
|
|
632
|
+
@staticmethod
|
|
633
|
+
async def _read_voices(response: httpx.Response, deadline: float | None) -> list[Voice]:
|
|
634
|
+
failure: BakbakError | None = None
|
|
635
|
+
content = b""
|
|
636
|
+
try:
|
|
637
|
+
content = await response.aread()
|
|
638
|
+
except httpx.HTTPError as exc:
|
|
639
|
+
failure = _transport_error(exc, "while reading the voice list")
|
|
640
|
+
if failure is not None:
|
|
641
|
+
raise failure
|
|
642
|
+
return _voices(response, content)
|