ringglabs 0.0.2__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.
Potentially problematic release.
This version of ringglabs might be problematic. Click here for more details.
- ringglabs/__init__.py +3 -0
- ringglabs/py.typed +1 -0
- ringglabs/stt/__init__.py +58 -0
- ringglabs/stt/_http.py +238 -0
- ringglabs/stt/_io.py +30 -0
- ringglabs/stt/_serialization.py +151 -0
- ringglabs/stt/_ws_async.py +152 -0
- ringglabs/stt/_ws_sync.py +156 -0
- ringglabs/stt/async_client.py +170 -0
- ringglabs/stt/client.py +170 -0
- ringglabs/stt/config.py +131 -0
- ringglabs/stt/enums.py +25 -0
- ringglabs/stt/errors.py +46 -0
- ringglabs/stt/models.py +156 -0
- ringglabs/stt/retry.py +64 -0
- ringglabs-0.0.2.dist-info/METADATA +375 -0
- ringglabs-0.0.2.dist-info/RECORD +20 -0
- ringglabs-0.0.2.dist-info/WHEEL +5 -0
- ringglabs-0.0.2.dist-info/licenses/LICENSE +21 -0
- ringglabs-0.0.2.dist-info/top_level.txt +1 -0
ringglabs/__init__.py
ADDED
ringglabs/py.typed
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""RinggLabs STT SDK public API."""
|
|
2
|
+
|
|
3
|
+
from .async_client import AsyncClient
|
|
4
|
+
from .client import Client
|
|
5
|
+
from .config import ClientConfig, TimeoutConfig
|
|
6
|
+
from .enums import Encoding, Language, Mode, VadState
|
|
7
|
+
from .errors import (
|
|
8
|
+
ApiError,
|
|
9
|
+
AuthenticationError,
|
|
10
|
+
ProtocolError,
|
|
11
|
+
RinggLabsError,
|
|
12
|
+
TimeoutError,
|
|
13
|
+
TransportError,
|
|
14
|
+
ValidationError,
|
|
15
|
+
)
|
|
16
|
+
from .models import (
|
|
17
|
+
AckEvent,
|
|
18
|
+
ErrorEvent,
|
|
19
|
+
FileSource,
|
|
20
|
+
PongEvent,
|
|
21
|
+
ReadyEvent,
|
|
22
|
+
RestTranscriptionResult,
|
|
23
|
+
StreamOptions,
|
|
24
|
+
TranscriptEvent,
|
|
25
|
+
TranscriptionOptions,
|
|
26
|
+
WsEvent,
|
|
27
|
+
)
|
|
28
|
+
from .retry import async_retry, retry
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"AckEvent",
|
|
32
|
+
"ApiError",
|
|
33
|
+
"AsyncClient",
|
|
34
|
+
"AuthenticationError",
|
|
35
|
+
"Client",
|
|
36
|
+
"ClientConfig",
|
|
37
|
+
"Encoding",
|
|
38
|
+
"ErrorEvent",
|
|
39
|
+
"FileSource",
|
|
40
|
+
"Language",
|
|
41
|
+
"Mode",
|
|
42
|
+
"PongEvent",
|
|
43
|
+
"ProtocolError",
|
|
44
|
+
"ReadyEvent",
|
|
45
|
+
"RestTranscriptionResult",
|
|
46
|
+
"RinggLabsError",
|
|
47
|
+
"StreamOptions",
|
|
48
|
+
"TimeoutConfig",
|
|
49
|
+
"TimeoutError",
|
|
50
|
+
"TranscriptEvent",
|
|
51
|
+
"TranscriptionOptions",
|
|
52
|
+
"TransportError",
|
|
53
|
+
"ValidationError",
|
|
54
|
+
"VadState",
|
|
55
|
+
"WsEvent",
|
|
56
|
+
"async_retry",
|
|
57
|
+
"retry",
|
|
58
|
+
]
|
ringglabs/stt/_http.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""REST transport implementations."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from ._serialization import parse_rest_result
|
|
11
|
+
from .config import ClientConfig
|
|
12
|
+
from .errors import (
|
|
13
|
+
ApiError,
|
|
14
|
+
AuthenticationError,
|
|
15
|
+
ProtocolError,
|
|
16
|
+
TimeoutError,
|
|
17
|
+
TransportError,
|
|
18
|
+
)
|
|
19
|
+
from .models import RestTranscriptionResult, TranscriptionOptions
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _to_wire(value: Any) -> str:
|
|
23
|
+
if isinstance(value, Enum):
|
|
24
|
+
return str(value.value)
|
|
25
|
+
return str(value)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _make_headers(config: ClientConfig, api_key: str | None) -> dict[str, str]:
|
|
29
|
+
headers = dict(config.default_headers or {})
|
|
30
|
+
if api_key:
|
|
31
|
+
headers["x-api-key"] = api_key
|
|
32
|
+
return headers
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _build_api_error(response: httpx.Response, payload: dict[str, Any] | None) -> ApiError:
|
|
36
|
+
detail = None
|
|
37
|
+
code = None
|
|
38
|
+
if payload is not None:
|
|
39
|
+
detail = payload.get("detail")
|
|
40
|
+
code = payload.get("code")
|
|
41
|
+
message = str(detail) if detail else (response.text.strip() or "request failed")
|
|
42
|
+
error_cls = AuthenticationError if response.status_code in {401, 402} else ApiError
|
|
43
|
+
return error_cls(
|
|
44
|
+
message=message,
|
|
45
|
+
status_code=response.status_code,
|
|
46
|
+
code=str(code) if code is not None else None,
|
|
47
|
+
payload=payload,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class AsyncHttpTransport:
|
|
52
|
+
"""Async HTTP transport for SDK REST methods."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, config: ClientConfig):
|
|
55
|
+
self._config = config
|
|
56
|
+
self._client: httpx.AsyncClient | None = None
|
|
57
|
+
|
|
58
|
+
async def open(self) -> None:
|
|
59
|
+
if self._client is None:
|
|
60
|
+
self._client = httpx.AsyncClient(
|
|
61
|
+
timeout=self._config.timeout.as_httpx_timeout(),
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
async def close(self) -> None:
|
|
65
|
+
if self._client is not None:
|
|
66
|
+
await self._client.aclose()
|
|
67
|
+
self._client = None
|
|
68
|
+
|
|
69
|
+
async def transcribe_bytes(
|
|
70
|
+
self,
|
|
71
|
+
audio: bytes,
|
|
72
|
+
options: TranscriptionOptions,
|
|
73
|
+
*,
|
|
74
|
+
api_key_override: str | None = None,
|
|
75
|
+
) -> RestTranscriptionResult:
|
|
76
|
+
await self.open()
|
|
77
|
+
assert self._client is not None
|
|
78
|
+
language = _to_wire(options.language)
|
|
79
|
+
resolved_api_key = (
|
|
80
|
+
api_key_override if api_key_override is not None else options.api_key
|
|
81
|
+
)
|
|
82
|
+
headers = _make_headers(self._config, self._config.resolve_api_key(resolved_api_key))
|
|
83
|
+
|
|
84
|
+
files = {"file": (options.filename, audio, options.content_type)}
|
|
85
|
+
form = {
|
|
86
|
+
"language": language,
|
|
87
|
+
"enable_cap_punc": "true" if options.enable_cap_punc else "false",
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
response = await self._client.post(
|
|
92
|
+
self._config.rest_url,
|
|
93
|
+
headers=headers,
|
|
94
|
+
data=form,
|
|
95
|
+
files=files,
|
|
96
|
+
timeout=self._config.timeout.as_httpx_timeout(),
|
|
97
|
+
)
|
|
98
|
+
except httpx.TimeoutException as exc:
|
|
99
|
+
raise TimeoutError("REST transcription request timed out") from exc
|
|
100
|
+
except httpx.RequestError as exc:
|
|
101
|
+
raise TransportError(f"REST transcription request failed: {exc}") from exc
|
|
102
|
+
|
|
103
|
+
payload: dict[str, Any] | None = None
|
|
104
|
+
try:
|
|
105
|
+
parsed = response.json()
|
|
106
|
+
if isinstance(parsed, dict):
|
|
107
|
+
payload = parsed
|
|
108
|
+
except Exception:
|
|
109
|
+
payload = None
|
|
110
|
+
|
|
111
|
+
if response.status_code >= 400:
|
|
112
|
+
raise _build_api_error(response, payload)
|
|
113
|
+
if payload is None:
|
|
114
|
+
raise ProtocolError("REST response is not a JSON object")
|
|
115
|
+
return parse_rest_result(payload)
|
|
116
|
+
|
|
117
|
+
async def health_check(self, *, api_key_override: str | None = None) -> dict[str, Any]:
|
|
118
|
+
await self.open()
|
|
119
|
+
assert self._client is not None
|
|
120
|
+
headers = _make_headers(self._config, self._config.resolve_api_key(api_key_override))
|
|
121
|
+
try:
|
|
122
|
+
response = await self._client.get(
|
|
123
|
+
self._config.health_url,
|
|
124
|
+
headers=headers,
|
|
125
|
+
timeout=self._config.timeout.as_httpx_timeout(),
|
|
126
|
+
)
|
|
127
|
+
except httpx.TimeoutException as exc:
|
|
128
|
+
raise TimeoutError("Health check request timed out") from exc
|
|
129
|
+
except httpx.RequestError as exc:
|
|
130
|
+
raise TransportError(f"Health check request failed: {exc}") from exc
|
|
131
|
+
|
|
132
|
+
payload: dict[str, Any] | None = None
|
|
133
|
+
try:
|
|
134
|
+
parsed = response.json()
|
|
135
|
+
if isinstance(parsed, dict):
|
|
136
|
+
payload = parsed
|
|
137
|
+
except Exception:
|
|
138
|
+
payload = None
|
|
139
|
+
|
|
140
|
+
if response.status_code >= 400:
|
|
141
|
+
raise _build_api_error(response, payload)
|
|
142
|
+
if payload is None:
|
|
143
|
+
raise ProtocolError("Health response is not a JSON object")
|
|
144
|
+
return payload
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class SyncHttpTransport:
|
|
148
|
+
"""Sync HTTP transport for SDK REST methods."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, config: ClientConfig):
|
|
151
|
+
self._config = config
|
|
152
|
+
self._client: httpx.Client | None = None
|
|
153
|
+
|
|
154
|
+
def open(self) -> None:
|
|
155
|
+
if self._client is None:
|
|
156
|
+
self._client = httpx.Client(
|
|
157
|
+
timeout=self._config.timeout.as_httpx_timeout(),
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
def close(self) -> None:
|
|
161
|
+
if self._client is not None:
|
|
162
|
+
self._client.close()
|
|
163
|
+
self._client = None
|
|
164
|
+
|
|
165
|
+
def transcribe_bytes(
|
|
166
|
+
self,
|
|
167
|
+
audio: bytes,
|
|
168
|
+
options: TranscriptionOptions,
|
|
169
|
+
*,
|
|
170
|
+
api_key_override: str | None = None,
|
|
171
|
+
) -> RestTranscriptionResult:
|
|
172
|
+
self.open()
|
|
173
|
+
assert self._client is not None
|
|
174
|
+
language = _to_wire(options.language)
|
|
175
|
+
resolved_api_key = (
|
|
176
|
+
api_key_override if api_key_override is not None else options.api_key
|
|
177
|
+
)
|
|
178
|
+
headers = _make_headers(self._config, self._config.resolve_api_key(resolved_api_key))
|
|
179
|
+
files = {"file": (options.filename, audio, options.content_type)}
|
|
180
|
+
form = {
|
|
181
|
+
"language": language,
|
|
182
|
+
"enable_cap_punc": "true" if options.enable_cap_punc else "false",
|
|
183
|
+
}
|
|
184
|
+
try:
|
|
185
|
+
response = self._client.post(
|
|
186
|
+
self._config.rest_url,
|
|
187
|
+
headers=headers,
|
|
188
|
+
data=form,
|
|
189
|
+
files=files,
|
|
190
|
+
timeout=self._config.timeout.as_httpx_timeout(),
|
|
191
|
+
)
|
|
192
|
+
except httpx.TimeoutException as exc:
|
|
193
|
+
raise TimeoutError("REST transcription request timed out") from exc
|
|
194
|
+
except httpx.RequestError as exc:
|
|
195
|
+
raise TransportError(f"REST transcription request failed: {exc}") from exc
|
|
196
|
+
|
|
197
|
+
payload: dict[str, Any] | None = None
|
|
198
|
+
try:
|
|
199
|
+
parsed = response.json()
|
|
200
|
+
if isinstance(parsed, dict):
|
|
201
|
+
payload = parsed
|
|
202
|
+
except Exception:
|
|
203
|
+
payload = None
|
|
204
|
+
|
|
205
|
+
if response.status_code >= 400:
|
|
206
|
+
raise _build_api_error(response, payload)
|
|
207
|
+
if payload is None:
|
|
208
|
+
raise ProtocolError("REST response is not a JSON object")
|
|
209
|
+
return parse_rest_result(payload)
|
|
210
|
+
|
|
211
|
+
def health_check(self, *, api_key_override: str | None = None) -> dict[str, Any]:
|
|
212
|
+
self.open()
|
|
213
|
+
assert self._client is not None
|
|
214
|
+
headers = _make_headers(self._config, self._config.resolve_api_key(api_key_override))
|
|
215
|
+
try:
|
|
216
|
+
response = self._client.get(
|
|
217
|
+
self._config.health_url,
|
|
218
|
+
headers=headers,
|
|
219
|
+
timeout=self._config.timeout.as_httpx_timeout(),
|
|
220
|
+
)
|
|
221
|
+
except httpx.TimeoutException as exc:
|
|
222
|
+
raise TimeoutError("Health check request timed out") from exc
|
|
223
|
+
except httpx.RequestError as exc:
|
|
224
|
+
raise TransportError(f"Health check request failed: {exc}") from exc
|
|
225
|
+
|
|
226
|
+
payload: dict[str, Any] | None = None
|
|
227
|
+
try:
|
|
228
|
+
parsed = response.json()
|
|
229
|
+
if isinstance(parsed, dict):
|
|
230
|
+
payload = parsed
|
|
231
|
+
except Exception:
|
|
232
|
+
payload = None
|
|
233
|
+
|
|
234
|
+
if response.status_code >= 400:
|
|
235
|
+
raise _build_api_error(response, payload)
|
|
236
|
+
if payload is None:
|
|
237
|
+
raise ProtocolError("Health response is not a JSON object")
|
|
238
|
+
return payload
|
ringglabs/stt/_io.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""IO helpers for REST transcription inputs."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from .errors import ValidationError
|
|
5
|
+
from .models import FileSource
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def read_audio_source(source: FileSource, *, fallback_filename: str = "audio.wav") -> tuple[bytes, str]:
|
|
9
|
+
if isinstance(source, (bytes, bytearray)):
|
|
10
|
+
return bytes(source), fallback_filename
|
|
11
|
+
|
|
12
|
+
if isinstance(source, (str, Path)):
|
|
13
|
+
path = Path(source)
|
|
14
|
+
if not path.exists():
|
|
15
|
+
raise ValidationError(f"Audio file not found: {path}")
|
|
16
|
+
if not path.is_file():
|
|
17
|
+
raise ValidationError(f"Audio path is not a file: {path}")
|
|
18
|
+
return path.read_bytes(), path.name
|
|
19
|
+
|
|
20
|
+
if hasattr(source, "read"):
|
|
21
|
+
content = source.read() # type: ignore[call-arg]
|
|
22
|
+
if not isinstance(content, (bytes, bytearray)):
|
|
23
|
+
raise ValidationError("File-like source must return bytes from read()")
|
|
24
|
+
filename = getattr(source, "name", fallback_filename)
|
|
25
|
+
filename = Path(filename).name if isinstance(filename, str) else fallback_filename
|
|
26
|
+
return bytes(content), filename
|
|
27
|
+
|
|
28
|
+
raise ValidationError(
|
|
29
|
+
"source must be a file path, bytes/bytearray, or binary file-like object"
|
|
30
|
+
)
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Payload parsing and model conversion."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .errors import ProtocolError
|
|
7
|
+
from .models import (
|
|
8
|
+
AckEvent,
|
|
9
|
+
ErrorEvent,
|
|
10
|
+
PongEvent,
|
|
11
|
+
ReadyEvent,
|
|
12
|
+
RestTranscriptionResult,
|
|
13
|
+
TranscriptEvent,
|
|
14
|
+
WsEvent,
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _require_dict(payload: Any, *, label: str) -> dict[str, Any]:
|
|
19
|
+
if not isinstance(payload, dict):
|
|
20
|
+
raise ProtocolError(f"{label} must be a JSON object")
|
|
21
|
+
return payload
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _require_str(payload: dict[str, Any], key: str) -> str:
|
|
25
|
+
value = payload.get(key)
|
|
26
|
+
if not isinstance(value, str):
|
|
27
|
+
raise ProtocolError(f"Expected string field {key!r}")
|
|
28
|
+
return value
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _optional_str(payload: dict[str, Any], key: str) -> str | None:
|
|
32
|
+
value = payload.get(key)
|
|
33
|
+
if value is None:
|
|
34
|
+
return None
|
|
35
|
+
if not isinstance(value, str):
|
|
36
|
+
raise ProtocolError(f"Expected optional string field {key!r}")
|
|
37
|
+
return value
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _require_bool(payload: dict[str, Any], key: str) -> bool:
|
|
41
|
+
value = payload.get(key)
|
|
42
|
+
if not isinstance(value, bool):
|
|
43
|
+
raise ProtocolError(f"Expected boolean field {key!r}")
|
|
44
|
+
return value
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _optional_float(payload: dict[str, Any], key: str) -> float | None:
|
|
48
|
+
value = payload.get(key)
|
|
49
|
+
if value is None:
|
|
50
|
+
return None
|
|
51
|
+
if not isinstance(value, (int, float)) or isinstance(value, bool):
|
|
52
|
+
raise ProtocolError(f"Expected optional float field {key!r}")
|
|
53
|
+
return float(value)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _optional_int(payload: dict[str, Any], key: str) -> int | None:
|
|
57
|
+
value = payload.get(key)
|
|
58
|
+
if value is None:
|
|
59
|
+
return None
|
|
60
|
+
if not isinstance(value, int) or isinstance(value, bool):
|
|
61
|
+
raise ProtocolError(f"Expected optional integer field {key!r}")
|
|
62
|
+
return value
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_json_message(raw_message: str) -> dict[str, Any]:
|
|
66
|
+
try:
|
|
67
|
+
parsed = json.loads(raw_message)
|
|
68
|
+
except json.JSONDecodeError as exc:
|
|
69
|
+
raise ProtocolError(f"Invalid JSON from server: {exc.msg}") from exc
|
|
70
|
+
return _require_dict(parsed, label="message")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def parse_ws_event(payload: dict[str, Any]) -> WsEvent:
|
|
74
|
+
payload = _require_dict(payload, label="ws payload")
|
|
75
|
+
event_type = _require_str(payload, "type")
|
|
76
|
+
|
|
77
|
+
if event_type == "ready":
|
|
78
|
+
return ReadyEvent(
|
|
79
|
+
type=event_type,
|
|
80
|
+
request_id=_require_str(payload, "request_id"),
|
|
81
|
+
sample_rate=int(payload.get("sample_rate", 0)),
|
|
82
|
+
language=_require_str(payload, "language"),
|
|
83
|
+
mode=_require_str(payload, "mode"),
|
|
84
|
+
enable_cap_punc=_require_bool(payload, "enable_cap_punc"),
|
|
85
|
+
vad_tail_sil_ms=int(payload.get("vad_tail_sil_ms", 0)),
|
|
86
|
+
vad_confidence=float(payload.get("vad_confidence", 0.0)),
|
|
87
|
+
accept_client_vad_events=_require_bool(payload, "accept_client_vad_events"),
|
|
88
|
+
raw=payload,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
if event_type == "transcript":
|
|
92
|
+
return TranscriptEvent(
|
|
93
|
+
type=event_type,
|
|
94
|
+
transcription=_require_str(payload, "transcription"),
|
|
95
|
+
is_final=_require_bool(payload, "is_final"),
|
|
96
|
+
language=_require_str(payload, "language"),
|
|
97
|
+
request_id=_optional_str(payload, "request_id"),
|
|
98
|
+
segment_idx=_optional_int(payload, "segment_idx"),
|
|
99
|
+
segments=_optional_int(payload, "segments"),
|
|
100
|
+
compute_latency_ms=_optional_float(payload, "compute_latency_ms"),
|
|
101
|
+
audio_duration_sec=_optional_float(payload, "audio_duration_sec"),
|
|
102
|
+
transcribed_audio_duration_sec=_optional_float(
|
|
103
|
+
payload, "transcribed_audio_duration_sec"
|
|
104
|
+
),
|
|
105
|
+
processing_time_ms=_optional_float(payload, "processing_time_ms"),
|
|
106
|
+
raw=payload,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
if event_type == "ack":
|
|
110
|
+
return AckEvent(
|
|
111
|
+
type=event_type,
|
|
112
|
+
ack_for=_require_str(payload, "ack_for"),
|
|
113
|
+
state=_require_str(payload, "state"),
|
|
114
|
+
raw=payload,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
if event_type == "pong":
|
|
118
|
+
ts = payload.get("timestamp")
|
|
119
|
+
if not isinstance(ts, (int, float)) or isinstance(ts, bool):
|
|
120
|
+
raise ProtocolError("Expected numeric field 'timestamp' in pong event")
|
|
121
|
+
return PongEvent(type=event_type, timestamp=float(ts), raw=payload)
|
|
122
|
+
|
|
123
|
+
if event_type == "error":
|
|
124
|
+
status_code = payload.get("status_code")
|
|
125
|
+
if status_code is not None and (
|
|
126
|
+
not isinstance(status_code, int) or isinstance(status_code, bool)
|
|
127
|
+
):
|
|
128
|
+
raise ProtocolError("Expected optional integer field 'status_code' in error event")
|
|
129
|
+
return ErrorEvent(
|
|
130
|
+
type=event_type,
|
|
131
|
+
detail=_require_str(payload, "detail"),
|
|
132
|
+
code=_optional_str(payload, "code"),
|
|
133
|
+
status_code=status_code,
|
|
134
|
+
raw=payload,
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
raise ProtocolError(f"Unknown event type from server: {event_type!r}")
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def parse_rest_result(payload: dict[str, Any]) -> RestTranscriptionResult:
|
|
141
|
+
payload = _require_dict(payload, label="REST response")
|
|
142
|
+
return RestTranscriptionResult(
|
|
143
|
+
status=_require_str(payload, "status"),
|
|
144
|
+
transcription=_require_str(payload, "transcription"),
|
|
145
|
+
is_final=_require_bool(payload, "is_final"),
|
|
146
|
+
language=_require_str(payload, "language"),
|
|
147
|
+
duration_seconds=float(payload.get("duration_seconds", 0.0)),
|
|
148
|
+
processing_time_seconds=float(payload.get("processing_time_seconds", 0.0)),
|
|
149
|
+
request_id=_require_str(payload, "request_id"),
|
|
150
|
+
raw=payload,
|
|
151
|
+
)
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Async WebSocket streaming session implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
from typing import AsyncIterator
|
|
8
|
+
|
|
9
|
+
from websockets.exceptions import ConnectionClosed
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
from websockets.asyncio.client import connect as ws_connect
|
|
13
|
+
except ImportError: # pragma: no cover
|
|
14
|
+
from websockets.client import connect as ws_connect # type: ignore[no-redef]
|
|
15
|
+
|
|
16
|
+
from ._serialization import parse_json_message, parse_ws_event
|
|
17
|
+
from .config import ClientConfig
|
|
18
|
+
from .errors import ApiError, ProtocolError, TimeoutError, TransportError
|
|
19
|
+
from .models import ErrorEvent, ReadyEvent, StartConfig, WsEvent
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AsyncStreamSession:
|
|
23
|
+
"""Async context-managed WebSocket stream session."""
|
|
24
|
+
|
|
25
|
+
def __init__(
|
|
26
|
+
self,
|
|
27
|
+
client_config: ClientConfig,
|
|
28
|
+
start_config: StartConfig,
|
|
29
|
+
*,
|
|
30
|
+
api_key_override: str | None = None,
|
|
31
|
+
):
|
|
32
|
+
self._client_config = client_config
|
|
33
|
+
self._start_config = start_config
|
|
34
|
+
self._api_key_override = api_key_override
|
|
35
|
+
self._ws = None
|
|
36
|
+
self.ready_event: ReadyEvent | None = None
|
|
37
|
+
|
|
38
|
+
async def __aenter__(self) -> "AsyncStreamSession":
|
|
39
|
+
await self.open()
|
|
40
|
+
return self
|
|
41
|
+
|
|
42
|
+
async def __aexit__(self, exc_type, exc, tb) -> None:
|
|
43
|
+
await self.close()
|
|
44
|
+
|
|
45
|
+
async def open(self) -> ReadyEvent:
|
|
46
|
+
if self._ws is not None:
|
|
47
|
+
return self.ready_event if self.ready_event is not None else await self._handshake()
|
|
48
|
+
uri = self._client_config.ws_url
|
|
49
|
+
try:
|
|
50
|
+
self._ws = await ws_connect(
|
|
51
|
+
uri,
|
|
52
|
+
open_timeout=self._client_config.timeout.ws_open,
|
|
53
|
+
close_timeout=self._client_config.timeout.ws_close,
|
|
54
|
+
)
|
|
55
|
+
except asyncio.TimeoutError as exc:
|
|
56
|
+
raise TimeoutError("WebSocket connection timed out") from exc
|
|
57
|
+
except Exception as exc:
|
|
58
|
+
raise TransportError(f"WebSocket connection failed: {exc}") from exc
|
|
59
|
+
|
|
60
|
+
return await self._handshake()
|
|
61
|
+
|
|
62
|
+
async def _handshake(self) -> ReadyEvent:
|
|
63
|
+
if self._ws is None:
|
|
64
|
+
raise TransportError("WebSocket is not connected")
|
|
65
|
+
resolved_key = self._client_config.resolve_api_key(self._api_key_override)
|
|
66
|
+
payload = self._start_config.to_payload(resolved_api_key=resolved_key)
|
|
67
|
+
await self._ws.send(json.dumps(payload, ensure_ascii=False))
|
|
68
|
+
try:
|
|
69
|
+
raw = await asyncio.wait_for(
|
|
70
|
+
self._ws.recv(), timeout=self._client_config.timeout.ws_recv
|
|
71
|
+
)
|
|
72
|
+
except asyncio.TimeoutError as exc:
|
|
73
|
+
raise TimeoutError("Timed out waiting for server ready message") from exc
|
|
74
|
+
event = self._parse_raw_event(raw)
|
|
75
|
+
if isinstance(event, ErrorEvent):
|
|
76
|
+
raise ApiError(
|
|
77
|
+
message=event.detail,
|
|
78
|
+
code=event.code,
|
|
79
|
+
status_code=event.status_code,
|
|
80
|
+
payload=event.raw,
|
|
81
|
+
)
|
|
82
|
+
if not isinstance(event, ReadyEvent):
|
|
83
|
+
raise ProtocolError(
|
|
84
|
+
f"Expected first server message to be 'ready', got {event.type!r}"
|
|
85
|
+
)
|
|
86
|
+
self.ready_event = event
|
|
87
|
+
return event
|
|
88
|
+
|
|
89
|
+
async def send_audio(self, audio_chunk: bytes) -> None:
|
|
90
|
+
if self._ws is None:
|
|
91
|
+
raise TransportError("WebSocket is not connected")
|
|
92
|
+
if not isinstance(audio_chunk, (bytes, bytearray)):
|
|
93
|
+
raise ProtocolError("audio_chunk must be bytes")
|
|
94
|
+
await self._ws.send(bytes(audio_chunk))
|
|
95
|
+
|
|
96
|
+
async def send_vad_event(self, state: str) -> None:
|
|
97
|
+
if self._ws is None:
|
|
98
|
+
raise TransportError("WebSocket is not connected")
|
|
99
|
+
payload = {"type": "vad_event", "state": str(state)}
|
|
100
|
+
await self._ws.send(json.dumps(payload, ensure_ascii=False))
|
|
101
|
+
|
|
102
|
+
async def start_speaking(self) -> None:
|
|
103
|
+
await self.send_vad_event("user_start_speaking")
|
|
104
|
+
|
|
105
|
+
async def stop_speaking(self) -> None:
|
|
106
|
+
await self.send_vad_event("user_stop_speaking")
|
|
107
|
+
|
|
108
|
+
async def ping(self) -> None:
|
|
109
|
+
if self._ws is None:
|
|
110
|
+
raise TransportError("WebSocket is not connected")
|
|
111
|
+
await self._ws.send(json.dumps({"type": "ping"}, ensure_ascii=False))
|
|
112
|
+
|
|
113
|
+
async def end(self, command: str = "end") -> None:
|
|
114
|
+
if self._ws is None:
|
|
115
|
+
raise TransportError("WebSocket is not connected")
|
|
116
|
+
if command not in {"end", "stop", "exit", "close"}:
|
|
117
|
+
raise ProtocolError("command must be one of: end, stop, exit, close")
|
|
118
|
+
await self._ws.send(json.dumps({"type": command}, ensure_ascii=False))
|
|
119
|
+
|
|
120
|
+
async def recv_event(self) -> WsEvent:
|
|
121
|
+
if self._ws is None:
|
|
122
|
+
raise TransportError("WebSocket is not connected")
|
|
123
|
+
try:
|
|
124
|
+
raw = await asyncio.wait_for(
|
|
125
|
+
self._ws.recv(), timeout=self._client_config.timeout.ws_recv
|
|
126
|
+
)
|
|
127
|
+
except asyncio.TimeoutError as exc:
|
|
128
|
+
raise TimeoutError("Timed out waiting for WebSocket message") from exc
|
|
129
|
+
except ConnectionClosed as exc:
|
|
130
|
+
raise TransportError(f"WebSocket connection closed: {exc}") from exc
|
|
131
|
+
return self._parse_raw_event(raw)
|
|
132
|
+
|
|
133
|
+
async def events(self) -> AsyncIterator[WsEvent]:
|
|
134
|
+
while True:
|
|
135
|
+
try:
|
|
136
|
+
event = await self.recv_event()
|
|
137
|
+
except TimeoutError:
|
|
138
|
+
raise
|
|
139
|
+
except TransportError:
|
|
140
|
+
break
|
|
141
|
+
yield event
|
|
142
|
+
|
|
143
|
+
def _parse_raw_event(self, raw: str | bytes) -> WsEvent:
|
|
144
|
+
if isinstance(raw, bytes):
|
|
145
|
+
raise ProtocolError("Expected text JSON event from server, got binary frame")
|
|
146
|
+
payload = parse_json_message(raw)
|
|
147
|
+
return parse_ws_event(payload)
|
|
148
|
+
|
|
149
|
+
async def close(self) -> None:
|
|
150
|
+
if self._ws is not None:
|
|
151
|
+
await self._ws.close()
|
|
152
|
+
self._ws = None
|