vocalstack 1.0.0__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.
vocalstack/realtime.py ADDED
@@ -0,0 +1,555 @@
1
+ """``vs.realtime``: a realtime session is a signed token plus one socket
2
+ (``RealtimeSession``, over the public WS frame protocol; a live
3
+ transcription's publisher stream is one too). Nothing is stored: the transcript is what
4
+ the socket sends."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import asyncio
9
+ import json
10
+ import os
11
+ import time
12
+ from typing import Any, AsyncIterator, Callable, Dict, List, Optional, Union
13
+
14
+ import websockets
15
+ from websockets.asyncio.client import ClientConnection
16
+
17
+ from ._http import Transport
18
+ from ._models import (
19
+ Capabilities,
20
+ CreateSessionResponse,
21
+ ErrorFrame,
22
+ SessionDone,
23
+ SessionOptions,
24
+ SessionStats,
25
+ TranscriptEvent,
26
+ WarmRequest,
27
+ parse_server_frame,
28
+ )
29
+ from .errors import VocalStackError, capacity_exceeded, from_envelope
30
+
31
+ DEFAULT_READY_DEADLINE_S = 30.0
32
+
33
+
34
+ def upgrade_refused(status: int, body: Optional[bytes]) -> VocalStackError:
35
+ """A refused socket upgrade as an error. A 503 carrying the error body
36
+ with ``unavailable`` (the database is waking; retry shortly) says so;
37
+ any other 503 (a bare one from a saturated proxy, or no body at all) is
38
+ ``capacity_exceeded``. So is a 502 or 504 without the API's error body:
39
+ the proxy in front of the engines found none free in time. Every other
40
+ status is its own envelope."""
41
+ parsed = None
42
+ try:
43
+ parsed = json.loads(body) if body else None
44
+ except Exception:
45
+ pass
46
+ if status == 503:
47
+ if isinstance(parsed, dict) and parsed.get("code") == "unavailable":
48
+ return from_envelope(parsed, status)
49
+ return capacity_exceeded("stream host answered 503 (fleet saturated)")
50
+ ours = isinstance(parsed, dict) and isinstance(parsed.get("code"), str)
51
+ if status in (502, 504) and not ours:
52
+ return capacity_exceeded(f"stream host answered {status} (no engine answered in time)")
53
+ return from_envelope(parsed, status)
54
+
55
+
56
+ RESTART_CLOSE = 1012
57
+ LOST_WAITS_S = [1.0, 2.0, 4.0, 8.0, 15.0, 15.0, 15.0, 15.0]
58
+ RESTART_TRIES = 3
59
+ STEADY_S = 30.0
60
+ EARLY_RECOVERIES = 1
61
+ MAX_PENDING_BYTES = 4 * 1024 * 1024
62
+
63
+
64
+ class RealtimeSession:
65
+ """Async-iterable stream of transcript events.
66
+
67
+ Yields ``transcript.committed`` / ``transcript.draft`` /
68
+ ``transcript.words`` model objects; lifecycle frames are handled
69
+ internally (``session.loading``/``ready`` before iteration begins,
70
+ ``session.done``/``error`` ending it). Unknown frame types are
71
+ ignored.
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ session_id: str,
77
+ ws: ClientConnection,
78
+ on_frame: Optional[Callable[[Any], None]] = None,
79
+ *,
80
+ stream_url: Optional[str] = None,
81
+ ready_deadline_s: float = DEFAULT_READY_DEADLINE_S,
82
+ ) -> None:
83
+ self.session_id = session_id
84
+ self._ws = ws
85
+ self._on_frame = on_frame
86
+ self.done_reason: Optional[str] = None
87
+ self.stats: Optional[SessionStats] = None
88
+ self._error: Optional[VocalStackError] = None
89
+ self._closed = False
90
+ self._stream_url = stream_url
91
+ self._ready_deadline_s = ready_deadline_s
92
+ self._reconnecting = False
93
+ self._reconnects = 0
94
+ self._opened_at = time.monotonic()
95
+ self._early_recoveries = 0
96
+ self._pending: List[Union[str, bytes]] = []
97
+ self._pending_bytes = 0
98
+
99
+
100
+ @classmethod
101
+ async def connect(
102
+ cls,
103
+ session_id: str,
104
+ stream_url: str,
105
+ *,
106
+ ready_deadline_s: float = DEFAULT_READY_DEADLINE_S,
107
+ on_frame: Optional[Callable[[Any], None]] = None,
108
+ ) -> "RealtimeSession":
109
+ """Open the WS and wait for ``session.ready``.
110
+
111
+ ``on_frame`` sees every server text frame as it arrives, parsed:
112
+ the lifecycle frames the iterator keeps to itself
113
+ (``session.loading``, ``session.ready``, ``session.done``,
114
+ ``error``) and the transcript frames alike. For logs and protocol
115
+ views; iterate the session to read the transcript.
116
+
117
+ The deadline covers the gap since the LAST server frame: expiry
118
+ with no frames seen synthesizes ``capacity_exceeded`` (the
119
+ upgrade hung in the proxy's queue); once
120
+ ``session.loading`` heartbeats flow, expiry maps to
121
+ ``engine_unavailable`` instead.
122
+ """
123
+ ws = await cls._open_ready(stream_url, ready_deadline_s, on_frame)
124
+ return cls(session_id, ws, on_frame, stream_url=stream_url, ready_deadline_s=ready_deadline_s)
125
+
126
+ @staticmethod
127
+ async def _open_ready(
128
+ stream_url: str, ready_deadline_s: float, on_frame: Optional[Callable[[Any], None]]
129
+ ) -> ClientConnection:
130
+ """Open ``stream_url`` and wait for ``session.ready``: the socket, or
131
+ the error the connect is refused with."""
132
+ try:
133
+ ws = await websockets.connect(stream_url, max_size=None, open_timeout=ready_deadline_s, close_timeout=2)
134
+ except websockets.InvalidStatus as e:
135
+ refused = upgrade_refused(e.response.status_code, e.response.body)
136
+ refused._answered = True
137
+ raise refused from e
138
+ except TimeoutError as e:
139
+ raise VocalStackError(
140
+ "capacity_exceeded", f"the upgrade was not answered within {ready_deadline_s}s", retryable=True
141
+ ) from e
142
+ except OSError as e:
143
+ raise VocalStackError("engine_unavailable", f"connect failed: {e}", retryable=True) from e
144
+
145
+ saw_frame = False
146
+ while True:
147
+ try:
148
+ raw = await asyncio.wait_for(ws.recv(), timeout=ready_deadline_s)
149
+ except asyncio.TimeoutError:
150
+ await ws.close()
151
+ if saw_frame:
152
+ raise VocalStackError(
153
+ "engine_unavailable",
154
+ f"engine did not become ready within {ready_deadline_s}s",
155
+ retryable=True,
156
+ ) from None
157
+ raise capacity_exceeded(
158
+ f"no response from stream host within {ready_deadline_s}s "
159
+ "(fleet may be saturated)"
160
+ ) from None
161
+ except websockets.ConnectionClosed as e:
162
+ raise VocalStackError(
163
+ "engine_unavailable", "connection closed before ready", retryable=True
164
+ ) from e
165
+ if isinstance(raw, bytes):
166
+ continue
167
+ saw_frame = True
168
+ frame = parse_server_frame(raw)
169
+ if frame is None:
170
+ continue
171
+ _hand(on_frame, frame)
172
+ if frame.type == "session.ready":
173
+ return ws
174
+ if frame.type == "error":
175
+ await ws.close()
176
+ raise VocalStackError(frame.code, frame.message, retryable=frame.retryable)
177
+
178
+
179
+ async def send_audio(self, pcm: Union[bytes, bytearray, memoryview]) -> None:
180
+ """Raw PCM per the session's negotiated format (f32le 16 kHz mono).
181
+
182
+ Sends racing the end of the session are silently dropped — the
183
+ event iterator is the authority on how the session ended.
184
+ """
185
+ await self._send(bytes(pcm))
186
+
187
+ async def _send(self, data: Union[str, bytes]) -> None:
188
+ """Send now; while reconnecting after a restart close, keep it
189
+ (bounded) for the next socket."""
190
+ if not self._reconnecting:
191
+ try:
192
+ await self._ws.send(data)
193
+ return
194
+ except websockets.ConnectionClosed as e:
195
+ if self._closed or not _restart(e):
196
+ return
197
+ if self._pending_bytes + len(data) <= MAX_PENDING_BYTES:
198
+ self._pending.append(data)
199
+ self._pending_bytes += len(data)
200
+
201
+ async def _reconnect(self) -> None:
202
+ """The relay restarting: open the same ``stream_url`` again (1, 2,
203
+ 4 s apart), send what waited, and go on as the same session. Out
204
+ of tries: ``engine_lost``. A socket that stayed open ``STEADY_S``
205
+ before the restart close starts the tries anew, so a long session
206
+ goes through any number of restarts."""
207
+ self._reconnecting = True
208
+ if time.monotonic() - self._opened_at >= STEADY_S:
209
+ self._reconnects = 0
210
+ try:
211
+ while self._reconnects < RESTART_TRIES and not self._closed and self._stream_url:
212
+ await asyncio.sleep(2 ** self._reconnects)
213
+ self._reconnects += 1
214
+ try:
215
+ ws = await self._open_ready(self._stream_url, self._ready_deadline_s, self._on_frame)
216
+ except VocalStackError as e:
217
+ if not e.retryable:
218
+ raise
219
+ continue
220
+ self._ws = ws
221
+ self._opened_at = time.monotonic()
222
+ self._reconnecting = False
223
+ waiting, self._pending, self._pending_bytes = self._pending, [], 0
224
+ for d in waiting:
225
+ await self._send(d)
226
+ return
227
+ raise engine_lost(RESTART_CLOSE)
228
+ finally:
229
+ self._reconnecting = False
230
+
231
+ async def _recover(self) -> None:
232
+ """The socket dropped with no close frame (the server it was on
233
+ stopped answering): open the same ``stream_url`` again, ``LOST_WAITS_S``
234
+ apart, for as long as the server answers "try again" (a retryable
235
+ refusal of the upgrade), send what waited, and go on as the same
236
+ session. A refusal for good, no answer at all, or the last try
237
+ spent: ``engine_lost``, as before."""
238
+ self._reconnecting = True
239
+ try:
240
+ for wait in LOST_WAITS_S:
241
+ await asyncio.sleep(wait)
242
+ if self._closed or not self._stream_url:
243
+ break
244
+ try:
245
+ ws = await self._open_ready(self._stream_url, self._ready_deadline_s, self._on_frame)
246
+ except Exception as e:
247
+ if isinstance(e, VocalStackError) and e.retryable and getattr(e, "_answered", False):
248
+ continue
249
+ break
250
+ self._ws = ws
251
+ self._opened_at = time.monotonic()
252
+ self._reconnecting = False
253
+ waiting, self._pending, self._pending_bytes = self._pending, [], 0
254
+ for d in waiting:
255
+ await self._send(d)
256
+ return
257
+ raise engine_lost()
258
+ finally:
259
+ self._reconnecting = False
260
+
261
+ async def send_file(
262
+ self,
263
+ source: Union[str, bytes, bytearray, "os.PathLike[str]"],
264
+ *,
265
+ chunk_bytes: int = 256 * 1024,
266
+ ) -> None:
267
+ """Upload an encoded audio file (file sessions only), then ``eof()``.
268
+
269
+ A path is streamed from disk rather than read whole — uploads run
270
+ to hundreds of megabytes.
271
+ """
272
+ if isinstance(source, (bytes, bytearray)):
273
+ for off in range(0, len(source), chunk_bytes):
274
+ await self.send_audio(bytes(source[off : off + chunk_bytes]))
275
+ else:
276
+ with open(source, "rb") as fh:
277
+ while True:
278
+ chunk = await asyncio.to_thread(fh.read, chunk_bytes)
279
+ if not chunk:
280
+ break
281
+ await self.send_audio(chunk)
282
+ await self.eof()
283
+
284
+ async def eof(self) -> None:
285
+ """End of source: server flushes, emits final commits, then
286
+ ``session.done`` — after which iteration completes."""
287
+ await self._send(json.dumps({"type": "eof"}))
288
+
289
+ async def update(
290
+ self,
291
+ *,
292
+ latency_mode: Optional[str] = None,
293
+ spoken_language: Optional[str] = None,
294
+ speaker_labels: Optional[str] = None,
295
+ translate: Optional[List[str]] = None,
296
+ ) -> None:
297
+ """Options update during the realtime session; omitted fields are unchanged.
298
+
299
+ ``latency_mode`` (``"auto"`` | ``"fast"`` | ``"accuracy"``)
300
+ switches the decode model policy from the next engine step;
301
+ ``spoken_language`` changes the transcription language from the next
302
+ engine step (``""`` or ``"auto"`` = auto-detect); ``speaker_labels``
303
+ turns speaker labelling on (``"on"`` or ``"auto"``) or off (``"off"``) from
304
+ the next engine step; ``translate`` replaces the whole
305
+ target-language list (``[]`` turns translation off). Applies to
306
+ subsequent transcript — already-delivered segments are not
307
+ re-transcribed, re-attributed or re-translated.
308
+ """
309
+ frame: Dict[str, Any] = {"type": "session.update"}
310
+ if latency_mode is not None:
311
+ frame["latencyMode"] = latency_mode
312
+ if spoken_language is not None:
313
+ frame["spokenLanguage"] = spoken_language
314
+ if speaker_labels is not None:
315
+ frame["speakerLabels"] = speaker_labels
316
+ if translate is not None:
317
+ frame["translate"] = translate
318
+ await self._send(json.dumps(frame))
319
+
320
+ async def cancel(self) -> None:
321
+ """Stop now, abandoning the rest of the audio.
322
+
323
+ The server ends the session with ``session.done`` /
324
+ ``cancelled`` and frees the machine immediately; everything
325
+ committed before the stop stays valid. Prefer this to
326
+ ``close()`` for a deliberate stop — it is a clean end that still
327
+ reports stats.
328
+ """
329
+ await self._send(json.dumps({"type": "cancel"}))
330
+
331
+ async def close(self) -> None:
332
+ """Hard-close (aborts the run server-side; no resume, rule 7).
333
+ Prefer ``eof()`` to get final commits."""
334
+ self._closed = True
335
+ await self._ws.close()
336
+
337
+
338
+ def __aiter__(self) -> AsyncIterator[TranscriptEvent]:
339
+ return self._events()
340
+
341
+ async def _events(self) -> AsyncIterator[TranscriptEvent]:
342
+ while True:
343
+ if self._error:
344
+ raise self._error
345
+ if self.done_reason is not None or self._closed:
346
+ return
347
+ try:
348
+ raw = await self._ws.recv()
349
+ except websockets.ConnectionClosed as e:
350
+ if self._closed:
351
+ return
352
+ if _restart(e):
353
+ try:
354
+ await self._reconnect()
355
+ except VocalStackError as err:
356
+ self._error = err
357
+ raise
358
+ continue
359
+ young = time.monotonic() - self._opened_at < STEADY_S
360
+ if e.rcvd is None and (not young or self._early_recoveries < EARLY_RECOVERIES):
361
+ if young:
362
+ self._early_recoveries += 1
363
+ try:
364
+ await self._recover()
365
+ except VocalStackError as err:
366
+ self._error = err
367
+ raise err from e
368
+ continue
369
+ self._error = engine_lost(e.rcvd.code if e.rcvd else None)
370
+ raise self._error from e
371
+ if isinstance(raw, bytes):
372
+ continue
373
+ frame = parse_server_frame(raw)
374
+ if frame is None:
375
+ continue
376
+ _hand(self._on_frame, frame)
377
+ if isinstance(frame, SessionDone):
378
+ self.done_reason = frame.reason
379
+ self.stats = frame.stats
380
+ return
381
+ if isinstance(frame, ErrorFrame):
382
+ self._error = VocalStackError(
383
+ frame.code, frame.message, retryable=frame.retryable
384
+ )
385
+ raise self._error
386
+ if frame.type.startswith("transcript."):
387
+ yield frame
388
+
389
+
390
+ async def __aenter__(self) -> "RealtimeSession":
391
+ return self
392
+
393
+ async def __aexit__(self, *exc: object) -> None:
394
+ await self.close()
395
+
396
+
397
+ def _restart(e: "websockets.ConnectionClosed") -> bool:
398
+ """The socket closed with the relay's restart close."""
399
+ return e.rcvd is not None and e.rcvd.code == RESTART_CLOSE
400
+
401
+
402
+ def engine_lost(close_code: Optional[int] = None) -> VocalStackError:
403
+ """A ready socket that closed with neither ``session.done`` nor an
404
+ ``error`` frame, and not by ``close()``: the engine went away
405
+ mid-stream (its machine stopped or crashed) or the connection to it
406
+ dropped. What was committed before stays; nothing after it was
407
+ transcribed. Retryable: open a new realtime session to go on. (The
408
+ relay's restart close, 1012, is not this: the session reconnects and
409
+ goes on, ``RESTART_CLOSE``.)"""
410
+ how = f" (close {close_code})" if close_code else ""
411
+ return VocalStackError(
412
+ "engine_lost",
413
+ "The connection to the transcription engine closed before the realtime session "
414
+ f"finished{how}; open a new realtime session to continue.",
415
+ retryable=True,
416
+ )
417
+
418
+
419
+ def _hand(on_frame: Optional[Callable[[Any], None]], frame: Any) -> None:
420
+ """Hands a frame to ``on_frame``; a raising callback never breaks the socket."""
421
+ if on_frame is None:
422
+ return
423
+ try:
424
+ on_frame(frame)
425
+ except Exception:
426
+ pass
427
+
428
+
429
+ async def pace_realtime(
430
+ session: RealtimeSession,
431
+ pcm: bytes,
432
+ *,
433
+ chunk_seconds: float = 0.25,
434
+ speed: float = 1.0,
435
+ ) -> None:
436
+ """Feed a whole PCM buffer at ``speed``× realtime, then ``eof()``.
437
+ Convenience for file sources against the realtime API."""
438
+ bytes_per_second = 16000 * 4
439
+ chunk = max(4, int(bytes_per_second * chunk_seconds) & ~3)
440
+ start = time.monotonic()
441
+ sent_s = 0.0
442
+ for off in range(0, len(pcm), chunk):
443
+ await session.send_audio(pcm[off : off + chunk])
444
+ sent_s += len(pcm[off : off + chunk]) / bytes_per_second
445
+ target = start + sent_s / speed
446
+ delay = target - time.monotonic()
447
+ if delay > 0:
448
+ await asyncio.sleep(delay)
449
+ await session.eof()
450
+
451
+
452
+ class RealtimeTranscript:
453
+ """Result of :meth:`Realtime.transcribe_file` / :meth:`Realtime.transcribe_url`."""
454
+
455
+ __slots__ = ("segments", "done_reason", "stats")
456
+
457
+ def __init__(self, segments: list, done_reason: Optional[str], stats: Any = None) -> None:
458
+ self.segments = segments
459
+ self.done_reason = done_reason
460
+ self.stats = stats
461
+
462
+ @property
463
+ def text(self) -> str:
464
+ """All committed text, space-joined."""
465
+ return " ".join(s.text for s in self.segments)
466
+
467
+ def __repr__(self) -> str:
468
+ rt = f", realtime={self.stats.realtime_factor}x" if self.stats else ""
469
+ return f"RealtimeTranscript(segments={len(self.segments)}, done_reason={self.done_reason!r}{rt})"
470
+
471
+
472
+ class Realtime:
473
+ def __init__(self, t: Transport, ready_deadline_s: float) -> None:
474
+ self._t = t
475
+ self._ready_deadline_s = ready_deadline_s
476
+
477
+ async def create_session(self, *, idempotency_key: Optional[str] = None, **options: Any) -> CreateSessionResponse:
478
+ """``POST /v1/realtime/sessions``: validate the options, get a signed
479
+ ``stream_url``. Keyword args mirror SessionOptions (``spoken_language``,
480
+ ``speaker_labels``, ``latency_mode``, ``events``, ``input``, ...)."""
481
+ body = SessionOptions.model_validate(options).model_dump(by_alias=True, exclude_none=True, mode="json")
482
+ data = await self._t.json("POST", "/v1/realtime/sessions", json_body=body, idempotency_key=idempotency_key)
483
+ return CreateSessionResponse.model_validate(data)
484
+
485
+ async def connect(
486
+ self,
487
+ *,
488
+ ready_deadline_s: Optional[float] = None,
489
+ on_frame: Optional[Callable[[Any], None]] = None,
490
+ **options: Any,
491
+ ) -> RealtimeSession:
492
+ """``create_session``, then open the socket and wait for ``session.ready``.
493
+ ``on_frame`` sees every server frame, lifecycle included (see
494
+ :meth:`RealtimeSession.connect`)."""
495
+ created = await self.create_session(**options)
496
+ return await RealtimeSession.connect(
497
+ created.session_id,
498
+ created.stream_url,
499
+ ready_deadline_s=ready_deadline_s or self._ready_deadline_s,
500
+ on_frame=on_frame,
501
+ )
502
+
503
+ async def capabilities(self) -> Capabilities:
504
+ """Languages, audio formats and limits."""
505
+ return Capabilities.model_validate(await self._t.json("GET", "/v1/realtime/capabilities"))
506
+
507
+ async def warm(self, client_kind: str, can_start: bool, spoken_language: Optional[str] = None) -> None:
508
+ """A person is using a screen that can start a live transcription, so
509
+ the one they start next is ready at once. Send it on real use, at most
510
+ every 30 seconds, and at once when the selected spoken language
511
+ changes (``None``: auto-detect)."""
512
+ body = WarmRequest.model_validate({"clientKind": client_kind, "canStart": can_start, "spokenLanguage": spoken_language})
513
+ await self._t.json("POST", "/v1/realtime/warm", json_body=body.model_dump(by_alias=True, exclude_none=True))
514
+
515
+ async def transcribe_file(
516
+ self,
517
+ source: Any,
518
+ *,
519
+ on_progress: Optional[Callable[[Any], None]] = None,
520
+ on_commit: Optional[Callable[[Any], None]] = None,
521
+ **options: Any,
522
+ ) -> RealtimeTranscript:
523
+ """Stream an encoded file (mp3, wav, flac, ogg, m4a...; a path or
524
+ bytes) through a realtime session and collect the transcript.
525
+ Nothing is stored; for a stored, shareable transcription use
526
+ ``vs.transcriptions.create(file=...)``."""
527
+ session = await self.connect(input={"kind": "file"}, **options)
528
+ async with session:
529
+ await session.send_file(source)
530
+ return await _collect(session, on_progress, on_commit)
531
+
532
+ async def transcribe_url(
533
+ self,
534
+ url: str,
535
+ *,
536
+ on_progress: Optional[Callable[[Any], None]] = None,
537
+ on_commit: Optional[Callable[[Any], None]] = None,
538
+ **options: Any,
539
+ ) -> RealtimeTranscript:
540
+ """The same for a link the engine fetches itself."""
541
+ session = await self.connect(input={"kind": "url", "url": url}, **options)
542
+ async with session:
543
+ return await _collect(session, on_progress, on_commit)
544
+
545
+
546
+ async def _collect(session: RealtimeSession, on_progress: Any, on_commit: Any) -> RealtimeTranscript:
547
+ segments: List[Any] = []
548
+ async for event in session:
549
+ if event.type == "transcript.committed":
550
+ segments.append(event.segment)
551
+ if on_commit is not None:
552
+ on_commit(event.segment)
553
+ elif event.type == "transcript.progress" and on_progress is not None:
554
+ on_progress(event)
555
+ return RealtimeTranscript(segments, session.done_reason, session.stats)