vocalstack 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
vocalstack/client.py ADDED
@@ -0,0 +1,113 @@
1
+ """The VocalStack client: one class, grouped by resource.
2
+
3
+ import asyncio, os
4
+ from vocalstack import VocalStack
5
+
6
+ async def main():
7
+ async with VocalStack(api_key=os.environ["VOCALSTACK_API_KEY"]) as vs:
8
+ tx = await vs.transcriptions.create(url="https://example.com/talk.mp3")
9
+ await vs.transcriptions.wait_for_job(tx.id)
10
+ snap = await vs.transcriptions.transcript(tx.id)
11
+ print(" ".join(s.text for s in snap.sentences))
12
+
13
+ asyncio.run(main())
14
+
15
+ What is what: a realtime session is a signed token plus one socket,
16
+ nothing stored (``vs.realtime``); a broadcast is the link listeners open;
17
+ a transcription is a file, link, microphone or stream transcribed and
18
+ stored, one continuous transcript however often a live one is paused;
19
+ a job is a file or link transcription's work.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from typing import Callable, Optional, Union
25
+
26
+ import httpx
27
+
28
+ from ._http import DEFAULT_BASE_URL, Transport
29
+ from .realtime import Realtime
30
+ from .resources import (
31
+ Billing,
32
+ Broadcasts,
33
+ Connect,
34
+ Corrections,
35
+ Events,
36
+ Languages,
37
+ Me,
38
+ Meta,
39
+ Rtmp,
40
+ Search,
41
+ ShareLinks,
42
+ SpeakerInvites,
43
+ Speakers,
44
+ Tags,
45
+ Transcriptions,
46
+ Uploads,
47
+ Voices,
48
+ )
49
+ from .realtime import DEFAULT_READY_DEADLINE_S
50
+
51
+
52
+ class VocalStack:
53
+ """``api_key``: an API key (``vs_key_``), for a server. ``token``
54
+ instead: a signed-in person's access token or a browser token, or a
55
+ callable returning one (read per request); not with ``api_key``. ``base_url`` defaults to
56
+ ``https://api.vocalstack.com``. A ``429`` is retried after its
57
+ ``Retry-After`` (at most 60 s) up to ``max_retries`` times."""
58
+
59
+ def __init__(
60
+ self,
61
+ base_url: Optional[str] = None,
62
+ *,
63
+ api_key: Optional[str] = None,
64
+ token: Union[None, str, Callable[[], Optional[str]]] = None,
65
+ acting_principal: Optional[str] = None,
66
+ device_id: Optional[str] = None,
67
+ http: Optional[httpx.AsyncClient] = None,
68
+ max_retries: int = 2,
69
+ timeout: float = 300.0,
70
+ ready_deadline_s: float = DEFAULT_READY_DEADLINE_S,
71
+ ) -> None:
72
+ t = Transport(
73
+ base_url,
74
+ api_key,
75
+ token,
76
+ http=http,
77
+ acting_principal=acting_principal,
78
+ device_id=device_id,
79
+ max_retries=max_retries,
80
+ timeout=timeout,
81
+ )
82
+ self._t = t
83
+ self.base_url = t.base_url
84
+ self.realtime = Realtime(t, ready_deadline_s)
85
+ self.broadcasts = Broadcasts(t)
86
+ self.transcriptions = Transcriptions(t, ready_deadline_s)
87
+ self.uploads = Uploads(t)
88
+ self.corrections = Corrections(t)
89
+ self.share_links = ShareLinks(t)
90
+ self.tags = Tags(t)
91
+ self.speakers = Speakers(t)
92
+ self.speaker_invites = SpeakerInvites(t)
93
+ self.voices = Voices(t)
94
+ self.search = Search(t)
95
+ self.me = Me(t)
96
+ self.connect = Connect(t)
97
+ self.billing = Billing(t)
98
+ self.languages = Languages(t)
99
+ self.rtmp = Rtmp(t)
100
+ self.events = Events(t)
101
+ self.meta = Meta(t)
102
+
103
+ async def aclose(self) -> None:
104
+ await self._t.aclose()
105
+
106
+ async def __aenter__(self) -> "VocalStack":
107
+ return self
108
+
109
+ async def __aexit__(self, *exc: object) -> None:
110
+ await self.aclose()
111
+
112
+
113
+ __all__ = ["DEFAULT_BASE_URL", "VocalStack"]
vocalstack/errors.py ADDED
@@ -0,0 +1,97 @@
1
+ """Typed exceptions keyed by the contract's closed error-code enum."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import email.utils
6
+ import time
7
+ from typing import Any, Mapping, Optional
8
+
9
+
10
+ class VocalStackError(Exception):
11
+ """Any failure surfaced by this SDK: an HTTP error envelope, a socket
12
+ ``error`` frame, or one the transport synthesizes (``capacity_exceeded``).
13
+
14
+ ``details`` is the envelope's ``data.details`` (for example ``metric``,
15
+ ``balance``, ``required``, ``plan``, ``topUpUrl`` on ``insufficient_credit``);
16
+ ``headers`` are the response headers (``Retry-After``, ``RateLimit-*``,
17
+ ``WWW-Authenticate``) when the error came from an HTTP response.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ code: str,
23
+ message: str,
24
+ *,
25
+ retryable: bool = False,
26
+ status: Optional[int] = None,
27
+ details: Any = None,
28
+ headers: Optional[Mapping[str, str]] = None,
29
+ ) -> None:
30
+ super().__init__(message)
31
+ self.code = code
32
+ self.message = message
33
+ self.retryable = retryable
34
+ self.status = status
35
+ self.details = details
36
+ self.headers = headers
37
+
38
+ @property
39
+ def retry_after(self) -> Optional[float]:
40
+ """Seconds the server asked the caller to wait (``Retry-After``), if it said."""
41
+ v = self.headers.get("retry-after") if self.headers is not None else None
42
+ if not v:
43
+ return None
44
+ try:
45
+ return float(v)
46
+ except ValueError:
47
+ pass
48
+ try:
49
+ at = email.utils.parsedate_to_datetime(v).timestamp()
50
+ except (TypeError, ValueError):
51
+ return None
52
+ return max(0.0, at - time.time())
53
+
54
+ def __repr__(self) -> str:
55
+ return (
56
+ f"VocalStackError(code={self.code!r}, message={self.message!r}, "
57
+ f"retryable={self.retryable}, status={self.status}, details={self.details!r})"
58
+ )
59
+
60
+
61
+ def capacity_exceeded(message: str) -> VocalStackError:
62
+ """Synthesized by the transport: a saturated fleet queues the socket
63
+ upgrade at the proxy (it hangs) or answers a bare 503, and the wire
64
+ never carries the envelope."""
65
+ return VocalStackError("capacity_exceeded", message, retryable=True)
66
+
67
+
68
+ def from_envelope(
69
+ body: Any, status: Optional[int] = None, headers: Optional[Mapping[str, str]] = None
70
+ ) -> VocalStackError:
71
+ if isinstance(body, dict) and isinstance(body.get("code"), str):
72
+ data = body.get("data") or {}
73
+ return VocalStackError(
74
+ body["code"],
75
+ body.get("message", body["code"]),
76
+ retryable=bool(data.get("retryable", False)),
77
+ status=status,
78
+ details=data.get("details"),
79
+ headers=headers,
80
+ )
81
+ return VocalStackError(
82
+ "internal", f"unexpected error (status {status})", status=status, headers=headers
83
+ )
84
+
85
+
86
+ def from_oauth(
87
+ body: Any, status: Optional[int] = None, headers: Optional[Mapping[str, str]] = None
88
+ ) -> VocalStackError:
89
+ """A token endpoint's ``400 { error, error_description }`` (RFC 6749
90
+ §5.2) as a :class:`VocalStackError` whose ``code`` is the ``error``
91
+ (``invalid_request``, ``invalid_grant``, ``unsupported_grant_type``);
92
+ any other answer goes through the envelope."""
93
+ if status == 400 and isinstance(body, dict) and isinstance(body.get("error"), str):
94
+ return VocalStackError(
95
+ body["error"], body.get("error_description") or body["error"], status=status, headers=headers
96
+ )
97
+ return from_envelope(body, status, headers)