vocalstack 1.2.3__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.3
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
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "vocalstack"
7
- version = "1.2.3"
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.3"
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
 
@@ -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``,
@@ -453,6 +480,9 @@ class RealtimeSession:
453
480
  _size("resend_buffer_bytes", resend_buffer_bytes)
454
481
  _size("resend_buffer_s", resend_buffer_s)
455
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)
456
486
  plain = with_resend(stream_url, ring * 1000 / bytes_per_second)
457
487
  if refile and input_kind in ("file", "url"):
458
488
  plain = with_refile(plain)
@@ -487,6 +517,7 @@ class RealtimeSession:
487
517
  input_kind=input_kind,
488
518
  refile=refile,
489
519
  heartbeat=heartbeat,
520
+ opus=opus,
490
521
  )
491
522
 
492
523
  @staticmethod
@@ -579,8 +610,10 @@ class RealtimeSession:
579
610
  that ended with an error, each send is reported to ``on_audio_lost``
580
611
  with its size, which is how a caller that only sends learns of it.
581
612
  """
582
- data = bytes(pcm)
583
- 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)
584
617
  if self._closed or self.done_reason is not None:
585
618
  return
586
619
  if self._error is not None:
@@ -808,6 +841,10 @@ class RealtimeSession:
808
841
  elif start < self._ring_start:
809
842
  lost = self._ring_start - start
810
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)
811
848
  self._resume = start - self._base if valid else None
812
849
  self._taken = valid or whole
813
850
  self._from = start
@@ -828,8 +865,8 @@ class RealtimeSession:
828
865
  if self._kept is not None:
829
866
  floor = min(floor, self._kept)
830
867
  drop = 0
831
- while drop < len(ring) and self._ring_start + len(ring[drop]) <= floor:
832
- 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])
833
870
  drop += 1
834
871
  if drop:
835
872
  del ring[:drop]
@@ -892,15 +929,15 @@ class RealtimeSession:
892
929
  self._texts_done += 1
893
930
  await ws.send(entry[1])
894
931
  entry[2] = True
895
- while i < len(self._ring) and off + len(self._ring[i]) <= pos:
896
- off += len(self._ring[i])
932
+ while i < len(self._ring) and off + _pcm(self._ring[i]) <= pos:
933
+ off += _pcm(self._ring[i])
897
934
  i += 1
898
935
  if i >= len(self._ring):
899
936
  break
900
937
  chunk = self._ring[i]
901
- end = off + len(chunk)
938
+ end = off + _pcm(chunk)
902
939
  self._started = end
903
- 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))
904
941
  self._from = end
905
942
  self._handed = end
906
943
  except websockets.ConnectionClosed as e:
@@ -1560,8 +1597,20 @@ class Realtime:
1560
1597
  """``create_session``, then open the socket and wait for ``session.ready``.
1561
1598
  ``on_frame`` sees every server frame, lifecycle included (see
1562
1599
  :meth:`RealtimeSession.connect`, also for ``resend_buffer_s``,
1563
- ``resend_buffer_bytes``, ``on_audio_lost`` and ``refile``)."""
1564
- 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)
1565
1614
  return await RealtimeSession.connect(
1566
1615
  created.session_id,
1567
1616
  created.stream_url,
@@ -1574,6 +1623,7 @@ class Realtime:
1574
1623
  input_kind=_field(options.get("input"), "kind"),
1575
1624
  refile=refile,
1576
1625
  heartbeat=heartbeat,
1626
+ opus=wants_opus,
1577
1627
  )
1578
1628
 
1579
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
File without changes