vocalstack 1.2.0__tar.gz → 1.2.2__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.2
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,31 @@ 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. That reconnect offers the audio still kept
128
+ (`kept_from=<byte>`), and sends it again from the byte `session.ready` names
129
+ (`resumeFrom`), so what the dead socket swallowed is not lost; when it names
130
+ none, nothing is sent again. A server that sends no `heartbeatS` is never
131
+ judged by its silence, and a client whose own timers stood still (a blocked
132
+ thread, a sleeping machine) starts the count again. `heartbeat=False` on `connect` and `publish`
133
+ turns it off.
134
+ `transcribe_file` and `transcribe_url`, and their `on_commit`, are for file and link sessions, which start over instead; they keep one line per
135
+ `seq`, the last received.
136
+ - A reconnect try after such a drop that gets no answer at all is
137
+ made again on the same waits, four such tries at most (about 1, 2, 3 and 4
138
+ seconds apart, the last within 13 seconds of the drop), then the session ends with `engine_lost`; an answered
139
+ refusal for good still ends it at once.
115
140
  - 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
141
  - After a restart close (1012, a server being replaced), when the server says
117
142
  how many bytes it took (`taken=`, said only for `input.kind` `live`), the SDK
@@ -99,6 +99,31 @@ 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. That reconnect offers the audio still kept
115
+ (`kept_from=<byte>`), and sends it again from the byte `session.ready` names
116
+ (`resumeFrom`), so what the dead socket swallowed is not lost; when it names
117
+ none, nothing is sent again. A server that sends no `heartbeatS` is never
118
+ judged by its silence, and a client whose own timers stood still (a blocked
119
+ thread, a sleeping machine) starts the count again. `heartbeat=False` on `connect` and `publish`
120
+ turns it off.
121
+ `transcribe_file` and `transcribe_url`, and their `on_commit`, are for file and link sessions, which start over instead; they keep one line per
122
+ `seq`, the last received.
123
+ - A reconnect try after such a drop that gets no answer at all is
124
+ made again on the same waits, four such tries at most (about 1, 2, 3 and 4
125
+ seconds apart, the last within 13 seconds of the drop), then the session ends with `engine_lost`; an answered
126
+ refusal for good still ends it at once.
102
127
  - 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
128
  - After a restart close (1012, a server being replaced), when the server says
