vocalstack 1.2.0__tar.gz → 1.2.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: vocalstack
3
- Version: 1.2.0
3
+ Version: 1.2.3
4
4
  Summary: VocalStack speech API SDK (asyncio): one client grouped by resource, typed models from the API contract, realtime WebSocket streaming.
5
5
  Project-URL: Homepage, https://vocalstack.com
6
6
  License-Expression: MIT
@@ -112,6 +112,32 @@ async with VocalStack(api_key=key) as vs:
112
112
  - `transcript.draft` frames **fully replace** the live tail; never append them.
113
113
  - `transcript.committed` segments are immutable, gapless by `segment.seq`,
114
114
  and carry word timings.
115
+ - A reconnect of a live session says `last_seq=<n>` in the stream URL's query,
116
+ the highest `seq` of the committed lines it received (nothing before the
117
+ first), so the server sends only the lines after it. A server that does not
118
+ read it sends first the committed lines the client may not have received,
119
+ with their own `seq` and `sentenceId`, and a line that did arrive then comes
120
+ a second time: the session's events deliver it twice (keep lines by `seq`).
121
+ - A connection that dies without closing (a network change, a frozen path) is
122
+ noticed: every connect says `heartbeat=1` in the stream URL's query, and a
123
+ server that answers with `heartbeatS` on `session.ready` sends a
124
+ `session.heartbeat` frame that often, whatever the session is doing. When
125
+ nothing at all arrived for three times `heartbeatS` (12 s at most: the server
126
+ says 1 to 4 s) the socket is dropped and the session goes on as after a socket lost
127
+ with no close frame. The reconnect after any live socket lost with no close
128
+ frame (also one whose server died) offers the audio still kept
129
+ (`kept_from=<byte>`), and sends it again from the byte `session.ready` names
130
+ (`resumeFrom`), so what the lost socket swallowed is not lost; when it names
131
+ none, nothing is sent again. A server that sends no `heartbeatS` is never
132
+ judged by its silence, and a client whose own timers stood still (a blocked
133
+ thread, a sleeping machine) starts the count again. `heartbeat=False` on `connect` and `publish`
134
+ turns it off.
135
+ `transcribe_file` and `transcribe_url`, and their `on_commit`, are for file and link sessions, which start over instead; they keep one line per
136
+ `seq`, the last received.
137
+ - A reconnect try after such a drop that gets no answer at all is
138
+ made again on the same waits, four such tries at most (about 1, 2, 3 and 4
139
+ seconds apart, the last within 13 seconds of the drop), then the session ends with `engine_lost`; an answered
140
+ refusal for good still ends it at once.
115
141
  - A dropped connection ends the realtime session (to go on, create a new one), except after a restart close (1012) or when the server it was on died: the SDK then reconnects to the same `streamUrl` and the realtime session goes on. A restart close that comes before `session.ready` is followed the same way inside `connect` (about 1, 2 and 4 s apart, three more tries at most), so it is not an error of the first connect.
116
142
  - After a restart close (1012, a server being replaced), when the server says
117
143
  how many bytes it took (`taken=`, said only for `input.kind` `live`), the SDK
@@ -99,6 +99,32 @@ async with VocalStack(api_key=key) as vs:
99
99
  - `transcript.draft` frames **fully replace** the live tail; never append them.
100
100
  - `transcript.committed` segments are immutable, gapless by `segment.seq`,
101
101
  and carry word timings.
102
+ - A reconnect of a live session says `last_seq=<n>` in the stream URL's query,
103
+ the highest `seq` of the committed lines it received (nothing before the
104
+ first), so the server sends only the lines after it. A server that does not
105
+ read it sends first the committed lines the client may not have received,
106
+ with their own `seq` and `sentenceId`, and a line that did arrive then comes
107
+ a second time: the session's events deliver it twice (keep lines by `seq`).
108
+ - A connection that dies without closing (a network change, a frozen path) is
109
+ noticed: every connect says `heartbeat=1` in the stream URL's query, and a
110
+ server that answers with `heartbeatS` on `session.ready` sends a
111
+ `session.heartbeat` frame that often, whatever the session is doing. When
112
+ nothing at all arrived for three times `heartbeatS` (12 s at most: the server
113
+ says 1 to 4 s) the socket is dropped and the session goes on as after a socket lost
114
+ with no close frame. The reconnect after any live socket lost with no close
115
+ frame (also one whose server died) offers the audio still kept
116
+ (`kept_from=<byte>`), and sends it again from the byte `session.ready` names
117
+ (`resumeFrom`), so what the lost socket swallowed is not lost; when it names
118
+ none, nothing is sent again. A server that sends no `heartbeatS` is never
119
+ judged by its silence, and a client whose own timers stood still (a blocked
120
+ thread, a sleeping machine) starts the count again. `heartbeat=False` on `connect` and `publish`
121
+ turns it off.
122
+ `transcribe_file` and `transcribe_url`, and their `on_commit`, are for file and link sessions, which start over instead; they keep one line per
123
+ `seq`, the last received.
124
+ - A reconnect try after such a drop that gets no answer at all is
125
+ made again on the same waits, four such tries at most (about 1, 2, 3 and 4
126
+ seconds apart, the last within 13 seconds of the drop), then the session ends with `engine_lost`; an answered
127
+ refusal for good still ends it at once.
102
128
  - A dropped connection ends the realtime session (to go on, create a new one), except after a restart close (1012) or when the server it was on died: the SDK then reconnects to the same `streamUrl` and the realtime session goes on. A restart close that comes before `session.ready` is followed the same way inside `connect` (about 1, 2 and 4 s apart, three more tries at most), so it is not an error of the first connect.
