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/SKILL.md ADDED
@@ -0,0 +1,243 @@
1
+ ---
2
+ name: vocalstack
3
+ description: Use when writing Python code that calls the VocalStack speech API with the vocalstack package, for example to transcribe an audio or video URL or a local file, stream live audio for realtime transcription, fetch or export a transcript (PDF, XLSX, SRT, VTT, text, Markdown, JSON), or search transcripts. Covers installing, API keys, base URLs, five copy-paste programs and error handling (401, 402, 403, 429).
4
+ ---
5
+
6
+ # VocalStack Python SDK
7
+
8
+ The VocalStack API transcribes speech (files, links, live audio), with speaker
9
+ labels and translation. The `vocalstack` package has one asyncio client,
10
+ `VocalStack`, with one group per resource: `vs.transcriptions`,
11
+ `vs.broadcasts`, `vs.search`, `vs.realtime` and a few more
12
+ (listed at the end). Answers are pydantic models with snake_case attributes.
13
+
14
+ ## What is what
15
+
16
+ - A **transcription** is a file, a link, a microphone or a stream, transcribed
17
+ and stored. Create one with `await vs.transcriptions.create(...)`. Its id is
18
+ what you read the transcript and exports with:
19
+ `await vs.transcriptions.transcript(tx.id)`. A live one is one continuous
20
+ transcript however often it is paused and resumed.
21
+ - A **job** is a file or link transcription's work:
22
+ `await vs.transcriptions.wait_for_job(tx.id)` polls it until it is `done` or `failed`
23
+ (`on_progress=lambda job: ...` sees each read: `job.state`, `job.progress.pct`).
24
+ - A **broadcast** is a link listeners open to follow a live transcription.
25
+ - A **realtime session** (`vs.realtime`) is a socket you stream audio into and
26
+ read the transcript from. Nothing is stored. "Session" means only this.
27
+
28
+ ## Install
29
+
30
+ ```sh
31
+ python3 -m venv .venv && . .venv/bin/activate # system Pythons refuse a bare pip install
32
+ pip install vocalstack # Python 3.10 or newer
33
+ ```
34
+
35
+ Live transcription (program 4) also needs `ffmpeg` on PATH.
36
+
37
+ Speaker numbers start at 0. A speaker of `-1` means speaker labels were off
38
+ for that transcription, so print the text without a speaker.
39
+
40
+ ## Auth and base URL
41
+
42
+ - Read the key from `VOCALSTACK_API_KEY` and pass it as `api_key`. It goes
43
+ out as `Authorization: Bearer <key>`, also on sockets.
44
+ - An API key starts with `vs_key_`. There is one kind of key: every call is
45
+ real usage on the account's tier and quotas.
46
+ - Keys are for servers. Never put a key in browser code or in a URL. The API
47
+ refuses a key sent from a web page (`Origin` header) or in a query string.
48
+ - Scopes: `read` (read transcripts, search, export), `write` (transcribe
49
+ files and links, open realtime sessions, change things), `recordings:publish`
50
+ (start, pause and stop a stored live transcription and send it audio), or `*`.
51
+ - Base URL: `https://api.vocalstack.com` (the default). Override it with
52
+ `VOCALSTACK_BASE_URL` (for example, a local or staging server).
53
+
54
+ Every program below opens the client the same way, inside `async def main()`
55
+ run with `asyncio.run(main())` (a `None` base URL means the default):
56
+
57
+ ```python
58
+ async with VocalStack(os.environ.get("VOCALSTACK_BASE_URL"), api_key=os.environ["VOCALSTACK_API_KEY"]) as vs:
59
+ ...
60
+ ```
61
+
62
+ ## 1. Transcribe a URL and wait for the result
63
+
64
+ The server fetches the link itself, so it must be a public http(s) address.
65
+ Private, loopback and cloud-metadata addresses are refused.
66
+
67
+ ```python
68
+ import asyncio, os
69
+ from vocalstack import VocalStack
70
+
71
+ async def main():
72
+ async with VocalStack(os.environ.get("VOCALSTACK_BASE_URL"), api_key=os.environ["VOCALSTACK_API_KEY"]) as vs:
73
+ tx = await vs.transcriptions.create(
74
+ url="https://raw.githubusercontent.com/openai/whisper/main/tests/jfk.flac",
75
+ name="JFK sample",
76
+ )
77
+ job = await vs.transcriptions.wait_for_job(tx.id) # queued -> fetching -> transcribing -> done | failed
78
+ if job.state != "done":
79
+ raise SystemExit(f"transcription {job.state}: {job.error}")
80
+ snap = await vs.transcriptions.transcript(tx.id)
81
+ for s in snap.sentences:
82
+ print(f"[speaker {s.speaker}] {s.text}" if s.speaker >= 0 else s.text)
83
+ print("transcription id", tx.id)
84
+
85
+ asyncio.run(main())
86
+ ```
87
+
88
+ ## 2. Transcribe a local file
89
+
90
+ ```python
91
+ import asyncio, os, sys
92
+ from vocalstack import VocalStack
93
+
94
+ async def main(path): # mp3, wav, flac, ogg, m4a, mp4 ...
95
+ async with VocalStack(os.environ.get("VOCALSTACK_BASE_URL"), api_key=os.environ["VOCALSTACK_API_KEY"]) as vs:
96
+ tx = await vs.transcriptions.create(
97
+ file=path, # a path, bytes, or an open binary file
98
+ settings={"spokenLanguage": "en", "speakerLabels": "on"}, # both optional; "auto" (default) | "on" | "off"
99
+ # Off unless asked for: settings summary, title, summaryTranslations,
100
+ # translationTts (text-to-speech of translations), and share_link=True (a public share link).
101
+ )
102
+ job = await vs.transcriptions.wait_for_job(tx.id)
103
+ if job.state != "done":
104
+ raise SystemExit(f"transcription {job.state}: {job.error}")
105
+ snap = await vs.transcriptions.transcript(tx.id)
106
+ print(" ".join(s.text for s in snap.sentences))
107
+
108
+ asyncio.run(main(sys.argv[1]))
109
+ ```
110
+
111
+ ## 3. Fetch a transcript or an export file
112
+
113
+ The transcript holds segments (with word timings), sentences and speakers.
114
+ Export formats are `pdf`, `xlsx`, `srt`, `vtt`, `txt`, `md` and `json`; add
115
+ `lang="<code>"` for a translated file, `speaker_labels="off"` (or `"on"`, `"auto"`),
116
+ `timestamps="off"`, `start_s`/`end_s` for one part and `summary=True`. `export` returns the file's bytes.
117
+
118
+ ```python
119
+ import asyncio, os, sys
120
+ from vocalstack import VocalStack
121
+
122
+ async def main(tx_id):
123
+ async with VocalStack(os.environ.get("VOCALSTACK_BASE_URL"), api_key=os.environ["VOCALSTACK_API_KEY"]) as vs:
124
+ snap = await vs.transcriptions.transcript(tx_id)
125
+ print(len(snap.segments), "segments,", len(snap.sentences), "sentences, state", snap.state)
126
+ with open("transcript.srt", "wb") as f:
127
+ f.write(await vs.transcriptions.export(tx_id, "srt"))
128
+
129
+ asyncio.run(main(sys.argv[1]))
130
+ ```
131
+
132
+ ## 4. Live transcription from a microphone or a file
133
+
134
+ A live transcription takes raw PCM: 32-bit float little-endian, 16 kHz, mono.
135
+ Create it, start it, and open the publisher socket the grant names.
136
+ Here ffmpeg decodes a file, and `pace_realtime` sends it at realtime speed and
137
+ then calls `eof()`. For a microphone, read ffmpeg's stdout as it arrives
138
+ (`-f avfoundation -i :0` on macOS, `-f pulse -i default` on Linux) and call
139
+ `await stream.send_audio(chunk)` for each chunk.
140
+
141
+ ```python
142
+ import asyncio, os, subprocess, sys
143
+ from vocalstack import VocalStack, pace_realtime
144
+
145
+ async def main(path):
146
+ async with VocalStack(os.environ.get("VOCALSTACK_BASE_URL"), api_key=os.environ["VOCALSTACK_API_KEY"]) as vs:
147
+ tx = await vs.transcriptions.create_live(name="Live demo", settings={"spokenLanguage": "en"})
148
+ grant = await vs.transcriptions.start(tx.id)
149
+
150
+ pcm = subprocess.run(["ffmpeg", "-loglevel", "error", "-i", path,
151
+ "-f", "f32le", "-ac", "1", "-ar", "16000", "-"],
152
+ check=True, capture_output=True).stdout
153
+
154
+ # A cold engine can take a while to load, so allow a long ready deadline.
155
+ async with await vs.transcriptions.publish(grant, ready_deadline_s=180) as stream:
156
+ feeder = asyncio.create_task(pace_realtime(stream, pcm)) # then eof(), which ends the transcription
157
+ async for event in stream:
158
+ if event.type == "transcript.committed":
159
+ print(f"[speaker {event.segment.speaker}] {event.segment.text}", flush=True)
160
+ await feeder
161
+
162
+ # To end it without eof(): vs.transcriptions.pause(tx.id), then vs.transcriptions.stop(tx.id).
163
+ # A stopped transcription cannot be started again: create a new one.
164
+ snap = await vs.transcriptions.transcript(tx.id)
165
+ print("final:", " ".join(s.text for s in snap.sentences))
166
+
167
+ asyncio.run(main(sys.argv[1]))
168
+ ```
169
+
170
+ To transcribe without storing anything, use a realtime session instead:
171
+ `(await vs.realtime.transcribe_file("talk.mp3")).text`.
172
+
173
+ ## 5. Search transcripts
174
+
175
+ ```python
176
+ import asyncio, os, sys
177
+ from vocalstack import VocalStack
178
+
179
+ async def main(q): # 2+ characters
180
+ async with VocalStack(os.environ.get("VOCALSTACK_BASE_URL"), api_key=os.environ["VOCALSTACK_API_KEY"]) as vs:
181
+ res = await vs.search.query(q, limit=5)
182
+ for h in res.hits:
183
+ print(f"{h.link_name} @ {h.media_start:.1f}s [speaker {h.speaker}]: {h.text} (transcription {h.transcription_id})")
184
+
185
+ asyncio.run(main(sys.argv[1]))
186
+ ```
187
+
188
+ By meaning, in any language, even with none of the words (vector search). Each
189
+ hit's `passage` is its whole paragraph: give the passages to your own model as
190
+ context to answer questions about what was said (RAG). Pay as you go counts 60
191
+ an hour (`allowance`); Premium and Enterprise have no limit.
192
+
193
+ ```python
194
+ res = await vs.search.vector("how much does housing cost")
195
+ for h in res.hits:
196
+ print(f"{h.similarity:.2f}", h.passage.media_start, h.passage.text)
197
+ ```
198
+
199
+ ## Errors
200
+
201
+ A failed call raises `vocalstack.VocalStackError` with `.code`, `.message`,
202
+ `.status`, `.retryable`, `.details` (the body's `data.details`), `.headers`
203
+ and `.retry_after` (seconds, from `Retry-After`). A `429`, and a
204
+ `503 unavailable` on a call that is safe to repeat, is retried for you after
205
+ its `Retry-After`, twice by default (`max_retries` on the client).
206
+
207
+ | Status | `code` | What to do |
208
+ |---|---|---|
209
+ | 401 | `invalid_token`, `key_expired`, `key_revoked` | Check `VOCALSTACK_API_KEY`. Use the replacement key, or create a new one. |
210
+ | 403 | `forbidden` | Usually a missing scope: the message names it, and `e.headers["www-authenticate"]` lists the scopes the route needs. A suspended key or account gets `suspended`. |
211
+ | 403 | `terms_acceptance_required` | The account has not accepted the current Terms of Service and Privacy Policy: someone signs in to the Dashboard and accepts them (an organisation's keys work once an owner or admin has). Not retryable until then. |
212
+ | 402 | `insufficient_credit` | The account's credit is out, or does not cover the transcription: every transcription is billed at least the plan's minimum (`rates.minimumSeconds`, 5 minutes). `details`: `balance`, `plan`, `topUpUrl`, and `required` when the cost was known up front. Add credit; `await vs.billing.get()` shows the balance. |
213
+ | 409 | `payment_method_required` | Auto top-up (`vs.billing.set_auto_top_up`) and the portal (`vs.billing.portal()`) need a payment first (`vs.billing.create_checkout(kind="topup", amount=25, accept_terms=True)` opens one; a signed-in person's token, never an API key). |
214
+ | 402 | `quota_exceeded` | The plan's transcriptions-at-once limit is reached. `details`: `metric` (`concurrent_transcriptions`), `limit`, `used`, `plan`, `topUpUrl`. |
215
+ | 429 | `rate_limited` | Retried automatically; if it still fails, wait `e.retry_after` seconds. Every response carries `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`. |
216
+ | 503 | `unavailable` | The service is waking (its database was asleep). Retried automatically after `Retry-After` (2 s) on calls that are safe to repeat: GET, HEAD, DELETE, or any call with `idempotency_key=`. A create without a key is not retried: retry it yourself, with an `idempotency_key` so it cannot run twice. A realtime socket refused this way raises `unavailable`; a bare 503 there is `capacity_exceeded`. |
217
+
218
+ ```python
219
+ from vocalstack import VocalStackError
220
+ try:
221
+ await vs.search.query("country")
222
+ except VocalStackError as e:
223
+ if e.code in ("insufficient_credit", "quota_exceeded"):
224
+ print("billing:", e.message, e.details)
225
+ else:
226
+ print(e.status, e.code, e.message)
227
+ ```
228
+
229
+ ## More
230
+
231
+ - The other groups: `vs.transcriptions` (also `list`, `get`, `update`, `archive`,
232
+ `restore`, `purge`, `list_share_links`, `create_share_link`, `list_scripts`,
233
+ `pause`, `resume`, `stop`, `summarize`, `summary`, `translation`, `audio`,
234
+ `subscribe`, `history`, `corrections`, `apply_corrections`, `request_voice`),
235
+ `vs.corrections` (`revert`), `vs.share_links`, `vs.speakers` (with `invite`, `list_invites`, `renew_invite`,
236
+ `cancel_invite`), `vs.speaker_invites` (the invited person's link, no key), `vs.voices`, `vs.broadcasts`,
237
+ `vs.me` (`get`, `usage`), `vs.languages`, `vs.rtmp`, `vs.events`, `vs.meta`.
238
+ Each method is its operation's name in the OpenAPI document, in snake_case
239
+ (`transcriptions.create` is `POST /v1/transcriptions`).
240
+ - `<base>/llms.txt` lists every operation in a form written for agents.
241
+ `<base>/llms-full.txt` adds parameters, auth mode, tier and scopes.
242
+ - `<base>/docs` is the interactive reference. `<base>/v1/openapi.json` is
243
+ the OpenAPI document; the SDK's models are generated from it.
vocalstack/__init__.py ADDED
@@ -0,0 +1,61 @@
1
+ """VocalStack speech API SDK (asyncio): one client, ``VocalStack``, grouped
2
+ by resource, with models generated from the API's one contract."""
3
+
4
+ from . import _models as models
5
+ from ._models import (
6
+ Broadcast,
7
+ Capabilities,
8
+ CommittedSegment,
9
+ CreateSessionResponse,
10
+ DraftSegment,
11
+ Health,
12
+ PublishGrant,
13
+ SearchResults,
14
+ ServerFrame,
15
+ SessionOptions,
16
+ SessionStats,
17
+ Transcription,
18
+ TranscriptionJob,
19
+ TranscriptCommitted,
20
+ TranscriptDraft,
21
+ TranscriptProgress,
22
+ TranscriptSnapshot,
23
+ TranscriptWords,
24
+ Word,
25
+ )
26
+ from ._http import DEFAULT_BASE_URL
27
+ from .client import VocalStack
28
+ from .errors import VocalStackError
29
+ from .realtime import RealtimeTranscript
30
+ from .realtime import RealtimeSession, pace_realtime
31
+
32
+ __version__ = "1.0.0"
33
+
34
+ __all__ = [
35
+ "DEFAULT_BASE_URL",
36
+ "Broadcast",
37
+ "Capabilities",
38
+ "CommittedSegment",
39
+ "CreateSessionResponse",
40
+ "DraftSegment",
41
+ "Health",
42
+ "PublishGrant",
43
+ "RealtimeTranscript",
44
+ "SearchResults",
45
+ "ServerFrame",
46
+ "SessionOptions",
47
+ "SessionStats",
48
+ "RealtimeSession",
49
+ "Transcription",
50
+ "TranscriptionJob",
51
+ "TranscriptCommitted",
52
+ "TranscriptDraft",
53
+ "TranscriptProgress",
54
+ "TranscriptSnapshot",
55
+ "TranscriptWords",
56
+ "VocalStack",
57
+ "VocalStackError",
58
+ "Word",
59
+ "models",
60
+ "pace_realtime",
61
+ ]
vocalstack/_http.py ADDED
@@ -0,0 +1,166 @@
1
+ """The one HTTP path every resource method goes through."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ from typing import Any, Callable, Dict, Mapping, Optional, Union
8
+
9
+ import httpx
10
+
11
+ from .errors import VocalStackError, from_envelope, from_oauth
12
+
13
+ DEFAULT_BASE_URL = "https://api.vocalstack.com"
14
+
15
+ Query = Mapping[str, Any]
16
+
17
+
18
+ def _clean(q: Optional[Query]) -> Dict[str, str]:
19
+ out: Dict[str, str] = {}
20
+ for k, v in (q or {}).items():
21
+ if v is None or v == "":
22
+ continue
23
+ out[k] = ("true" if v else "false") if isinstance(v, bool) else str(v)
24
+ return out
25
+
26
+
27
+ def listener_query(listener_token: Optional[str], share_code: Optional[str]) -> Dict[str, Any]:
28
+ """The query of a listener-side read (a private broadcast's listener
29
+ token, or a share link's code), named as on the wire."""
30
+ return {"listenerToken": listener_token, "shareCode": share_code}
31
+
32
+
33
+ UNAVAILABLE_WAIT_S = 2.0
34
+
35
+
36
+ def retries(status: int, code: str, method: str, idempotency_key: Optional[str] = None) -> bool:
37
+ """Whether a failed call is retried after its ``Retry-After`` (up to
38
+ ``max_retries`` times): ``429 rate_limited`` always (nothing ran), and
39
+ ``503 unavailable`` (the database is waking) only when repeating the call
40
+ cannot do the work twice: GET, HEAD and DELETE, or a call carrying an
41
+ ``Idempotency-Key``."""
42
+ if status == 429:
43
+ return True
44
+ if status != 503 or code != "unavailable":
45
+ return False
46
+ return method.upper() in ("GET", "HEAD", "DELETE") or bool(idempotency_key)
47
+
48
+
49
+ class Transport:
50
+ def __init__(
51
+ self,
52
+ base_url: Optional[str],
53
+ api_key: Optional[str],
54
+ token: Union[None, str, Callable[[], Optional[str]]],
55
+ *,
56
+ http: Optional[httpx.AsyncClient],
57
+ acting_principal: Optional[str],
58
+ device_id: Optional[str],
59
+ max_retries: int,
60
+ timeout: float,
61
+ ) -> None:
62
+ self.base_url = (base_url or DEFAULT_BASE_URL).rstrip("/")
63
+ if api_key and token:
64
+ raise TypeError("VocalStack: pass api_key (a server) or token (a browser), not both")
65
+ self._api_key = api_key
66
+ self._token = token
67
+ self.own_http = http is None
68
+ self.http = http or httpx.AsyncClient(timeout=timeout)
69
+ self.acting_principal = acting_principal
70
+ self.device_id = device_id
71
+ self.max_retries = max_retries
72
+
73
+ def bearer(self) -> Optional[str]:
74
+ """What goes in ``Authorization: Bearer``: the API key, else the token."""
75
+ if self._api_key:
76
+ return self._api_key
77
+ t = self._token
78
+ return t() if callable(t) else t
79
+
80
+ def auth_headers(self) -> Dict[str, str]:
81
+ """The credential as a header (sockets too: a key is refused in a URL)."""
82
+ key = self.bearer()
83
+ return {"authorization": f"Bearer {key}"} if key else {}
84
+
85
+ def url(self, path: str) -> str:
86
+ return self.base_url + path
87
+
88
+ def ws_url(self, path: str, query: Optional[Query] = None) -> str:
89
+ base = "ws" + self.base_url[4:] if self.base_url.startswith("http") else self.base_url
90
+ q = _clean(query)
91
+ return base + path + (("?" + str(httpx.QueryParams(q))) if q else "")
92
+
93
+ async def raw(
94
+ self,
95
+ method: str,
96
+ path: str,
97
+ *,
98
+ query: Optional[Query] = None,
99
+ json_body: Any = None,
100
+ files: Any = None,
101
+ data: Any = None,
102
+ headers: Optional[Mapping[str, str]] = None,
103
+ idempotency_key: Optional[str] = None,
104
+ anonymous: bool = False,
105
+ no_retry: bool = False,
106
+ oauth_errors: bool = False,
107
+ ) -> httpx.Response:
108
+ h: Dict[str, str] = {"accept": "application/json"}
109
+ if headers:
110
+ h.update(headers)
111
+ key = None if anonymous else self.bearer()
112
+ if key:
113
+ h["authorization"] = f"Bearer {key}"
114
+ if self.acting_principal:
115
+ h["x-acting-principal"] = self.acting_principal
116
+ if self.device_id:
117
+ h["x-device-id"] = self.device_id
118
+ if idempotency_key:
119
+ h["idempotency-key"] = idempotency_key
120
+ attempt = 0
121
+ while True:
122
+ try:
123
+ resp = await self.http.request(
124
+ method,
125
+ self.url(path),
126
+ params=_clean(query),
127
+ json=json_body,
128
+ files=files,
129
+ data=data,
130
+ headers=h,
131
+ follow_redirects=False,
132
+ )
133
+ except httpx.TransportError as e:
134
+ raise VocalStackError("unavailable", "could not reach the VocalStack API", retryable=True) from e
135
+ if resp.status_code < 400:
136
+ return resp
137
+ body = None
138
+ try:
139
+ body = resp.json()
140
+ except (json.JSONDecodeError, ValueError):
141
+ pass
142
+ err = (from_oauth if oauth_errors else from_envelope)(body, resp.status_code, resp.headers)
143
+ if not no_retry and retries(resp.status_code, err.code, method, idempotency_key) and attempt < self.max_retries:
144
+ wait = err.retry_after
145
+ if wait is None and err.code == "unavailable":
146
+ wait = UNAVAILABLE_WAIT_S
147
+ if wait is not None and wait <= 60:
148
+ attempt += 1
149
+ await asyncio.sleep(wait)
150
+ continue
151
+ raise err
152
+
153
+ async def json(self, method: str, path: str, **kw: Any) -> Any:
154
+ resp = await self.raw(method, path, **kw)
155
+ if 300 <= resp.status_code < 400:
156
+ return {"location": resp.headers.get("location")}
157
+ if not resp.content:
158
+ return None
159
+ try:
160
+ return resp.json()
161
+ except (json.JSONDecodeError, ValueError) as e:
162
+ raise VocalStackError("internal", "the API answered with a body that is not JSON", status=resp.status_code, headers=resp.headers) from e
163
+
164
+ async def aclose(self) -> None:
165
+ if self.own_http:
166
+ await self.http.aclose()