104
129
  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.2"
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.2"
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")
@@ -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,16 @@ 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; that reconnect offers the audio still kept
446
+ (``kept_from``) and sends it again from the byte ``session.ready``
447
+ names (``resumeFrom``), or sends nothing again when it names none.
448
+ A server that says no ``heartbeatS`` is never judged by its silence.
404
449
  """
405
450
  if resend_buffer_bytes is not None:
406
451
  _size("resend_buffer_bytes", resend_buffer_bytes)
@@ -409,6 +454,8 @@ class RealtimeSession:
409
454
  plain = with_resend(stream_url, ring * 1000 / bytes_per_second)
410
455
  if refile and input_kind in ("file", "url"):
411
456
  plain = with_refile(plain)
457
+ if heartbeat:
458
+ plain = _with_query(plain, HEARTBEAT_PARAM, 1)
412
459
  url = plain
413
460
  tries = 0
414
461
  while True:
@@ -437,6 +484,7 @@ class RealtimeSession:
437
484
  bytes_per_second=bytes_per_second,
438
485
  input_kind=input_kind,
439
486
  refile=refile,
487
+ heartbeat=heartbeat,
440
488
  )
441
489
 
442
490
  @staticmethod
@@ -463,11 +511,13 @@ class RealtimeSession:
463
511
  "capacity_exceeded", f"the upgrade was not answered within {ready_deadline_s}s", retryable=True
464
512
  ) from e
465
513
  except OSError as e:
466
- raise VocalStackError("engine_unavailable", f"connect failed: {e}", retryable=True) from e
514
+ lost = VocalStackError("engine_unavailable", f"connect failed: {e}", retryable=True)
515
+ lost._unanswered = True # type: ignore[attr-defined]
516
+ raise lost from e
467
517
  except Exception as e:
468
- raise VocalStackError(
469
- "engine_unavailable", f"connect failed: {type(e).__name__}: {e}", retryable=True
470
- ) from e
518
+ lost = VocalStackError("engine_unavailable", f"connect failed: {type(e).__name__}: {e}", retryable=True)
519
+ lost._unanswered = isinstance(e, (EOFError, websockets.InvalidMessage)) # type: ignore[attr-defined]
520
+ raise lost from e
471
521
 
472
522
  try:
473
523
  return await RealtimeSession._until_ready(ws, ready_deadline_s, on_frame)
@@ -509,6 +559,10 @@ class RealtimeSession:
509
559
  continue
510
560
  _hand(on_frame, frame)
511
561
  if frame.type == "session.ready":
562
+ try:
563
+ ws.ready = json.loads(raw) # type: ignore[attr-defined]
564
+ except Exception:
565
+ pass
512
566
  return ws
513
567
  if frame.type == "error":
514
568
  await ws.close()
@@ -645,9 +699,65 @@ class RealtimeSession:
645
699
  def _watch(self, ws: ClientConnection) -> None:
646
700
  if isinstance(ws, Socket):
647
701
  ws.on_close_frame = self._close_frame
702
+ self._guard(ws)
648
703
  if getattr(ws, "close_frame_seen", False):
649
704
  self._close_frame(ws)
650
705
 
706
+ def _unguard(self) -> None:
707
+ if self._watcher is not None:
708
+ self._watcher.cancel()
709
+ self._watcher = None
710
+
711
+ def _guard(self, ws: ClientConnection) -> None:
712
+ """Watch ``ws`` for silence when its ``session.ready`` promised
713
+ heartbeats: nothing received for ``HEARTBEATS_MISSED`` of them is a
714
+ dead connection. A check that itself came late (the loop was
715
+ blocked, the machine slept) proves nothing and starts the count
716
+ again."""
717
+ self._unguard()
718
+ every = heartbeat_s(getattr(ws, "ready", None)) if self._heartbeat else None
719
+ if every is None or not isinstance(ws, Socket):
720
+ return
721
+ try:
722
+ loop = asyncio.get_running_loop()
723
+ except RuntimeError:
724
+ return
725
+ dead = every * HEARTBEATS_MISSED
726
+ tick = min(WATCH_EVERY_MOST_S, max(0.01, dead / 12))
727
+ late = min(WATCH_LATE_S, every / 2)
728
+ ws.heard_at = loop.time()
729
+ last = [loop.time()]
730
+
731
+ def check() -> None:
732
+ self._watcher = None
733
+ if ws is not self._ws or self._closed or self._error is not None or self.done_reason is not None:
734
+ return
735
+ if self._held is ws or self._dead is ws or ws.close_frame_seen:
736
+ return
737
+ now = loop.time()
738
+ came_late = now - last[0] > tick + late
739
+ last[0] = now
740
+ if came_late:
741
+ ws.heard_at = now
742
+ elif now - ws.heard_at >= dead:
743
+ self._silent(ws)
744
+ return
745
+ self._watcher = loop.call_later(tick, check)
746
+
747
+ self._watcher = loop.call_later(tick, check)
748
+
749
+ def _silent(self, ws: "Socket") -> None:
750
+ """Nothing came on ``ws`` for three heartbeats: drop it, and go on
751
+ as after a socket lost with no close frame."""
752
+ ws.went_silent = True
753
+ try:
754
+ ws.transport.abort()
755
+ except Exception:
756
+ pass
757
+ self._dead = ws
758
+ self._unclaim()
759
+ self._carry()
760
+
651
761
  def _close_frame(self, ws: ClientConnection) -> None:
652
762
  """The server's close frame came on ``ws``, whose connection may
653
763
  stay open for a while yet: a restart close fixes the byte the next
@@ -665,7 +775,7 @@ class RealtimeSession:
665
775
  while self._texts_done > 0 and self._texts[self._texts_done - 1][2] is not True:
666
776
  self._texts_done -= 1
667
777
 