103
129
  - After a restart close (1012, a server being replaced), when the server says
104
130
  how many bytes it took (`taken=`, said only for `input.kind` `live`), the SDK
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "vocalstack"
7
- version = "1.2.0"
7
+ version = "1.2.3"
8
8
  description = "VocalStack speech API SDK (asyncio): one client grouped by resource, typed models from the API contract, realtime WebSocket streaming."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -29,7 +29,7 @@ from .errors import VocalStackError
29
29
  from .realtime import RealtimeTranscript
30
30
  from .realtime import RealtimeSession, pace_realtime
31
31
 
32
- __version__ = "1.2.0"
32
+ __version__ = "1.2.3"
33
33
 
34
34
  __all__ = [
35
35
  "DEFAULT_BASE_URL",
@@ -85,6 +85,8 @@ SentenceStatus = Union[Literal["open", "closed", "dropped"], str]
85
85
 
86
86
  VoiceStatusState = Union[Literal["preparing", "unavailable"], str]
87
87
 
88
+ ServiceLevel = Union[Literal["operational", "degraded", "outage", "unknown"], str]
89
+
88
90
 
89
91
  class AccountClosing(_Base):
90
92
  at: str
@@ -1318,6 +1320,7 @@ class StreamIngest(_Base):
1318
1320
  bytes_in: int = Field(alias="bytesIn")
1319
1321
  detected: Optional[str] = None
1320
1322
  error: Optional[str] = None
1323
+ error_code: Optional[str] = Field(default=None, alias="errorCode")
1321
1324
  failures: int
1322
1325
  finished_at: Optional[str] = Field(default=None, alias="finishedAt")
1323
1326
  last_audio_at: Optional[str] = Field(default=None, alias="lastAudioAt")
@@ -1417,7 +1420,7 @@ stream, an RTMP encoder), which may feed broadcasts (`broadcasts`)."""
1417
1420
  media: Optional[List["MediaSummary"]] = None
1418
1421
  metrics: Optional["TranscriptionMetrics"] = None
1419
1422
  name: str
1420
- origin: Union[Literal["dashboard", "api", "extension", "desktop_app", "ios_app", "obs", "wordpress", "payload", "strapi", "sanity", "contentful", "mcp", "broadcast", "unknown"], str]
1423
+ origin: Union[Literal["dashboard", "api", "extension", "desktop_app", "ios_app", "android_app", "obs", "wordpress", "payload", "strapi", "sanity", "contentful", "mcp", "broadcast", "unknown"], str]
1421
1424
  owner_principal_id: str = Field(alias="ownerPrincipalId")
1422
1425
  peak_latency_s: Optional[float] = Field(default=None, alias="peakLatencyS")
1423
1426
  peak_listeners: Optional[int] = Field(default=None, alias="peakListeners")
@@ -1591,6 +1594,33 @@ class SessionStats(_Base):
1591
1594
  realtime_factor: float = Field(alias="realtimeFactor")
1592
1595
 
1593
1596
 
1597
+ class ServiceDay(_Base):
1598
+ date: str
1599
+ uptime: Optional[float] = None
1600
+
1601
+
1602
+ class ServiceComponent(_Base):
1603
+ days: List["ServiceDay"]
1604
+ id: str
1605
+ name: str
1606
+ since: Optional[str] = None
1607
+ status: ServiceLevel
1608
+ uptime: Optional[float] = None
1609
+
1610
+
1611
+ class ServiceIncident(_Base):
1612
+ component: str
1613
+ ended_at: Optional[str] = Field(default=None, alias="endedAt")
1614
+ started_at: str = Field(alias="startedAt")
1615
+
1616
+
1617
+ class ServiceStatus(_Base):
1618
+ checked_at: Optional[str] = Field(default=None, alias="checkedAt")
1619
+ components: List["ServiceComponent"]
1620
+ incidents: List["ServiceIncident"]
1621
+ status: ServiceLevel
1622
+
1623
+
1594
1624
  class SessionOptions(_Base):
1595
1625
  audio: Optional["AudioFormat"] = None
1596
1626
  events: Optional["EventOptions"] = None
@@ -2012,9 +2042,15 @@ class SessionQueued(_Base):
2012
2042
 
2013
2043
 
2014
2044
  class SessionReady(_Base):
2045
+ heartbeat_s: Optional[int] = Field(default=None, alias="heartbeatS")
2046
+ resume_from: Optional[int] = Field(default=None, alias="resumeFrom")
2015
2047
  type: Literal["session.ready"] = "session.ready"
2016
2048
 
2017
2049
 
2050
+ class SessionHeartbeat(_Base):
2051
+ type: Literal["session.heartbeat"] = "session.heartbeat"
2052
+
2053
+
2018
2054
  class TranscriptCommitted(_Base):
2019
2055
  segment: "CommittedSegment"
2020
2056
  type: Literal["transcript.committed"] = "transcript.committed"
@@ -2191,7 +2227,7 @@ class ErrorFrame(_Base):
2191
2227
  type: Literal["error"] = "error"
2192
2228
 
2193
2229
 
2194
- ServerFrame = Annotated[Union[SessionLoading, SessionQueued, SessionReady, TranscriptCommitted, TranscriptDraft, TranscriptWords, TranscriptAmended, TranscriptLatency, TranscriptSpeaker, TranscriptSpeakerGender, TranscriptSpeakerIdentified, TranscriptSpeakerNumbers, TranscriptSentence, TranscriptTranslated, TranscriptVoice, TranscriptVoiceStatus, TranscriptLanguageStatus, TranscriptRetracted, TranscriptHeld, TranscriptProgress, StreamPull, SourceProgress, SourcePrepared, SessionDone, ErrorFrame], Field(discriminator="type")]
2230
+ ServerFrame = Annotated[Union[SessionLoading, SessionQueued, SessionReady, SessionHeartbeat, TranscriptCommitted, TranscriptDraft, TranscriptWords, TranscriptAmended, TranscriptLatency, TranscriptSpeaker, TranscriptSpeakerGender, TranscriptSpeakerIdentified, TranscriptSpeakerNumbers, TranscriptSentence, TranscriptTranslated, TranscriptVoice, TranscriptVoiceStatus, TranscriptLanguageStatus, TranscriptRetracted, TranscriptHeld, TranscriptProgress, StreamPull, SourceProgress, SourcePrepared, SessionDone, ErrorFrame], Field(discriminator="type")]
2195
2231
 
2196
2232
  class SubscribeUpdate(_Base):
2197
2233
  audio: Optional[bool] = None
@@ -2316,6 +2352,7 @@ class SpeakerVoice(_Base):
2316
2352
  class StreamIngest(_Base):
2317
2353
  detected: Optional[str] = None
2318
2354
  error: Optional[str] = None
2355
+ error_code: Optional[str] = Field(default=None, alias="errorCode")
2319
2356
  failures: Optional[int] = None
2320
2357
  last_audio_at: Optional[str] = Field(default=None, alias="lastAudioAt")
2321
2358
  state: IngestState
@@ -2343,11 +2380,11 @@ class SubscribeGap(_Base):
2343
2380
 
2344
2381
  SubscriberFrame = Annotated[Union[SubscribeReady, RecordingState, RecordingSettings, RecordingSilence, RecordingExpiring, TranscriptCorrected, TranscriptSpeakerGender, TranscriptSpeakerIdentified, TranscriptSpeakerNamed, TranscriptSpeakerNumbers, TranscriptionStarted, JobProgress, SpeakerVoice, StreamIngest, TranscriptionEnded, Audience, SubscribeGap], Field(discriminator="type")]
2345
2382
 
2346
- SERVER_FRAME_TYPES = frozenset(["session.loading", "session.queued", "session.ready", "transcript.committed", "transcript.draft", "transcript.words", "transcript.amended", "transcript.latency", "transcript.speaker", "transcript.speakerGender", "transcript.speakerIdentified", "transcript.speakerNumbers", "transcript.sentence", "transcript.translated", "transcript.voice", "transcript.voiceStatus", "transcript.languageStatus", "transcript.retracted", "transcript.held", "transcript.progress", "stream.pull", "source.progress", "source.prepared", "session.done", "error"])
2383
+ SERVER_FRAME_TYPES = frozenset(["session.loading", "session.queued", "session.ready", "session.heartbeat", "transcript.committed", "transcript.draft", "transcript.words", "transcript.amended", "transcript.latency", "transcript.speaker", "transcript.speakerGender", "transcript.speakerIdentified", "transcript.speakerNumbers", "transcript.sentence", "transcript.translated", "transcript.voice", "transcript.voiceStatus", "transcript.languageStatus", "transcript.retracted", "transcript.held", "transcript.progress", "stream.pull", "source.progress", "source.prepared", "session.done", "error"])
2347
2384
 
2348
2385
  _server_frame_adapter: TypeAdapter[ServerFrame] = TypeAdapter(ServerFrame)
2349
2386
 
2350
- _SERVER_FRAME_CLASSES: Dict[str, Any] = {"session.loading": SessionLoading, "session.queued": SessionQueued, "session.ready": SessionReady, "transcript.committed": TranscriptCommitted, "transcript.draft": TranscriptDraft, "transcript.words": TranscriptWords, "transcript.amended": TranscriptAmended, "transcript.latency": TranscriptLatency, "transcript.speaker": TranscriptSpeaker, "transcript.speakerGender": TranscriptSpeakerGender, "transcript.speakerIdentified": TranscriptSpeakerIdentified, "transcript.speakerNumbers": TranscriptSpeakerNumbers, "transcript.sentence": TranscriptSentence, "transcript.translated": TranscriptTranslated, "transcript.voice": TranscriptVoice, "transcript.voiceStatus": TranscriptVoiceStatus, "transcript.languageStatus": TranscriptLanguageStatus, "transcript.retracted": TranscriptRetracted, "transcript.held": TranscriptHeld, "transcript.progress": TranscriptProgress, "stream.pull": StreamPull, "source.progress": SourceProgress, "source.prepared": SourcePrepared, "session.done": SessionDone, "error": ErrorFrame}
2387
+ _SERVER_FRAME_CLASSES: Dict[str, Any] = {"session.loading": SessionLoading, "session.queued": SessionQueued, "session.ready": SessionReady, "session.heartbeat": SessionHeartbeat, "transcript.committed": TranscriptCommitted, "transcript.draft": TranscriptDraft, "transcript.words": TranscriptWords, "transcript.amended": TranscriptAmended, "transcript.latency": TranscriptLatency, "transcript.speaker": TranscriptSpeaker, "transcript.speakerGender": TranscriptSpeakerGender, "transcript.speakerIdentified": TranscriptSpeakerIdentified, "transcript.speakerNumbers": TranscriptSpeakerNumbers, "transcript.sentence": TranscriptSentence, "transcript.translated": TranscriptTranslated, "transcript.voice": TranscriptVoice, "transcript.voiceStatus": TranscriptVoiceStatus, "transcript.languageStatus": TranscriptLanguageStatus, "transcript.retracted": TranscriptRetracted, "transcript.held": TranscriptHeld, "transcript.progress": TranscriptProgress, "stream.pull": StreamPull, "source.progress": SourceProgress, "source.prepared": SourcePrepared, "session.done": SessionDone, "error": ErrorFrame}
2351
2388
 
2352
2389
 
2353
2390
  TranscriptEvent = Union[TranscriptCommitted, TranscriptDraft, TranscriptWords, TranscriptAmended, TranscriptLatency, TranscriptSpeaker, TranscriptSpeakerGender, TranscriptSpeakerIdentified, TranscriptSpeakerNumbers, TranscriptSentence, TranscriptTranslated, TranscriptVoice, TranscriptVoiceStatus, TranscriptLanguageStatus, TranscriptRetracted, TranscriptHeld, TranscriptProgress]
@@ -60,11 +60,13 @@ def upgrade_refused(status: int, body: Optional[bytes]) -> VocalStackError:
60
60
  RESTART_CLOSE = 1012
61
61
  LOST_WAITS_S = [1.0, 2.0, 4.0, 8.0, 15.0, 15.0, 15.0, 15.0]
62
62
  RESTART_TRIES = 3
63
+ LOST_UNANSWERED_WAITS_S = [2.0, 3.0, 4.0]
63
64
  STEADY_S = 30.0
64
65
  EARLY_RECOVERIES = 1
65
66
  MAX_PENDING_BYTES = 4 * 1024 * 1024
66
67
  RESEND_BUFFER_S = 30.0
67
68
  RESUME_PARAM = "resume_from"
69
+ LAST_SEQ_PARAM = "last_seq"
68
70
  REFUSED_TOTAL_S = 90.0
69
71
  LOST_TOTAL_S = 90.0
70
72
  LAST_TRY_S = 5.0
@@ -73,6 +75,11 @@ JITTER = 0.3
73
75
  KEPT_FRAMES = 32
74
76
  LIVE_FRAMES = 256
75
77
  RESEND_PARAM = "resend"
78
+ HEARTBEAT_PARAM = "heartbeat"
79
+ KEPT_FROM_PARAM = "kept_from"
80
+ HEARTBEATS_MISSED = 3
81
+ WATCH_EVERY_MOST_S = 1.0
82
+ WATCH_LATE_S = 2.0
76
83
  CLOSE_GRACE_S = 0.25
77
84
  CLOSE_UNREAD_S = 30.0
78
85
  UNREAD_FRAMES = 1 << 40
@@ -117,6 +124,24 @@ def with_refile(url: str) -> str:
117
124
  return _with_query(url, "refile", 1)
118
125
 
119
126
 
127
+ def heartbeat_s(ready: Any) -> Optional[float]:
128
+ """The seconds between ``session.heartbeat`` frames a ``session.ready``
129
+ promises; none when it promises none."""
130
+ s = ready.get("heartbeatS") if isinstance(ready, dict) else None
131
+ if isinstance(s, bool) or not isinstance(s, (int, float)) or not math.isfinite(s) or s <= 0:
132
+ return None
133
+ return float(s)
134
+
135
+
136
+ def resume_from_of(ready: Any) -> Optional[int]:
137
+ """The byte of the last socket's audio a ``session.ready`` asks to be
138
+ sent again from; none when it names none."""
139
+ n = ready.get("resumeFrom") if isinstance(ready, dict) else None
140
+ if isinstance(n, bool) or not isinstance(n, int) or n < 0:
141
+ return None
142
+ return n
143
+
144
+
120
145
  _RERUN = object()
121
146
  FIRST_RETRY_AFTER_MOST_S = 30.0
122
147
 
@@ -224,8 +249,12 @@ class Socket(ClientConnection):
224
249
  on_close_frame: Optional[Callable[[Any], None]] = None
225
250
  close_frame_seen = False
226
251
  _close_by = 0.0
252
+ ready: Any = None
253
+ heard_at = 0.0
254
+ went_silent = False
227
255
 
228
256
  def data_received(self, data: bytes) -> None:
257
+ self.heard_at = self.loop.time()
229
258
  super().data_received(data)
230
259
  if self.close_frame_seen or self.protocol.close_rcvd is None:
231
260
  return
@@ -296,9 +325,14 @@ class RealtimeSession:
296
325
  bytes_per_second: int = 64000,
297
326
  input_kind: Optional[str] = None,
298
327
  refile: bool = False,
328
+ heartbeat: bool = True,
299
329
  ) -> None:
300
330
  self.session_id = session_id
331
+ self._heartbeat = heartbeat
332
+ self._kept: Optional[int] = None
333
+ self._watcher: Optional[asyncio.TimerHandle] = None
301
334
  self._whole_file = input_kind in ("file", "url")
335
+ self._last_seq: Optional[int] = None
302
336
  self._refile = refile and self._whole_file
303
337
  self._reruns = 0
304
338
  self._bytes_per_second = max(1, int(bytes_per_second))
@@ -356,6 +390,7 @@ class RealtimeSession:
356
390
  bytes_per_second: int = 64000,
357
391
  input_kind: Optional[str] = None,
358
392
  refile: bool = False,
393
+ heartbeat: bool = True,
359
394
  ) -> "RealtimeSession":
360
395
  """Open the WS and wait for ``session.ready``.
