vocalstack 1.2.2__tar.gz → 1.3.1__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.2
3
+ Version: 1.3.1
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
@@ -124,9 +124,10 @@ async with VocalStack(api_key=key) as vs:
124
124
  `session.heartbeat` frame that often, whatever the session is doing. When
125
125
  nothing at all arrived for three times `heartbeatS` (12 s at most: the server
126
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
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
128
129
  (`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
+ (`resumeFrom`), so what the lost socket swallowed is not lost; when it names
130
131
  none, nothing is sent again. A server that sends no `heartbeatS` is never
131
132
  judged by its silence, and a client whose own timers stood still (a blocked
132
133
  thread, a sleeping machine) starts the count again. `heartbeat=False` on `connect` and `publish`
@@ -111,9 +111,10 @@ async with VocalStack(api_key=key) as vs:
111
111
  `session.heartbeat` frame that often, whatever the session is doing. When
112
112
  nothing at all arrived for three times `heartbeatS` (12 s at most: the server
113
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
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
115
116
  (`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
+ (`resumeFrom`), so what the lost socket swallowed is not lost; when it names
117
118
  none, nothing is sent again. A server that sends no `heartbeatS` is never
118
119
  judged by its silence, and a client whose own timers stood still (a blocked
119
120
  thread, a sleeping machine) starts the count again. `heartbeat=False` on `connect` and `publish`
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "vocalstack"
7
- version = "1.2.2"
7
+ version = "1.3.1"
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.2"
32
+ __version__ = "1.3.1"
33
33
 
34
34
  __all__ = [
35
35
  "DEFAULT_BASE_URL",
@@ -21,7 +21,7 @@ ErrorCode = Union[Literal["invalid_audio", "invalid_options", "invalid_token", "
21
21
 
22
22
  SampleWarning = Union[Literal["overlaps", "noisy", "weak_voice", "unclear", "cut_off"], str]
23
23
 
24
- AudioEncoding = Union[Literal["pcm_f32le"], str]
24
+ AudioEncoding = Union[Literal["pcm_f32le", "opus"], str]
25
25
 
26
26
  FixKind = Union[Literal["extension", "scheme", "page_stream"], str]
27
27
 
@@ -208,6 +208,7 @@ class AppearanceView(_Base):
208
208
 
209
209
  class AudioCapabilities(_Base):
210
210
  channels: List[int]
211
+ codecs: Optional[List[AudioEncoding]] = None
211
212
  encodings: List[AudioEncoding]
212
213
  sample_rates: List[int] = Field(alias="sampleRates")
213
214
 
@@ -215,6 +216,7 @@ class AudioCapabilities(_Base):
215
216
  class AudioFormat(_Base):
216
217
  channels: Optional[int] = None
217
218
  encoding: Optional[AudioEncoding] = None
219
+ pre_skip: Optional[int] = Field(default=None, alias="preSkip")
218
220
  sample_rate: Optional[int] = Field(default=None, alias="sampleRate")
219
221
 
220
222
 
@@ -1420,7 +1422,7 @@ stream, an RTMP encoder), which may feed broadcasts (`broadcasts`)."""
1420
1422
  media: Optional[List["MediaSummary"]] = None
1421
1423
  metrics: Optional["TranscriptionMetrics"] = None
1422
1424
  name: str
1423
- origin: Union[Literal["dashboard", "api", "extension", "desktop_app", "ios_app", "obs", "wordpress", "payload", "strapi", "sanity", "contentful", "mcp", "broadcast", "unknown"], str]
1425
+ origin: Union[Literal["dashboard", "api", "extension", "desktop_app", "ios_app", "android_app", "obs", "wordpress", "payload", "strapi", "sanity", "contentful", "mcp", "broadcast", "unknown"], str]
1424
1426
  owner_principal_id: str = Field(alias="ownerPrincipalId")
1425
1427
  peak_latency_s: Optional[float] = Field(default=None, alias="peakLatencyS")
1426
1428
  peak_listeners: Optional[int] = Field(default=None, alias="peakListeners")
@@ -2026,7 +2028,21 @@ class Clock(_Base):
2026
2028
  wall: float
2027
2029
 
2028
2030
 
2029
- ClientFrame = Annotated[Union[Eof, Cancel, SessionUpdate, Clock], Field(discriminator="type")]
2031
+ class ClientMarks(_Base):
2032
+ backlog_s: Optional[float] = Field(default=None, alias="backlogS")
2033
+ first_sent_at: Optional[float] = Field(default=None, alias="firstSentAt")
2034
+ mic_at: Optional[float] = Field(default=None, alias="micAt")
2035
+ pressed_at: Optional[float] = Field(default=None, alias="pressedAt")
2036
+ sent_at: float = Field(alias="sentAt")
2037
+ type: Literal["client.marks"] = "client.marks"
2038
+
2039
+
2040
+ class AudioFormat(_Base):
2041
+ encoding: AudioEncoding
2042
+ type: Literal["audio.format"] = "audio.format"
2043
+
2044
+
2045
+ ClientFrame = Annotated[Union[Eof, Cancel, SessionUpdate, Clock, ClientMarks, AudioFormat], Field(discriminator="type")]
2030
2046
 
2031
2047
  class SessionLoading(_Base):
2032
2048
  stage: LoadingStage
@@ -77,6 +77,23 @@ LIVE_FRAMES = 256
77
77
  RESEND_PARAM = "resend"
78
78
  HEARTBEAT_PARAM = "heartbeat"
79
79
  KEPT_FROM_PARAM = "kept_from"
80
+ OPUS_PACKET_BYTES = 1280
81
+
82
+
83
+ class _Packet(bytes):
84
+ pcm = OPUS_PACKET_BYTES
85
+
86
+
87
+ def _pcm(chunk: bytes) -> int:
88
+ return getattr(chunk, "pcm", len(chunk))
89
+
90
+
91
+ def with_opus(url: str) -> str:
92
+ """``audio=opus`` on a stream URL: every binary frame is one raw Opus
93
+ packet of 20 ms (mono, no container), counted as 1,280 bytes."""
94
+ hash_at = url.find("#")
95
+ head, tail = (url, "") if hash_at == -1 else (url[:hash_at], url[hash_at:])
96
+ return f"{head}{'&' if '?' in head else '?'}audio=opus{tail}"
80
97
  HEARTBEATS_MISSED = 3
81
98
  WATCH_EVERY_MOST_S = 1.0
82
99
  WATCH_LATE_S = 2.0
@@ -326,8 +343,11 @@ class RealtimeSession:
326
343
  input_kind: Optional[str] = None,
327
344
  refile: bool = False,
328
345
  heartbeat: bool = True,
346
+ opus: bool = False,
329
347
  ) -> None:
330
348
  self.session_id = session_id
349
+ self._opus = opus and input_kind not in ("file", "url")
350
+ self.encoding = "opus" if self._opus else "pcm_f32le"
331
351
  self._heartbeat = heartbeat
332
352
  self._kept: Optional[int] = None
333
353
  self._watcher: Optional[asyncio.TimerHandle] = None
@@ -391,9 +411,16 @@ class RealtimeSession:
391
411
  input_kind: Optional[str] = None,
392
412
  refile: bool = False,
393
413
  heartbeat: bool = True,
414
+ opus: bool = False,
394
415
  ) -> "RealtimeSession":
395
416
  """Open the WS and wait for ``session.ready``.
396
417
 
418
+ ``opus`` (live only, where ``capabilities().audio.codecs`` lists
419
+ ``opus``): ``send_audio`` then takes one raw Opus packet of 20 ms
420
+ (mono, no container) per call, encoded by the caller, and every
421
+ byte count (the resend buffer, ``on_audio_lost``) is in decoded
422
+ ``pcm_f32le`` bytes, 1,280 a packet.
423
+
397
424
  ``on_frame`` sees every server text frame as it arrives, parsed:
398
425
  the lifecycle frames the iterator keeps to itself
399
426
  (``session.loading``, ``session.ready``, ``session.done``,
@@ -442,15 +469,20 @@ class RealtimeSession:
442
469
  Where ``session.ready`` answers with ``heartbeatS``, a socket on
443
470
  which nothing at all arrived for three times that long is taken for
444
471
  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.
472
+ with no close frame. The reconnect after any live socket lost with
473
+ no close frame (also one whose server died) offers the audio still
474
+ kept (``kept_from``) and sends it again from the byte
475
+ ``session.ready`` names (``resumeFrom``), or sends nothing again
476
+ when it names none.
448
477
  A server that says no ``heartbeatS`` is never judged by its silence.
449
478
  """
450
479
  if resend_buffer_bytes is not None:
451
480
  _size("resend_buffer_bytes", resend_buffer_bytes)
452
481
  _size("resend_buffer_s", resend_buffer_s)
453
482
  ring = int(resend_buffer_bytes) if resend_buffer_bytes is not None else resend_bytes(None, resend_buffer_s)
483
+ opus = opus and input_kind not in ("file", "url")
484
+ if opus:
485
+ stream_url = with_opus(stream_url)
454
486
  plain = with_resend(stream_url, ring * 1000 / bytes_per_second)
455
487
  if refile and input_kind in ("file", "url"):
456
488
  plain = with_refile(plain)
@@ -485,6 +517,7 @@ class RealtimeSession:
485
517
  input_kind=input_kind,
486
518
  refile=refile,
487
519
  heartbeat=heartbeat,
520
+ opus=opus,
488
521
  )
489
522
 
490
523
  @staticmethod
@@ -577,8 +610,10 @@ class RealtimeSession:
577
610
  that ended with an error, each send is reported to ``on_audio_lost``
578
611
  with its size, which is how a caller that only sends learns of it.
579
612
  """
580
- data = bytes(pcm)
581
- n = len(data)
613
+ data = _Packet(pcm) if self._opus else bytes(pcm)
614
+ if self._opus and not data:
615
+ return
616
+ n = _pcm(data)
582
617
  if self._closed or self.done_reason is not None:
583
618
  return
584
619
  if self._error is not None:
@@ -806,6 +841,10 @@ class RealtimeSession:
806
841
  elif start < self._ring_start:
807
842
  lost = self._ring_start - start
808
843
  start = self._ring_start
844
+ if self._opus and self._file is None:
845
+ start = self._ring_start + (start - self._ring_start) // OPUS_PACKET_BYTES * OPUS_PACKET_BYTES
846
+ if valid:
847
+ start = max(self._ring_start, start - OPUS_PACKET_BYTES)
809
848
  self._resume = start - self._base if valid else None
810
849
  self._taken = valid or whole
811
850
  self._from = start
@@ -826,8 +865,8 @@ class RealtimeSession:
826
865
  if self._kept is not None:
827
866
  floor = min(floor, self._kept)
828
867
  drop = 0
829
- while drop < len(ring) and self._ring_start + len(ring[drop]) <= floor:
830
- self._ring_start += len(ring[drop])
868
+ while drop < len(ring) and self._ring_start + _pcm(ring[drop]) <= floor:
869
+ self._ring_start += _pcm(ring[drop])
831
870
  drop += 1
832
871
  if drop:
833
872
  del ring[:drop]
@@ -890,15 +929,15 @@ class RealtimeSession:
890
929
  self._texts_done += 1
891
930
  await ws.send(entry[1])
892
931
  entry[2] = True
893
- while i < len(self._ring) and off + len(self._ring[i]) <= pos:
894
- off += len(self._ring[i])
932
+ while i < len(self._ring) and off + _pcm(self._ring[i]) <= pos:
933
+ off += _pcm(self._ring[i])
895
934
  i += 1
896
935
  if i >= len(self._ring):
897
936
  break
898
937
  chunk = self._ring[i]
899
- end = off + len(chunk)
938
+ end = off + _pcm(chunk)
900
939
  self._started = end
901
- await ws.send(chunk[pos - off :] if pos > off else chunk)
940
+ await ws.send(chunk[pos - off :] if pos > off and not self._opus else bytes(chunk))
902
941
  self._from = end
903
942
  self._handed = end
904
943
  except websockets.ConnectionClosed as e:
@@ -1136,7 +1175,7 @@ class RealtimeSession:
1136
1175
  if dropped and (not young or self._early_recoveries < EARLY_RECOVERIES):
1137
1176
  if young:
1138
1177
  self._early_recoveries += 1
1139
- self._hold(None, silent=getattr(ws, "went_silent", False))
1178
+ self._hold(None, silent=not self._whole_file or getattr(ws, "went_silent", False))
1140
1179
  await self._recover()
1141
1180
  return
1142
1181
  raise engine_lost(e.rcvd.code if e is not None and e.rcvd else None)
@@ -1558,8 +1597,20 @@ class Realtime:
1558
1597
  """``create_session``, then open the socket and wait for ``session.ready``.
1559
1598
  ``on_frame`` sees every server frame, lifecycle included (see
1560
1599
  :meth:`RealtimeSession.connect`, also for ``resend_buffer_s``,
1561
- ``resend_buffer_bytes``, ``on_audio_lost`` and ``refile``)."""
1562
- created = await self.create_session(**options)
1600
+ ``resend_buffer_bytes``, ``on_audio_lost`` and ``refile``).
1601
+ With ``audio={"encoding": "opus"}`` ``send_audio`` takes Opus packets
1602
+ (see :meth:`RealtimeSession.connect`); a server that does not take
1603
+ Opus answers ``invalid_options`` and the session is created again
1604
+ with ``pcm_f32le``: read ``session.encoding``."""
1605
+ wants_opus = _field(options.get("audio"), "encoding") == "opus"
1606
+ try:
1607
+ created = await self.create_session(**options)
1608
+ except VocalStackError as e:
1609
+ if not wants_opus or e.code != "invalid_options":
1610
+ raise
1611
+ options = {k: v for k, v in options.items() if k != "audio"}
1612
+ wants_opus = False
1613
+ created = await self.create_session(**options)
1563
1614
  return await RealtimeSession.connect(
1564
1615
  created.session_id,
1565
1616
  created.stream_url,
@@ -1572,6 +1623,7 @@ class Realtime:
1572
1623
  input_kind=_field(options.get("input"), "kind"),
1573
1624
  refile=refile,
1574
1625
  heartbeat=heartbeat,
1626
+ opus=wants_opus,
1575
1627
  )
1576
1628
 
1577
1629
  async def capabilities(self) -> Capabilities:
@@ -376,11 +376,15 @@ class Transcriptions(_ParentResource):
376
376
  resend_buffer_s: float = 30.0,
377
377
  resend_buffer_bytes: Optional[int] = None,
378
378
  on_audio_lost: Optional[Callable[[int], None]] = None,
379
+ opus: bool = False,
379
380
  ) -> "RealtimeSession":
380
381
  """Open the publisher socket a grant names and wait until it is
381
382
  ready: ``send_audio`` raw PCM (f32le, 16 kHz, mono), end with ``eof()``.
382
383
  ``on_frame`` sees every server frame, lifecycle included; the resend
383
- options are :meth:`RealtimeSession.connect`'s."""
384
+ options are :meth:`RealtimeSession.connect`'s. ``opus=True``:
385
+ ``send_audio`` takes Opus packets the caller encodes, where the
386
+ server's ``capabilities().audio.codecs`` lists ``opus`` (otherwise
387
+ the session stays ``pcm_f32le``: read ``session.encoding``)."""
384
388
  from .realtime import RealtimeSession
385
389
 
386
390
  if not grant.stream_url:
@@ -393,8 +397,16 @@ class Transcriptions(_ParentResource):
393
397
  resend_buffer_s=resend_buffer_s,
394
398
  resend_buffer_bytes=resend_buffer_bytes,
395
399
  on_audio_lost=on_audio_lost,
400
+ opus=opus and await self._takes_opus(),
396
401
  )
397
402
 
403
+ async def _takes_opus(self) -> bool:
404
+ try:
405
+ caps = await self._t.json("GET", "/v1/realtime/capabilities")
406
+ except VocalStackError:
407
+ return False
408
+ return "opus" in ((caps or {}).get("audio") or {}).get("codecs", [])
409
+
398
410
  async def job(self, id: str) -> m.TranscriptionJob:
399
411
  """A file or link transcription's job. States: queued, fetching,
400
412
  transcribing, done, failed, and cropping (waiting for ``start_job``)."""
File without changes
File without changes
File without changes