668
- def _hold(self, e: Optional["websockets.ConnectionClosed"]) -> None:
778
+ def _hold(self, e: Optional["websockets.ConnectionClosed"], silent: bool = False) -> None:
669
779
  """The socket closed and another is to follow: fix the byte the
670
780
  next one starts at. ``taken=N`` of a restart close counts from the
671
781
  closing socket's first byte (``_base``) and may reach every byte
@@ -702,6 +812,8 @@ class RealtimeSession:
702
812
  self._flushing = False
703
813
  self._held = self._ws
704
814
  self._dead = None
815
+ keeps = silent and not valid and self._file is None and self._ring_bytes > 0
816
+ self._kept = min(start, max(self._ring_start, self._base)) if keeps else None
705
817
  self._trim()
706
818
  if lost:
707
819
  self._lose(lost)
@@ -711,6 +823,8 @@ class RealtimeSession:
711
823
  return
712
824
  ring = self._ring
713
825
  floor = self._from if self._from is not None else min(self._sent - self._ring_bytes, self._handed)
826
+ if self._kept is not None:
827
+ floor = min(floor, self._kept)
714
828
  drop = 0
715
829
  while drop < len(ring) and self._ring_start + len(ring[drop]) <= floor:
716
830
  self._ring_start += len(ring[drop])
@@ -748,8 +862,19 @@ class RealtimeSession:
748
862
  ws.on_close_frame = self._close_frame
749
863
  self._opened_at = time.monotonic()
750
864
  start = self._from if self._from is not None else self._handed
865
+ kept, self._kept = self._kept, None
866
+ again = resume_from_of(getattr(ws, "ready", None)) if kept is not None and self._resume is None else None
867
+ if kept is not None and again is not None:
868
+ at = max(self._base + again, kept)
869
+ if at < start:
870
+ while self._texts_done > 0 and self._texts[self._texts_done - 1][0] >= at:
871
+ self._texts_done -= 1
872
+ for entry in self._texts[self._texts_done :]:
873
+ entry[2] = False
874
+ start = at
751
875
  self._from = start
752
876
  self._trim()
877
+ self._guard(ws)
753
878
  self._flushing = True
754
879
  self._base = start
755
880
  self._handed = start
@@ -812,6 +937,8 @@ class RealtimeSession:
812
937
  return max(0, self._sent - (self._from if self._from is not None else self._handed))
813
938
 
814
939
  def _let_go(self) -> None:
940
+ self._unguard()
941
+ self._kept = None
815
942
  self._flushing = False
816
943
  self._from = None
817
944
  self._ring = []
@@ -833,7 +960,15 @@ class RealtimeSession:
833
960
  url = with_resend(self._stream_url, self._ring_bytes * 1000 / self._bytes_per_second)
834
961
  if self._refile:
835
962
  url = with_refile(url)
836
- return url if self._resume is None else with_resume(url, self._resume)
963
+ if self._heartbeat:
964
+ url = _with_query(url, HEARTBEAT_PARAM, 1)
965
+ if self._kept is not None and self._resume is None:
966
+ url = _with_query(url, KEPT_FROM_PARAM, self._kept - self._base)
967
+ if self._resume is not None:
968
+ url = with_resume(url, self._resume)
969
+ if self._last_seq is not None and not self._whole_file:
970
+ url = _with_query(url, LAST_SEQ_PARAM, self._last_seq)
971
+ return url
837
972
 
838
973
  async def _open_again(self, within_s: Optional[float] = None) -> Optional[ClientConnection]:
839
974
  """The next socket, ready, within one deadline for the whole
@@ -930,10 +1065,16 @@ class RealtimeSession:
930
1065
  stopped answering): open the same ``stream_url`` again, ``LOST_WAITS_S``