361
396
 
@@ -401,6 +436,18 @@ class RealtimeSession:
401
436
  A restart close (1012) before ``session.ready`` and an upgrade
402
437
  answered 503 with ``Retry-After`` are followed by opening the same
403
438
  ``stream_url`` again, three more tries at most.
439
+
440
+ ``heartbeat`` (on unless set false) asks the server for
441
+ ``session.heartbeat`` frames (``heartbeat=1`` on the socket URL).
442
+ Where ``session.ready`` answers with ``heartbeatS``, a socket on
443
+ which nothing at all arrived for three times that long is taken for
444
+ lost and dropped, and the session goes on as after a socket lost
445
+ with no close frame. The reconnect after any live socket lost with
446
+ no close frame (also one whose server died) offers the audio still
447
+ kept (``kept_from``) and sends it again from the byte
448
+ ``session.ready`` names (``resumeFrom``), or sends nothing again
449
+ when it names none.
450
+ A server that says no ``heartbeatS`` is never judged by its silence.
404
451
  """
405
452
  if resend_buffer_bytes is not None:
406
453
  _size("resend_buffer_bytes", resend_buffer_bytes)
@@ -409,6 +456,8 @@ class RealtimeSession:
409
456
  plain = with_resend(stream_url, ring * 1000 / bytes_per_second)
410
457
  if refile and input_kind in ("file", "url"):
411
458
  plain = with_refile(plain)
459
+ if heartbeat:
460
+ plain = _with_query(plain, HEARTBEAT_PARAM, 1)
412
461
  url = plain
413
462
  tries = 0
414
463
  while True:
@@ -437,6 +486,7 @@ class RealtimeSession:
437
486
  bytes_per_second=bytes_per_second,
438
487
  input_kind=input_kind,
439
488
  refile=refile,
489
+ heartbeat=heartbeat,
440
490
  )
441
491
 
442
492
  @staticmethod
@@ -463,11 +513,13 @@ class RealtimeSession:
463
513
  "capacity_exceeded", f"the upgrade was not answered within {ready_deadline_s}s", retryable=True
464
514
  ) from e
465
515
  except OSError as e:
466
- raise VocalStackError("engine_unavailable", f"connect failed: {e}", retryable=True) from e
516
+ lost = VocalStackError("engine_unavailable", f"connect failed: {e}", retryable=True)
517
+ lost._unanswered = True # type: ignore[attr-defined]
518
+ raise lost from e
467
519
  except Exception as e:
468
- raise VocalStackError(
469
- "engine_unavailable", f"connect failed: {type(e).__name__}: {e}", retryable=True
470
- ) from e
520
+ lost = VocalStackError("engine_unavailable", f"connect failed: {type(e).__name__}: {e}", retryable=True)
521
+ lost._unanswered = isinstance(e, (EOFError, websockets.InvalidMessage)) # type: ignore[attr-defined]
522
+ raise lost from e
471
523
 
472
524
  try:
473
525
  return await RealtimeSession._until_ready(ws, ready_deadline_s, on_frame)
@@ -509,6 +561,10 @@ class RealtimeSession:
509
561
  continue
510
562
  _hand(on_frame, frame)
511
563
  if frame.type == "session.ready":
564
+ try:
565
+ ws.ready = json.loads(raw) # type: ignore[attr-defined]
566
+ except Exception:
567
+ pass
512
568
  return ws
513
569
  if frame.type == "error":
514
570
  await ws.close()
@@ -645,9 +701,65 @@ class RealtimeSession:
645
701
  def _watch(self, ws: ClientConnection) -> None:
646
702
  if isinstance(ws, Socket):
647
703
  ws.on_close_frame = self._close_frame
704
+ self._guard(ws)
648
705
  if getattr(ws, "close_frame_seen", False):
649
706
  self._close_frame(ws)
650
707
 
708
+ def _unguard(self) -> None:
709
+ if self._watcher is not None:
710
+ self._watcher.cancel()
711
+ self._watcher = None
712
+
713
+ def _guard(self, ws: ClientConnection) -> None:
714
+ """Watch ``ws`` for silence when its ``session.ready`` promised
715
+ heartbeats: nothing received for ``HEARTBEATS_MISSED`` of them is a
716
+ dead connection. A check that itself came late (the loop was
717
+ blocked, the machine slept) proves nothing and starts the count
718
+ again."""
719
+ self._unguard()
720
+ every = heartbeat_s(getattr(ws, "ready", None)) if self._heartbeat else None
721
+ if every is None or not isinstance(ws, Socket):
722
+ return
723
+ try:
724
+ loop = asyncio.get_running_loop()
725
+ except RuntimeError:
726
+ return
727
+ dead = every * HEARTBEATS_MISSED
728
+ tick = min(WATCH_EVERY_MOST_S, max(0.01, dead / 12))
729
+ late = min(WATCH_LATE_S, every / 2)
730
+ ws.heard_at = loop.time()
731
+ last = [loop.time()]
732
+
733
+ def check() -> None:
734
+ self._watcher = None
735
+ if ws is not self._ws or self._closed or self._error is not None or self.done_reason is not None:
736
+ return
737
+ if self._held is ws or self._dead is ws or ws.close_frame_seen:
738
+ return
739
+ now = loop.time()
740
+ came_late = now - last[0] > tick + late
741
+ last[0] = now
742
+ if came_late:
743
+ ws.heard_at = now
744
+ elif now - ws.heard_at >= dead:
745
+ self._silent(ws)
746
+ return
747
+ self._watcher = loop.call_later(tick, check)
748
+
749
+ self._watcher = loop.call_later(tick, check)
750
+
751
+ def _silent(self, ws: "Socket") -> None:
752
+ """Nothing came on ``ws`` for three heartbeats: drop it, and go on
753
+ as after a socket lost with no close frame."""
754
+ ws.went_silent = True
755
+ try:
756
+ ws.transport.abort()
757
+ except Exception:
758
+ pass
759
+ self._dead = ws
760
+ self._unclaim()
761
+ self._carry()
762
+
651
763
  def _close_frame(self, ws: ClientConnection) -> None:
652
764
  """The server's close frame came on ``ws``, whose connection may
