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/_models.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Response models: ``Audio`` and ``AudioChunk``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
from typing_extensions import override
|
|
9
|
+
|
|
10
|
+
from .audio import to_wav
|
|
11
|
+
|
|
12
|
+
__all__ = ["Audio", "AudioChunk"]
|
|
13
|
+
|
|
14
|
+
_WAV_TYPES = frozenset({"audio/wav", "audio/wave", "audio/x-wav", "audio/vnd.wave"})
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _media_type(content_type: str | None) -> str:
|
|
18
|
+
return (content_type or "").split(";", 1)[0].strip().lower()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(slots=True)
|
|
22
|
+
class Audio:
|
|
23
|
+
"""A whole synthesized file, from ``client.tts.generate()``.
|
|
24
|
+
|
|
25
|
+
Attributes:
|
|
26
|
+
data: the audio bytes exactly as received.
|
|
27
|
+
request_id: ``X-Request-Id``; quote it to support.
|
|
28
|
+
content_type: ``audio/wav``, ``audio/mpeg``, ``audio/pcm``,
|
|
29
|
+
``audio/basic`` (raw mu-law) or ``application/octet-stream``
|
|
30
|
+
(raw A-law).
|
|
31
|
+
encoding: ``X-Audio-Format`` (the encoding, or ``mp3``), if present.
|
|
32
|
+
sample_rate: ``X-Audio-Sample-Rate``, if present.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
data: bytes = field(repr=False)
|
|
36
|
+
request_id: str | None
|
|
37
|
+
content_type: str | None
|
|
38
|
+
encoding: str | None
|
|
39
|
+
sample_rate: int | None
|
|
40
|
+
|
|
41
|
+
def save(self, path: str | os.PathLike[str]) -> None:
|
|
42
|
+
"""Write exactly the bytes received to ``path``."""
|
|
43
|
+
with open(path, "wb") as f:
|
|
44
|
+
f.write(self.data)
|
|
45
|
+
|
|
46
|
+
def to_wav(self) -> bytes:
|
|
47
|
+
"""The audio as a WAV file.
|
|
48
|
+
|
|
49
|
+
WAV audio is returned unchanged; raw PCM, mu-law and A-law are wrapped
|
|
50
|
+
in a WAV header (see :func:`bakbak.audio.to_wav`).
|
|
51
|
+
|
|
52
|
+
Raises:
|
|
53
|
+
ValueError: for mp3, or raw audio whose encoding and sample rate
|
|
54
|
+
the response did not state.
|
|
55
|
+
"""
|
|
56
|
+
if _media_type(self.content_type) in _WAV_TYPES:
|
|
57
|
+
return self.data
|
|
58
|
+
if self.encoding is None or self.sample_rate is None:
|
|
59
|
+
raise ValueError(
|
|
60
|
+
"The response did not state the audio encoding and sample rate; "
|
|
61
|
+
"use bakbak.audio.to_wav(data, encoding, sample_rate)"
|
|
62
|
+
)
|
|
63
|
+
return to_wav(self.data, self.encoding, self.sample_rate)
|
|
64
|
+
|
|
65
|
+
@override
|
|
66
|
+
def __repr__(self) -> str:
|
|
67
|
+
return (
|
|
68
|
+
f"Audio(bytes={len(self.data)}, content_type={self.content_type!r}, "
|
|
69
|
+
f"encoding={self.encoding!r}, sample_rate={self.sample_rate!r}, "
|
|
70
|
+
f"request_id={self.request_id!r})"
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(slots=True)
|
|
75
|
+
class AudioChunk:
|
|
76
|
+
"""One piece of a streamed response.
|
|
77
|
+
|
|
78
|
+
Attributes:
|
|
79
|
+
audio: the decoded audio. It always holds whole samples.
|
|
80
|
+
step_time: the model's time for this step in seconds, when sent.
|
|
81
|
+
request_id: the request's id.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
audio: bytes
|
|
85
|
+
step_time: float | None = None
|
|
86
|
+
request_id: str | None = None
|
|
87
|
+
|
|
88
|
+
@override
|
|
89
|
+
def __repr__(self) -> str:
|
|
90
|
+
return (
|
|
91
|
+
f"AudioChunk(audio=<{len(self.audio)} bytes>, step_time={self.step_time!r}, "
|
|
92
|
+
f"request_id={self.request_id!r})"
|
|
93
|
+
)
|
bakbak/_response.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""``RawResponse``: what ``with_raw_response`` methods return."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
from typing_extensions import override
|
|
9
|
+
|
|
10
|
+
__all__ = ["RawResponse"]
|
|
11
|
+
|
|
12
|
+
T = TypeVar("T")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RawResponse(Generic[T]):
|
|
16
|
+
"""The HTTP response behind a call, plus its parsed result.
|
|
17
|
+
|
|
18
|
+
Attributes:
|
|
19
|
+
http_response: the ``httpx.Response`` of the attempt that succeeded.
|
|
20
|
+
retries_taken: how many retries the call needed.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
__slots__ = ("_parsed", "http_response", "retries_taken")
|
|
24
|
+
|
|
25
|
+
def __init__(self, http_response: httpx.Response, parsed: T, retries_taken: int) -> None:
|
|
26
|
+
self.http_response = http_response
|
|
27
|
+
self.retries_taken = retries_taken
|
|
28
|
+
self._parsed = parsed
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def headers(self) -> httpx.Headers:
|
|
32
|
+
return self.http_response.headers
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def status_code(self) -> int:
|
|
36
|
+
return self.http_response.status_code
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def request_id(self) -> str | None:
|
|
40
|
+
return self.http_response.headers.get("x-request-id")
|
|
41
|
+
|
|
42
|
+
def parse(self) -> T:
|
|
43
|
+
"""The result the plain method would have returned."""
|
|
44
|
+
return self._parsed
|
|
45
|
+
|
|
46
|
+
@override
|
|
47
|
+
def __repr__(self) -> str:
|
|
48
|
+
return (
|
|
49
|
+
f"RawResponse(status_code={self.status_code}, request_id={self.request_id!r}, "
|
|
50
|
+
f"retries_taken={self.retries_taken})"
|
|
51
|
+
)
|
bakbak/_retry.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""How long to wait before a retry (BEHAVIOR.md §4.3)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import email.utils
|
|
6
|
+
import math
|
|
7
|
+
import random
|
|
8
|
+
from collections.abc import Callable
|
|
9
|
+
from datetime import datetime, timezone
|
|
10
|
+
|
|
11
|
+
from ._constants import INITIAL_RETRY_DELAY, MAX_RETRY_AFTER, MAX_RETRY_DELAY, RETRY_JITTER
|
|
12
|
+
|
|
13
|
+
__all__ = ["backoff_delay", "parse_retry_after", "retry_delay"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def backoff_delay(retry: int, rand: Callable[[], float] = random.random) -> float:
|
|
17
|
+
"""Wait before retry ``retry`` (1-based) when the server gave no Retry-After:
|
|
18
|
+
``min(0.5 * 2^(n-1), 8) * (1 - 0.25 * r)`` with ``r`` uniform in [0, 1)."""
|
|
19
|
+
base = min(INITIAL_RETRY_DELAY * 2 ** (retry - 1), MAX_RETRY_DELAY)
|
|
20
|
+
return base * (1 - RETRY_JITTER * rand())
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_retry_after(value: str | None, now: datetime | None = None) -> float | None:
|
|
24
|
+
"""Seconds to wait from a ``Retry-After`` header, capped at 60 s.
|
|
25
|
+
|
|
26
|
+
Accepts a number of seconds or an HTTP date; returns ``None`` when the
|
|
27
|
+
header is absent or unreadable.
|
|
28
|
+
"""
|
|
29
|
+
if value is None:
|
|
30
|
+
return None
|
|
31
|
+
text = value.strip()
|
|
32
|
+
if not text:
|
|
33
|
+
return None
|
|
34
|
+
try:
|
|
35
|
+
seconds = float(text)
|
|
36
|
+
except ValueError:
|
|
37
|
+
try:
|
|
38
|
+
when = email.utils.parsedate_to_datetime(text)
|
|
39
|
+
except (TypeError, ValueError, IndexError):
|
|
40
|
+
return None
|
|
41
|
+
if when.tzinfo is None:
|
|
42
|
+
when = when.replace(tzinfo=timezone.utc)
|
|
43
|
+
seconds = (when - (now or datetime.now(timezone.utc))).total_seconds()
|
|
44
|
+
if math.isnan(seconds):
|
|
45
|
+
return None
|
|
46
|
+
return min(max(seconds, 0.0), MAX_RETRY_AFTER)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def retry_delay(retry: int, retry_after: str | None) -> float:
|
|
50
|
+
"""The wait before retry ``retry``: Retry-After if usable, else backoff."""
|
|
51
|
+
delay = parse_retry_after(retry_after)
|
|
52
|
+
return backoff_delay(retry) if delay is None else delay
|
bakbak/_sse.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""A Server-Sent Events decoder (BEHAVIOR.md §5.1).
|
|
2
|
+
|
|
3
|
+
It accepts LF and CRLF line ends, ignores comments and the ``id:`` and
|
|
4
|
+
``retry:`` fields, joins multi-line ``data:`` with ``\\n`` and dispatches an
|
|
5
|
+
event on a blank line. It has no line-length limit: one chunk's base64 can be
|
|
6
|
+
large.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
__all__ = ["SSEDecoder"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class SSEDecoder:
|
|
15
|
+
"""Turns response bytes into ``(event, data)`` pairs."""
|
|
16
|
+
|
|
17
|
+
__slots__ = ("_buf", "_data", "_event", "_scanned")
|
|
18
|
+
|
|
19
|
+
def __init__(self) -> None:
|
|
20
|
+
self._buf = bytearray()
|
|
21
|
+
self._scanned = 0 # bytes of _buf known to hold no line end
|
|
22
|
+
self._data: list[str] = []
|
|
23
|
+
self._event = ""
|
|
24
|
+
|
|
25
|
+
def feed(self, chunk: bytes) -> list[tuple[str, str]]:
|
|
26
|
+
"""Add bytes; return the events they completed."""
|
|
27
|
+
buf = self._buf
|
|
28
|
+
buf += chunk
|
|
29
|
+
events: list[tuple[str, str]] = []
|
|
30
|
+
pos = 0
|
|
31
|
+
search = self._scanned
|
|
32
|
+
while True:
|
|
33
|
+
nl = buf.find(b"\n", search)
|
|
34
|
+
if nl < 0:
|
|
35
|
+
break
|
|
36
|
+
end = nl - 1 if nl > pos and buf[nl - 1] == 0x0D else nl
|
|
37
|
+
event = self._line(bytes(buf[pos:end]))
|
|
38
|
+
if event is not None:
|
|
39
|
+
events.append(event)
|
|
40
|
+
pos = search = nl + 1
|
|
41
|
+
if pos:
|
|
42
|
+
del buf[:pos]
|
|
43
|
+
self._scanned = len(buf)
|
|
44
|
+
return events
|
|
45
|
+
|
|
46
|
+
def _line(self, line: bytes) -> tuple[str, str] | None:
|
|
47
|
+
if not line:
|
|
48
|
+
if not self._data:
|
|
49
|
+
self._event = ""
|
|
50
|
+
return None
|
|
51
|
+
event = (self._event, "\n".join(self._data))
|
|
52
|
+
self._data = []
|
|
53
|
+
self._event = ""
|
|
54
|
+
return event
|
|
55
|
+
if line[0] == 0x3A: # ":" starts a comment
|
|
56
|
+
return None
|
|
57
|
+
colon = line.find(b":")
|
|
58
|
+
if colon < 0:
|
|
59
|
+
name, value = line, b""
|
|
60
|
+
else:
|
|
61
|
+
name, value = line[:colon], line[colon + 1 :]
|
|
62
|
+
if value[:1] == b" ":
|
|
63
|
+
value = value[1:]
|
|
64
|
+
if name == b"data":
|
|
65
|
+
self._data.append(value.decode("utf-8", errors="replace"))
|
|
66
|
+
elif name == b"event":
|
|
67
|
+
self._event = value.decode("utf-8", errors="replace")
|
|
68
|
+
return None
|
bakbak/_streaming.py
ADDED
|
@@ -0,0 +1,432 @@
|
|
|
1
|
+
"""SSE stream results: ``AudioStream`` and ``AsyncAudioStream``.
|
|
2
|
+
|
|
3
|
+
A stream is lazy: the request is sent when the stream is entered (``with``) or
|
|
4
|
+
first iterated. Before any audio, failures are retried by the client's retry
|
|
5
|
+
loop; once audio has been handed out, a failure raises
|
|
6
|
+
``StreamInterruptedError`` and is never retried (BEHAVIOR.md §4.1).
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import binascii
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import time
|
|
15
|
+
from collections import deque
|
|
16
|
+
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from types import TracebackType
|
|
19
|
+
from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
20
|
+
|
|
21
|
+
import httpx
|
|
22
|
+
from typing_extensions import Self
|
|
23
|
+
|
|
24
|
+
from ._exceptions import BakbakError, make_interrupted_error
|
|
25
|
+
from ._models import AudioChunk
|
|
26
|
+
from ._sse import SSEDecoder
|
|
27
|
+
from ._utils import as_mapping, logger
|
|
28
|
+
|
|
29
|
+
if TYPE_CHECKING:
|
|
30
|
+
from .types import OutputFormat
|
|
31
|
+
|
|
32
|
+
__all__ = ["AsyncAudioStream", "AudioStream"]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def parse_events(decoder: SSEDecoder, chunk: bytes) -> list[Mapping[str, object]]:
|
|
36
|
+
"""Decode the JSON payloads of the events completed by ``chunk``.
|
|
37
|
+
|
|
38
|
+
The payload's ``type`` is authoritative; the ``event:`` name only fills it
|
|
39
|
+
in when the payload has none. Payloads that are not JSON objects are
|
|
40
|
+
ignored, as are unknown types further up.
|
|
41
|
+
"""
|
|
42
|
+
out: list[Mapping[str, object]] = []
|
|
43
|
+
for name, data in decoder.feed(chunk):
|
|
44
|
+
try:
|
|
45
|
+
payload = as_mapping(json.loads(data))
|
|
46
|
+
except ValueError:
|
|
47
|
+
logger.debug("ignoring an SSE event whose data is not JSON (%d bytes)", len(data))
|
|
48
|
+
continue
|
|
49
|
+
if payload is None:
|
|
50
|
+
continue
|
|
51
|
+
if "type" not in payload and name:
|
|
52
|
+
payload = {**payload, "type": name}
|
|
53
|
+
out.append(payload)
|
|
54
|
+
return out
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def decode_audio(event: Mapping[str, object]) -> bytes:
|
|
58
|
+
"""The audio of a ``chunk`` event, base64-decoded exactly once."""
|
|
59
|
+
data = event.get("data")
|
|
60
|
+
if not isinstance(data, str) or not data:
|
|
61
|
+
return b""
|
|
62
|
+
return binascii.a2b_base64(data)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def step_time(event: Mapping[str, object]) -> float | None:
|
|
66
|
+
value = event.get("step_time")
|
|
67
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
68
|
+
return float(value)
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SampleAligner:
|
|
73
|
+
"""Holds back a partial sample so chunks never split one (§5.2)."""
|
|
74
|
+
|
|
75
|
+
__slots__ = ("_carry", "_width")
|
|
76
|
+
|
|
77
|
+
def __init__(self, width: int) -> None:
|
|
78
|
+
self._width = width
|
|
79
|
+
self._carry = b""
|
|
80
|
+
|
|
81
|
+
def feed(self, audio: bytes) -> bytes:
|
|
82
|
+
if self._width <= 1:
|
|
83
|
+
return audio
|
|
84
|
+
if self._carry:
|
|
85
|
+
audio = self._carry + audio
|
|
86
|
+
cut = len(audio) - len(audio) % self._width
|
|
87
|
+
self._carry = audio[cut:]
|
|
88
|
+
return audio[:cut] if self._carry else audio
|
|
89
|
+
|
|
90
|
+
def leftover(self) -> int:
|
|
91
|
+
"""Bytes of an incomplete trailing sample, which are dropped."""
|
|
92
|
+
return len(self._carry)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
RawT = TypeVar("RawT")
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(slots=True)
|
|
99
|
+
class OpenStream(Generic[RawT]):
|
|
100
|
+
"""A stream whose first audio (or its ``done``) has arrived.
|
|
101
|
+
|
|
102
|
+
Attributes:
|
|
103
|
+
response: the open response.
|
|
104
|
+
pending: events already parsed and not yet handled, starting with the
|
|
105
|
+
first audio event, each with its audio if already decoded.
|
|
106
|
+
decoder: the SSE decoder, holding any partial event.
|
|
107
|
+
raw: the response's byte iterator, to continue reading from.
|
|
108
|
+
deadline: when the call's total timeout ends, if it has one.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
response: httpx.Response
|
|
112
|
+
pending: deque[tuple[Mapping[str, object], bytes | None]]
|
|
113
|
+
decoder: SSEDecoder
|
|
114
|
+
raw: RawT
|
|
115
|
+
deadline: float | None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _header_int(headers: httpx.Headers, name: str) -> int | None:
|
|
119
|
+
value = headers.get(name)
|
|
120
|
+
try:
|
|
121
|
+
return int(value) if value is not None else None
|
|
122
|
+
except ValueError:
|
|
123
|
+
return None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class _StreamBase:
|
|
127
|
+
__slots__ = (
|
|
128
|
+
"_aligner",
|
|
129
|
+
"_closed",
|
|
130
|
+
"_consumed",
|
|
131
|
+
"_deadline",
|
|
132
|
+
"_format",
|
|
133
|
+
"_open",
|
|
134
|
+
"audio_bytes",
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def __init__(self, output_format: OutputFormat | None, sample_width: int) -> None:
|
|
138
|
+
self._format = output_format
|
|
139
|
+
self._aligner = SampleAligner(sample_width)
|
|
140
|
+
self._open: OpenStream[Any] | None = None
|
|
141
|
+
self._consumed = False
|
|
142
|
+
self._closed = False
|
|
143
|
+
self._deadline: float | None = None
|
|
144
|
+
self.audio_bytes = 0
|
|
145
|
+
"""Audio bytes handed out so far."""
|
|
146
|
+
|
|
147
|
+
@property
|
|
148
|
+
def response(self) -> httpx.Response | None:
|
|
149
|
+
"""The HTTP response, once its headers have arrived."""
|
|
150
|
+
return self._open.response if self._open is not None else None
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def request_id(self) -> str | None:
|
|
154
|
+
"""``X-Request-Id``, once the response headers have arrived."""
|
|
155
|
+
return self._open.response.headers.get("x-request-id") if self._open else None
|
|
156
|
+
|
|
157
|
+
@property
|
|
158
|
+
def content_type(self) -> str | None:
|
|
159
|
+
return self._open.response.headers.get("content-type") if self._open else None
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def encoding(self) -> str | None:
|
|
163
|
+
"""``X-Audio-Format``, else the requested ``output_format`` encoding."""
|
|
164
|
+
if self._open is not None:
|
|
165
|
+
value = self._open.response.headers.get("x-audio-format")
|
|
166
|
+
if value:
|
|
167
|
+
return value
|
|
168
|
+
return self._format.get("encoding") if self._format else None
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def sample_rate(self) -> int | None:
|
|
172
|
+
"""``X-Audio-Sample-Rate``, else the requested sample rate."""
|
|
173
|
+
if self._open is not None:
|
|
174
|
+
value = _header_int(self._open.response.headers, "x-audio-sample-rate")
|
|
175
|
+
if value is not None:
|
|
176
|
+
return value
|
|
177
|
+
return self._format.get("sample_rate") if self._format else None
|
|
178
|
+
|
|
179
|
+
def _begin(self) -> None:
|
|
180
|
+
if self._consumed:
|
|
181
|
+
raise BakbakError("This stream has already been read; streams can be read once.")
|
|
182
|
+
if self._closed:
|
|
183
|
+
raise BakbakError("This stream is closed.")
|
|
184
|
+
self._consumed = True
|
|
185
|
+
|
|
186
|
+
def _handle(
|
|
187
|
+
self, event: Mapping[str, object], decoded: bytes | None = None
|
|
188
|
+
) -> AudioChunk | bool:
|
|
189
|
+
"""An ``AudioChunk`` to hand out, ``True`` at the end, ``False`` to skip."""
|
|
190
|
+
kind = event.get("type")
|
|
191
|
+
if kind == "chunk":
|
|
192
|
+
if decoded is None:
|
|
193
|
+
try:
|
|
194
|
+
decoded = decode_audio(event)
|
|
195
|
+
except (binascii.Error, ValueError):
|
|
196
|
+
# The stream breaks here (§6.4 note); never a raw binascii.Error.
|
|
197
|
+
raise make_interrupted_error(
|
|
198
|
+
None,
|
|
199
|
+
audio_bytes=self.audio_bytes,
|
|
200
|
+
header_request_id=self.request_id,
|
|
201
|
+
default_message="The server sent audio that is not valid base64.",
|
|
202
|
+
) from None
|
|
203
|
+
audio = self._aligner.feed(decoded)
|
|
204
|
+
if not audio:
|
|
205
|
+
return False
|
|
206
|
+
self.audio_bytes += len(audio)
|
|
207
|
+
return AudioChunk(audio, step_time(event), self.request_id)
|
|
208
|
+
if kind == "done":
|
|
209
|
+
if self._aligner.leftover():
|
|
210
|
+
logger.debug(
|
|
211
|
+
"dropping %d bytes of an incomplete last sample", self._aligner.leftover()
|
|
212
|
+
)
|
|
213
|
+
return True
|
|
214
|
+
if kind == "error":
|
|
215
|
+
raise make_interrupted_error(
|
|
216
|
+
event, audio_bytes=self.audio_bytes, header_request_id=self.request_id
|
|
217
|
+
)
|
|
218
|
+
return False
|
|
219
|
+
|
|
220
|
+
def _check_deadline(self) -> None:
|
|
221
|
+
if self._deadline is not None and time.monotonic() > self._deadline:
|
|
222
|
+
raise make_interrupted_error(
|
|
223
|
+
None,
|
|
224
|
+
audio_bytes=self.audio_bytes,
|
|
225
|
+
header_request_id=self.request_id,
|
|
226
|
+
default_message="The total timeout elapsed before the stream finished.",
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
def _broken(self, exc: Exception) -> BakbakError:
|
|
230
|
+
if isinstance(exc, httpx.TimeoutException):
|
|
231
|
+
message = "No audio arrived within the read timeout."
|
|
232
|
+
else:
|
|
233
|
+
message = "The connection broke before the stream finished."
|
|
234
|
+
return make_interrupted_error(
|
|
235
|
+
None,
|
|
236
|
+
audio_bytes=self.audio_bytes,
|
|
237
|
+
header_request_id=self.request_id,
|
|
238
|
+
default_message=message,
|
|
239
|
+
)
|
|
240
|
+
|
|
241
|
+
def _truncated(self) -> BakbakError:
|
|
242
|
+
return make_interrupted_error(
|
|
243
|
+
None, audio_bytes=self.audio_bytes, header_request_id=self.request_id
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
class AudioStream(_StreamBase):
|
|
248
|
+
"""The audio of ``client.tts.stream()``, as it is generated.
|
|
249
|
+
|
|
250
|
+
Iterate it for ``AudioChunk`` objects, or use ``iter_audio()``, ``read()``
|
|
251
|
+
or ``save()``. It can be read once. Use it as a context manager, or read
|
|
252
|
+
it to the end, so the connection is released.
|
|
253
|
+
|
|
254
|
+
``request_id``, ``content_type``, ``encoding`` and ``sample_rate`` are set
|
|
255
|
+
once the response headers have arrived (on ``with`` or the first chunk).
|
|
256
|
+
"""
|
|
257
|
+
|
|
258
|
+
__slots__ = ("_start",)
|
|
259
|
+
|
|
260
|
+
def __init__(
|
|
261
|
+
self,
|
|
262
|
+
start: Callable[[], OpenStream[Iterator[bytes]]],
|
|
263
|
+
*,
|
|
264
|
+
output_format: OutputFormat | None,
|
|
265
|
+
sample_width: int,
|
|
266
|
+
) -> None:
|
|
267
|
+
super().__init__(output_format, sample_width)
|
|
268
|
+
self._start = start
|
|
269
|
+
|
|
270
|
+
def _ensure_open(self) -> OpenStream[Iterator[bytes]]:
|
|
271
|
+
if self._open is None:
|
|
272
|
+
if self._closed:
|
|
273
|
+
raise BakbakError("This stream is closed.")
|
|
274
|
+
self._open = self._start()
|
|
275
|
+
self._deadline = self._open.deadline
|
|
276
|
+
return self._open
|
|
277
|
+
|
|
278
|
+
def __enter__(self) -> Self:
|
|
279
|
+
self._ensure_open()
|
|
280
|
+
return self
|
|
281
|
+
|
|
282
|
+
def __exit__(
|
|
283
|
+
self,
|
|
284
|
+
exc_type: type[BaseException] | None,
|
|
285
|
+
exc: BaseException | None,
|
|
286
|
+
tb: TracebackType | None,
|
|
287
|
+
) -> None:
|
|
288
|
+
self.close()
|
|
289
|
+
|
|
290
|
+
def __iter__(self) -> Iterator[AudioChunk]:
|
|
291
|
+
return self._chunks()
|
|
292
|
+
|
|
293
|
+
def _chunks(self) -> Iterator[AudioChunk]:
|
|
294
|
+
self._begin()
|
|
295
|
+
opened = self._ensure_open()
|
|
296
|
+
try:
|
|
297
|
+
while opened.pending:
|
|
298
|
+
result = self._handle(*opened.pending.popleft())
|
|
299
|
+
if result is True:
|
|
300
|
+
return
|
|
301
|
+
if result is not False:
|
|
302
|
+
yield result
|
|
303
|
+
failure: BakbakError | None = None
|
|
304
|
+
try:
|
|
305
|
+
for raw in opened.raw:
|
|
306
|
+
for event in parse_events(opened.decoder, raw):
|
|
307
|
+
result = self._handle(event)
|
|
308
|
+
if result is True:
|
|
309
|
+
return
|
|
310
|
+
if result is not False:
|
|
311
|
+
yield result
|
|
312
|
+
self._check_deadline()
|
|
313
|
+
except (httpx.TimeoutException, httpx.TransportError, httpx.StreamError) as exc:
|
|
314
|
+
failure = self._broken(exc)
|
|
315
|
+
# Raised outside the except block, so no httpx exception (which
|
|
316
|
+
# holds the request headers) is chained to it.
|
|
317
|
+
raise failure or self._truncated()
|
|
318
|
+
finally:
|
|
319
|
+
self.close()
|
|
320
|
+
|
|
321
|
+
def iter_audio(self) -> Iterator[bytes]:
|
|
322
|
+
"""Iterate over the audio bytes only."""
|
|
323
|
+
for chunk in self:
|
|
324
|
+
yield chunk.audio
|
|
325
|
+
|
|
326
|
+
def read(self) -> bytes:
|
|
327
|
+
"""Read the whole stream and return its audio."""
|
|
328
|
+
return b"".join(self.iter_audio())
|
|
329
|
+
|
|
330
|
+
def save(self, path: str | os.PathLike[str]) -> None:
|
|
331
|
+
"""Write the audio to ``path`` as it arrives, exactly as received."""
|
|
332
|
+
with open(path, "wb") as f:
|
|
333
|
+
for audio in self.iter_audio():
|
|
334
|
+
f.write(audio)
|
|
335
|
+
|
|
336
|
+
def close(self) -> None:
|
|
337
|
+
"""Release the connection. Safe to call more than once."""
|
|
338
|
+
self._closed = True
|
|
339
|
+
if self._open is not None:
|
|
340
|
+
self._open.response.close()
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
class AsyncAudioStream(_StreamBase):
|
|
344
|
+
"""The audio of ``client.tts.stream()`` on ``AsyncBakbak``.
|
|
345
|
+
|
|
346
|
+
The async twin of :class:`AudioStream`: ``async for``, ``async with``,
|
|
347
|
+
and awaitable ``read()``, ``save()`` and ``close()``.
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
__slots__ = ("_start",)
|
|
351
|
+
|
|
352
|
+
def __init__(
|
|
353
|
+
self,
|
|
354
|
+
start: Callable[[], Awaitable[OpenStream[AsyncIterator[bytes]]]],
|
|
355
|
+
*,
|
|
356
|
+
output_format: OutputFormat | None,
|
|
357
|
+
sample_width: int,
|
|
358
|
+
) -> None:
|
|
359
|
+
super().__init__(output_format, sample_width)
|
|
360
|
+
self._start = start
|
|
361
|
+
|
|
362
|
+
async def _ensure_open(self) -> OpenStream[AsyncIterator[bytes]]:
|
|
363
|
+
if self._open is None:
|
|
364
|
+
if self._closed:
|
|
365
|
+
raise BakbakError("This stream is closed.")
|
|
366
|
+
self._open = await self._start()
|
|
367
|
+
self._deadline = self._open.deadline
|
|
368
|
+
return self._open
|
|
369
|
+
|
|
370
|
+
async def __aenter__(self) -> Self:
|
|
371
|
+
await self._ensure_open()
|
|
372
|
+
return self
|
|
373
|
+
|
|
374
|
+
async def __aexit__(
|
|
375
|
+
self,
|
|
376
|
+
exc_type: type[BaseException] | None,
|
|
377
|
+
exc: BaseException | None,
|
|
378
|
+
tb: TracebackType | None,
|
|
379
|
+
) -> None:
|
|
380
|
+
await self.close()
|
|
381
|
+
|
|
382
|
+
def __aiter__(self) -> AsyncIterator[AudioChunk]:
|
|
383
|
+
return self._chunks()
|
|
384
|
+
|
|
385
|
+
async def _chunks(self) -> AsyncIterator[AudioChunk]:
|
|
386
|
+
self._begin()
|
|
387
|
+
opened = await self._ensure_open()
|
|
388
|
+
try:
|
|
389
|
+
while opened.pending:
|
|
390
|
+
result = self._handle(*opened.pending.popleft())
|
|
391
|
+
if result is True:
|
|
392
|
+
return
|
|
393
|
+
if result is not False:
|
|
394
|
+
yield result
|
|
395
|
+
failure: BakbakError | None = None
|
|
396
|
+
try:
|
|
397
|
+
async for raw in opened.raw:
|
|
398
|
+
for event in parse_events(opened.decoder, raw):
|
|
399
|
+
result = self._handle(event)
|
|
400
|
+
if result is True:
|
|
401
|
+
return
|
|
402
|
+
if result is not False:
|
|
403
|
+
yield result
|
|
404
|
+
self._check_deadline()
|
|
405
|
+
except (httpx.TimeoutException, httpx.TransportError, httpx.StreamError) as exc:
|
|
406
|
+
failure = self._broken(exc)
|
|
407
|
+
# Raised outside the except block, so no httpx exception (which
|
|
408
|
+
# holds the request headers) is chained to it.
|
|
409
|
+
raise failure or self._truncated()
|
|
410
|
+
finally:
|
|
411
|
+
await self.close()
|
|
412
|
+
|
|
413
|
+
async def iter_audio(self) -> AsyncIterator[bytes]:
|
|
414
|
+
"""Iterate over the audio bytes only."""
|
|
415
|
+
async for chunk in self:
|
|
416
|
+
yield chunk.audio
|
|
417
|
+
|
|
418
|
+
async def read(self) -> bytes:
|
|
419
|
+
"""Read the whole stream and return its audio."""
|
|
420
|
+
return b"".join([audio async for audio in self.iter_audio()])
|
|
421
|
+
|
|
422
|
+
async def save(self, path: str | os.PathLike[str]) -> None:
|
|
423
|
+
"""Write the audio to ``path`` as it arrives, exactly as received."""
|
|
424
|
+
with open(path, "wb") as f: # noqa: ASYNC230 - small sequential writes of local files
|
|
425
|
+
async for audio in self.iter_audio():
|
|
426
|
+
f.write(audio)
|
|
427
|
+
|
|
428
|
+
async def close(self) -> None:
|
|
429
|
+
"""Release the connection. Safe to call more than once."""
|
|
430
|
+
self._closed = True
|
|
431
|
+
if self._open is not None:
|
|
432
|
+
await self._open.response.aclose()
|