931
1066
  apart, for as long as the server answers "try again" (a retryable
932
1067
  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."""
1068
+ session. A try that got no answer at all (the connection refused or
1069
+ dropped before any response) is tried again too, after the waits of
1070
+ ``LOST_UNANSWERED_WAITS_S``, one more such try than it has waits. A refusal for good, the
1071
+ last unanswered try, or the last try spent: ``engine_lost``."""
935
1072
  until = time.monotonic() + LOST_TOTAL_S
936
- for wait in LOST_WAITS_S:
1073
+ unanswered = 0
1074
+ after: Optional[float] = None
1075
+ for step in LOST_WAITS_S:
1076
+ wait = step if after is None else after
1077
+ after = None
937
1078
  left = until - time.monotonic()
938
1079
  if left <= 0:
939
1080
  break
@@ -944,9 +1085,17 @@ class RealtimeSession:
944
1085
  try:
945
1086
  ws = await self._open_again(until - time.monotonic())
946
1087
  except Exception as e:
947
- if isinstance(e, VocalStackError) and e.retryable and getattr(e, "_answered", False):
1088
+ if not (isinstance(e, VocalStackError) and e.retryable):
1089
+ break
1090
+ if getattr(e, "_answered", False):
948
1091
  continue
949
- break
1092
+ if not getattr(e, "_unanswered", False):
1093
+ break
1094
+ if unanswered >= len(LOST_UNANSWERED_WAITS_S):
1095
+ break
1096
+ after = LOST_UNANSWERED_WAITS_S[unanswered]
1097
+ unanswered += 1
1098
+ continue
950
1099
  if ws is None:
951
1100
  return
952
1101
  await self._flush(ws)
@@ -987,7 +1136,7 @@ class RealtimeSession:
987
1136
  if dropped and (not young or self._early_recoveries < EARLY_RECOVERIES):
988
1137
  if young:
989
1138
  self._early_recoveries += 1
990
- self._hold(None)
1139
+ self._hold(None, silent=getattr(ws, "went_silent", False))
991
1140
  await self._recover()
992
1141
  return
993
1142
  raise engine_lost(e.rcvd.code if e is not None and e.rcvd else None)
@@ -1215,6 +1364,7 @@ class RealtimeSession:
1215
1364
  Prefer ``eof()`` to get final commits."""
1216
1365
  self._closed = True
1217
1366
  self._closing.set()
1367
+ self._unguard()
1218
1368
  await self._ws.close()
1219
1369
 
1220
1370
 
@@ -1263,6 +1413,10 @@ class RealtimeSession:
1263
1413
  if frame is None:
1264
1414
  return None
1265
1415
  _hand(self._on_frame, frame)
1416
+ if frame.type == "transcript.committed":
1417
+ seq = getattr(getattr(frame, "segment", None), "seq", None)
1418
+ if isinstance(seq, int) and seq >= 0:
1419
+ self._last_seq = seq if self._last_seq is None else max(self._last_seq, seq)
1266
1420
  if isinstance(frame, SessionDone):
1267
1421
  self.done_reason = frame.reason
1268
1422
  self.stats = frame.stats
@@ -1398,6 +1552,7 @@ class Realtime:
1398
1552
  resend_buffer_bytes: Optional[int] = None,
1399
1553
  on_audio_lost: Optional[Callable[[int], None]] = None,
1400
1554
  refile: bool = False,
1555
+ heartbeat: bool = True,
1401
1556
  **options: Any,
1402
1557
  ) -> RealtimeSession:
1403
1558
  """``create_session``, then open the socket and wait for ``session.ready``.
@@ -1416,6 +1571,7 @@ class Realtime:
1416
1571
  on_audio_lost=on_audio_lost,
1417
1572
  input_kind=_field(options.get("input"), "kind"),
1418
1573
  refile=refile,
1574
+ heartbeat=heartbeat,
1419
1575
  )
1420
1576
 
1421
1577
  async def capabilities(self) -> Capabilities:
@@ -1470,7 +1626,11 @@ async def _collect(session: RealtimeSession, on_progress: Any, on_commit: Any) -
1470
1626
  run = session._reruns
1471
1627
  segments.clear()
1472
1628
  if event.type == "transcript.committed":
1473
- segments.append(event.segment)
1629
+ at = next((i for i, s in enumerate(segments) if s.seq == event.segment.seq), -1)
1630
+ if at == -1:
1631
+ segments.append(event.segment)
1632
+ else:
1633
+ segments[at] = event.segment
1474
1634
  if on_commit is not None:
1475
1635
  on_commit(event.segment)
1476
1636
  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