653
765
  stay open for a while yet: a restart close fixes the byte the next
@@ -665,7 +777,7 @@ class RealtimeSession:
665
777
  while self._texts_done > 0 and self._texts[self._texts_done - 1][2] is not True:
666
778
  self._texts_done -= 1
667
779
 
668
- def _hold(self, e: Optional["websockets.ConnectionClosed"]) -> None:
780
+ def _hold(self, e: Optional["websockets.ConnectionClosed"], silent: bool = False) -> None:
669
781
  """The socket closed and another is to follow: fix the byte the
670
782
  next one starts at. ``taken=N`` of a restart close counts from the
671
783
  closing socket's first byte (``_base``) and may reach every byte
@@ -702,6 +814,8 @@ class RealtimeSession:
702
814
  self._flushing = False
703
815
  self._held = self._ws
704
816
  self._dead = None
817
+ keeps = silent and not valid and self._file is None and self._ring_bytes > 0
818
+ self._kept = min(start, max(self._ring_start, self._base)) if keeps else None
705
819
  self._trim()
706
820
  if lost:
707
821
  self._lose(lost)
@@ -711,6 +825,8 @@ class RealtimeSession:
711
825
  return
712
826
  ring = self._ring
713
827
  floor = self._from if self._from is not None else min(self._sent - self._ring_bytes, self._handed)
828
+ if self._kept is not None:
829
+ floor = min(floor, self._kept)
714
830
  drop = 0
715
831
  while drop < len(ring) and self._ring_start + len(ring[drop]) <= floor:
716
832
  self._ring_start += len(ring[drop])
@@ -748,8 +864,19 @@ class RealtimeSession:
748
864
  ws.on_close_frame = self._close_frame
749
865
  self._opened_at = time.monotonic()
750
866
  start = self._from if self._from is not None else self._handed
867
+ kept, self._kept = self._kept, None
868
+ again = resume_from_of(getattr(ws, "ready", None)) if kept is not None and self._resume is None else None
869
+ if kept is not None and again is not None:
870
+ at = max(self._base + again, kept)
871
+ if at < start:
872
+ while self._texts_done > 0 and self._texts[self._texts_done - 1][0] >= at:
873
+ self._texts_done -= 1
874
+ for entry in self._texts[self._texts_done :]:
875
+ entry[2] = False
876
+ start = at
751
877
  self._from = start
752
878
  self._trim()
879
+ self._guard(ws)
753
880
  self._flushing = True
754
881
  self._base = start
755
882
  self._handed = start
@@ -812,6 +939,8 @@ class RealtimeSession:
812
939
  return max(0, self._sent - (self._from if self._from is not None else self._handed))
813
940
 
814
941
  def _let_go(self) -> None:
942
+ self._unguard()
943
+ self._kept = None
815
944
  self._flushing = False
816
945
  self._from = None
817
946
  self._ring = []
@@ -833,7 +962,15 @@ class RealtimeSession:
833
962
  url = with_resend(self._stream_url, self._ring_bytes * 1000 / self._bytes_per_second)
834
963
  if self._refile:
835
964
  url = with_refile(url)
836
- return url if self._resume is None else with_resume(url, self._resume)
965
+ if self._heartbeat:
966
+ url = _with_query(url, HEARTBEAT_PARAM, 1)
967
+ if self._kept is not None and self._resume is None:
968
+ url = _with_query(url, KEPT_FROM_PARAM, self._kept - self._base)
969
+ if self._resume is not None:
970
+ url = with_resume(url, self._resume)
971
+ if self._last_seq is not None and not self._whole_file:
972
+ url = _with_query(url, LAST_SEQ_PARAM, self._last_seq)
973
+ return url
837
974
 
838
975
  async def _open_again(self, within_s: Optional[float] = None) -> Optional[ClientConnection]:
839
976
  """The next socket, ready, within one deadline for the whole
@@ -930,10 +1067,16 @@ class RealtimeSession:
930
1067
  stopped answering): open the same ``stream_url`` again, ``LOST_WAITS_S``
931
1068
  apart, for as long as the server answers "try again" (a retryable
932
1069
  refusal of the upgrade), send what waited, and go on as the same
933
- session. A refusal for good, no answer at all, or the last try
934
- spent: ``engine_lost``, as before."""
1070
+ session. A try that got no answer at all (the connection refused or
1071
+ dropped before any response) is tried again too, after the waits of
1072
+ ``LOST_UNANSWERED_WAITS_S``, one more such try than it has waits. A refusal for good, the
1073
+ last unanswered try, or the last try spent: ``engine_lost``."""
935
1074
  until = time.monotonic() + LOST_TOTAL_S
936
- for wait in LOST_WAITS_S:
1075
+ unanswered = 0
1076
+ after: Optional[float] = None
1077
+ for step in LOST_WAITS_S:
1078
+ wait = step if after is None else after
1079
+ after = None
937
1080
  left = until - time.monotonic()
938
1081
  if left <= 0:
939
1082
  break
@@ -944,9 +1087,17 @@ class RealtimeSession:
944
1087
  try:
945
1088
  ws = await self._open_again(until - time.monotonic())
946
1089
  except Exception as e:
947
- if isinstance(e, VocalStackError) and e.retryable and getattr(e, "_answered", False):
1090
+ if not (isinstance(e, VocalStackError) and e.retryable):
1091
+ break
1092
+ if getattr(e, "_answered", False):
948
1093
  continue
949
- break
1094
+ if not getattr(e, "_unanswered", False):
1095
+ break
1096
+ if unanswered >= len(LOST_UNANSWERED_WAITS_S):
1097
+ break
1098
+ after = LOST_UNANSWERED_WAITS_S[unanswered]
1099
+ unanswered += 1
1100
+ continue
950
1101
  if ws is None:
951
1102
  return
952
1103
  await self._flush(ws)
@@ -987,7 +1138,7 @@ class RealtimeSession:
987
1138
  if dropped and (not young or self._early_recoveries < EARLY_RECOVERIES):
988
1139
  if young:
989
1140
  self._early_recoveries += 1
990
- self._hold(None)
1141
+ self._hold(None, silent=not self._whole_file or getattr(ws, "went_silent", False))
991
1142
  await self._recover()
992
1143
  return
993
1144
  raise engine_lost(e.rcvd.code if e is not None and e.rcvd else None)
@@ -1215,6 +1366,7 @@ class RealtimeSession:
1215
1366
  Prefer ``eof()`` to get final commits."""
1216
1367
  self._closed = True
1217
1368
  self._closing.set()
1369
+ self._unguard()
1218
1370
  await self._ws.close()
1219
1371
 
1220
1372
 
@@ -1263,6 +1415,10 @@ class RealtimeSession:
1263
1415
  if frame is None:
1264
1416
  return None
1265
1417
  _hand(self._on_frame, frame)
1418
+ if frame.type == "transcript.committed":
1419
+ seq = getattr(getattr(frame, "segment", None), "seq", None)
1420
+ if isinstance(seq, int) and seq >= 0:
1421
+ self._last_seq = seq if self._last_seq is None else max(self._last_seq, seq)
1266
1422
  if isinstance(frame, SessionDone):
1267
1423
  self.done_reason = frame.reason
1268
1424
  self.stats = frame.stats
@@ -1398,6 +1554,7 @@ class Realtime:
1398
1554
  resend_buffer_bytes: Optional[int] = None,
1399
1555
  on_audio_lost: Optional[Callable[[int], None]] = None,
1400
1556
  refile: bool = False,
1557
+ heartbeat: bool = True,
1401
1558
  **options: Any,
1402
1559
  ) -> RealtimeSession:
1403
1560
  """``create_session``, then open the socket and wait for ``session.ready``.
@@ -1416,6 +1573,7 @@ class Realtime:
1416
1573
  on_audio_lost=on_audio_lost,
1417
1574
  input_kind=_field(options.get("input"), "kind"),
1418
1575
  refile=refile,
1576
+ heartbeat=heartbeat,
1419
1577
  )
1420
1578
 
1421
1579
  async def capabilities(self) -> Capabilities:
@@ -1470,7 +1628,11 @@ async def _collect(session: RealtimeSession, on_progress: Any, on_commit: Any) -
1470
1628
  run = session._reruns
1471
1629
  segments.clear()
1472
1630
  if event.type == "transcript.committed":
1473
- segments.append(event.segment)
1631
+ at = next((i for i, s in enumerate(segments) if s.seq == event.segment.seq), -1)
1632
+ if at == -1:
1633
+ segments.append(event.segment)
1634
+ else:
1635
+ segments[at] = event.segment
1474
1636
  if on_commit is not None:
1475
1637
  on_commit(event.segment)
1476
1638
  elif event.type == "transcript.progress" and on_progress is not None:
@@ -1275,6 +1275,9 @@ class Meta(_Group):
1275
1275
  async def health(self) -> m.Health:
1276
1276
  return _one(m.Health, await self._t.json("GET", "/v1/health"))
1277
1277
 
1278
+ async def status(self) -> m.ServiceStatus:
1279
+ return _one(m.ServiceStatus, await self._t.json("GET", "/v1/status"))
1280
+
1278
1281
  async def openapi(self) -> Dict[str, Any]:
1279
1282
  """The OpenAPI document the models are generated from."""
1280
1283
  return await self._t.json("GET", "/v1/openapi.json")
File without changes
File without changes
File without changes