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.
@@ -0,0 +1,1277 @@
1
+ """The resource groups of :class:`vocalstack.VocalStack`, one per tag of
2
+ the API document (``/v1/openapi.json``)."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import datetime
8
+ import json
9
+ import os
10
+ import time
11
+ from typing import IO, TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, TypeVar, Union
12
+
13
+ import httpx
14
+ import websockets
15
+ from pydantic import BaseModel
16
+
17
+ from . import _models as m
18
+ from ._http import Transport, listener_query
19
+ from .errors import VocalStackError
20
+
21
+ if TYPE_CHECKING:
22
+ from .realtime import RealtimeSession
23
+
24
+ T = TypeVar("T", bound=BaseModel)
25
+
26
+ Upload = Union[str, "os.PathLike[str]", bytes, bytearray, IO[bytes]]
27
+
28
+
29
+ def _body(model: Type[BaseModel], fields: Dict[str, Any]) -> Dict[str, Any]:
30
+ """Validate keyword arguments (snake_case or the wire's camelCase)
31
+ against a request model and dump them as the wire expects."""
32
+ return model.model_validate(fields).model_dump(by_alias=True, exclude_none=True, mode="json")
33
+
34
+
35
+ def _one(model: Type[T], data: Any) -> T:
36
+ return model.model_validate(data)
37
+
38
+
39
+ def _many(model: Type[T], data: Any, key: str) -> List[T]:
40
+ return [model.model_validate(x) for x in ((data or {}).get(key) or [])]
41
+
42
+
43
+ async def _all_pages(page: Callable[[Optional[str]], Any], key: str) -> List[Any]:
44
+ """Every item of a paged list: each page asked for with the previous
45
+ page's ``nextCursor`` until one comes back without it."""
46
+ out: List[Any] = []
47
+ cursor: Optional[str] = None
48
+ while True:
49
+ data = (await page(cursor)) or {}
50
+ out.extend(data.get(key) or [])
51
+ cursor = data.get("nextCursor")
52
+ if not cursor:
53
+ return out
54
+
55
+
56
+ def _file_part(file: Upload, file_name: Optional[str], default: str) -> tuple:
57
+ if isinstance(file, (bytes, bytearray)):
58
+ return (file_name or default, bytes(file))
59
+ if isinstance(file, (str, os.PathLike)):
60
+ path = os.fspath(file)
61
+ with open(path, "rb") as fh:
62
+ return (file_name or os.path.basename(path), fh.read())
63
+ name = file_name or os.path.basename(getattr(file, "name", "") or "") or default
64
+ return (name, file.read())
65
+
66
+
67
+ def _p(segment: Any) -> str:
68
+ from urllib.parse import quote
69
+
70
+ return quote(str(segment), safe="")
71
+
72
+
73
+ class _Group:
74
+ def __init__(self, t: Transport) -> None:
75
+ self._t = t
76
+
77
+
78
+ class _ParentResource(_Group):
79
+ """What broadcasts and transcriptions share: archiving, share links, scripts, the events socket."""
80
+
81
+ _base = ""
82
+ _key = ""
83
+ _model: Type[Union[m.Broadcast, m.Transcription]] = m.Broadcast
84
+ _update: Type[Union[m.UpdateBroadcast, m.UpdateTranscription]] = m.UpdateBroadcast
85
+
86
+ def _path(self, id: str, rest: str = "") -> str:
87
+ return f"{self._base}/{_p(id)}{rest}"
88
+
89
+ async def list(self, lifecycle: str = "active") -> List[Any]:
90
+ """Every one, newest first: ``lifecycle`` is ``active``, ``archived``,
91
+ or ``all`` (both in one list). A paged list is read to its last page
92
+ (``transcriptions.list_page`` reads one)."""
93
+ items = await _all_pages(lambda c: self._t.json("GET", self._base, query={"lifecycle": lifecycle, "cursor": c}), self._key)
94
+ return [self._model.model_validate(x) for x in items]
95
+
96
+ async def get(self, id: str) -> Any:
97
+ return _one(self._model, await self._t.json("GET", self._path(id)))
98
+
99
+ async def update(self, id: str, **fields: Any) -> Any:
100
+ """Rename, or change the default settings (a broadcast: also its
101
+ access, password or link, ``code``)."""
102
+ body = _body(self._update, fields)
103
+ return _one(self._model, await self._t.json("PATCH", self._path(id), json_body=body))
104
+
105
+ async def archive(self, id: str) -> Any:
106
+ return _one(self._model, await self._t.json("POST", self._path(id, "/archive")))
107
+
108
+ async def restore(self, id: str) -> Any:
109
+ return _one(self._model, await self._t.json("POST", self._path(id, "/restore")))
110
+
111
+ async def purge(self, id: str) -> None:
112
+ """Delete an archived one and everything in it, for good."""
113
+ await self._t.json("POST", self._path(id, "/purge"))
114
+
115
+ async def archive_many(self, ids: List[str]) -> m.ManyResult:
116
+ return _one(m.ManyResult, await self._t.json("POST", f"{self._base}/archive", json_body={"ids": ids}))
117
+
118
+ async def restore_many(self, ids: List[str]) -> m.ManyResult:
119
+ return _one(m.ManyResult, await self._t.json("POST", f"{self._base}/restore", json_body={"ids": ids}))
120
+
121
+ async def purge_many(self, ids: List[str]) -> m.ManyResult:
122
+ return _one(m.ManyResult, await self._t.json("POST", f"{self._base}/purge", json_body={"ids": ids}))
123
+
124
+ async def list_share_links(self, id: str) -> List[m.ShareLink]:
125
+ items = await _all_pages(lambda c: self._t.json("GET", self._path(id, "/share-links"), query={"cursor": c}), "links")
126
+ return [m.ShareLink.model_validate(x) for x in items]
127
+
128
+ async def list_scripts(self, id: str) -> List[m.Script]:
129
+ return _many(m.Script, await self._t.json("GET", self._path(id, "/scripts")), "scripts")
130
+
131
+ async def create_share_link(self, id: str, **fields: Any) -> m.ShareLink:
132
+ body = _body(m.CreateShareLink, fields)
133
+ return _one(m.ShareLink, await self._t.json("POST", self._path(id, "/share-links"), json_body=body))
134
+
135
+ async def events(
136
+ self, id: str, *, listener_token: Optional[str] = None, share_code: Optional[str] = None
137
+ ) -> Any:
138
+ """The events socket a waiting screen needs (``transcription.started``:
139
+ it is live, ``transcription.ended``, ``job.progress``,
140
+ ``stream.ingest``; each names its transcription, ``transcriptionId``):
141
+ a ``websockets`` connection yielding JSON text."""
142
+ url = self._t.ws_url(self._path(id, "/events"), listener_query(listener_token, share_code))
143
+ return await websockets.connect(url, additional_headers=self._t.auth_headers())
144
+
145
+
146
+ class Broadcasts(_ParentResource):
147
+ """``vs.broadcasts``: the links listeners open."""
148
+
149
+ _base = "/v1/broadcasts"
150
+ _key = "broadcasts"
151
+ _model = m.Broadcast
152
+ _update = m.UpdateBroadcast
153
+
154
+ async def create(self, *, idempotency_key: Optional[str] = None, **fields: Any) -> m.Broadcast:
155
+ body = _body(m.CreateBroadcast, fields)
156
+ data = await self._t.json("POST", self._base, json_body=body, idempotency_key=idempotency_key)
157
+ return _one(m.Broadcast, data)
158
+
159
+ async def record(self, id: str, *, idempotency_key: Optional[str] = None, **fields: Any) -> m.PublishGrant:
160
+ """Start a new live transcription on the broadcast, each call a new
161
+ one (the grant's ``transcription``). The grant's ``stream_url`` is the
162
+ publisher socket (``vs.transcriptions.publish(grant)``). A 409
163
+ ``conflict`` with ``details["takeover"]`` means another device is
164
+ sending: pass ``takeover=True`` to send from here instead."""
165
+ body = _body(m.StartLiveTranscription, fields)
166
+ data = await self._t.json("POST", self._path(id, "/record"), json_body=body, idempotency_key=idempotency_key)
167
+ return _one(m.PublishGrant, data)
168
+
169
+ async def add_audio_source(self, id: str, **fields: Any) -> m.Broadcast:
170
+ """A stream the broadcast can record from (a YouTube live, a radio address)."""
171
+ body = _body(m.CreateAudioSource, fields)
172
+ return _one(m.Broadcast, await self._t.json("POST", self._path(id, "/audio-sources"), json_body=body))
173
+
174
+ async def remove_audio_source(self, id: str, source_id: str) -> m.Broadcast:
175
+ data = await self._t.json("DELETE", self._path(id, f"/audio-sources/{_p(source_id)}"))
176
+ return _one(m.Broadcast, data)
177
+
178
+ async def check_audio_source(self, id: str, source_id: str, *, fresh: bool = False) -> m.AudioSourceCheck:
179
+ data = await self._t.json(
180
+ "GET",
181
+ self._path(id, f"/audio-sources/{_p(source_id)}/check"),
182
+ query={"fresh": True if fresh else None},
183
+ )
184
+ return _one(m.AudioSourceCheck, data)
185
+
186
+
187
+ _LIST_FILTERS = {
188
+ "site": "site", "q": "q", "language": "language", "kind": "kind", "origin": "origin", "tag": "tag",
189
+ "broadcast": "broadcast", "created_after": "createdAfter", "created_before": "createdBefore", "shared": "shared",
190
+ }
191
+
192
+
193
+ def _list_filters(**filters: Any) -> Dict[str, Any]:
194
+ out: Dict[str, Any] = {}
195
+ for k, v in filters.items():
196
+ if isinstance(v, datetime.datetime):
197
+ v = v.isoformat() if v.tzinfo else v.replace(tzinfo=datetime.timezone.utc).isoformat()
198
+ elif isinstance(v, datetime.date):
199
+ v = v.isoformat()
200
+ out[_LIST_FILTERS[k]] = v
201
+ return out
202
+
203
+
204
+ class Transcriptions(_ParentResource):
205
+ """``vs.transcriptions``: a file, a link, a microphone or a stream, transcribed and stored."""
206
+
207
+ _base = "/v1/transcriptions"
208
+ _key = "transcriptions"
209
+ _model = m.Transcription
210
+ _update = m.UpdateTranscription
211
+
212
+ def __init__(self, t: Transport, ready_deadline_s: float) -> None:
213
+ super().__init__(t)
214
+ self._ready_deadline_s = ready_deadline_s
215
+
216
+ async def get(
217
+ self, id: str, *, listener_token: Optional[str] = None, share_code: Optional[str] = None
218
+ ) -> m.Transcription:
219
+ """One transcription; a listener reads it with ``listener_token`` or
220
+ ``share_code`` (without the owner's details)."""
221
+ return _one(m.Transcription, await self._t.json("GET", self._path(id), query=listener_query(listener_token, share_code)))
222
+
223
+ async def list(
224
+ self,
225
+ lifecycle: str = "active",
226
+ *,
227
+ site: Optional[str] = None,
228
+ q: Optional[str] = None,
229
+ language: Optional[str] = None,
230
+ kind: Optional[str] = None,
231
+ origin: Optional[str] = None,
232
+ tag: Optional[str] = None,
233
+ broadcast: Optional[str] = None,
234
+ created_after: Optional[Union[str, datetime.date]] = None,
235
+ created_before: Optional[Union[str, datetime.date]] = None,
236
+ shared: Optional[bool] = None,
237
+ ) -> List[m.Transcription]:
238
+ """Every transcription that matches, newest first, read to the last
239
+ page. The filters are ``list_page``'s: ``shared=True``, ``q``,
240
+ ``site``, ``language``, ``kind``, ``origin``, ``tag``, ``broadcast``,
241
+ ``created_after``, ``created_before``."""
242
+ query = _list_filters(
243
+ site=site, q=q, language=language, kind=kind, origin=origin, tag=tag, broadcast=broadcast,
244
+ created_after=created_after, created_before=created_before, shared=shared,
245
+ )
246
+ items = await _all_pages(lambda c: self._t.json("GET", self._base, query={"lifecycle": lifecycle, "cursor": c, **query}), self._key)
247
+ return [m.Transcription.model_validate(x) for x in items]
248
+
249
+ async def list_page(
250
+ self,
251
+ *,
252
+ lifecycle: str = "active",
253
+ cursor: Optional[str] = None,
254
+ limit: Optional[int] = None,
255
+ site: Optional[str] = None,
256
+ q: Optional[str] = None,
257
+ language: Optional[str] = None,
258
+ kind: Optional[str] = None,
259
+ origin: Optional[str] = None,
260
+ tag: Optional[str] = None,
261
+ broadcast: Optional[str] = None,
262
+ created_after: Optional[Union[str, datetime.date]] = None,
263
+ created_before: Optional[Union[str, datetime.date]] = None,
264
+ shared: Optional[bool] = None,
265
+ ) -> m.TranscriptionPage:
266
+ """One page of transcriptions, newest first (``limit`` 1 to 200, 100
267
+ by default); ``cursor`` is the previous page's ``next_cursor``, and
268
+ the last page has none. Every filter given must match: ``q`` (words
269
+ in the name, source name or link), ``site`` (``youtube``,
270
+ ``vimeo``…), ``language`` (``en``…), ``kind`` (``file``, ``link``,
271
+ ``live``), ``origin``, ``tag`` (id or name), ``broadcast`` (id),
272
+ ``created_after`` / ``created_before`` (a datetime, a date, or the
273
+ API's string), ``shared`` (``True``: each has a ``share_code``)."""
274
+ query = _list_filters(
275
+ site=site, q=q, language=language, kind=kind, origin=origin, tag=tag, broadcast=broadcast,
276
+ created_after=created_after, created_before=created_before, shared=shared,
277
+ )
278
+ data = await self._t.json("GET", self._base, query={"lifecycle": lifecycle, "cursor": cursor, "limit": limit, **query})
279
+ return _one(m.TranscriptionPage, data)
280
+
281
+ async def create(
282
+ self,
283
+ *,
284
+ file: Optional[Upload] = None,
285
+ file_name: Optional[str] = None,
286
+ idempotency_key: Optional[str] = None,
287
+ **fields: Any,
288
+ ) -> m.Transcription:
289
+ """From a file (``file``: a path, bytes or an open binary file) or a
290
+ public link (``url=...``): ``await vs.transcriptions.wait_for_job(tx.id)``,
291
+ then ``await vs.transcriptions.transcript(tx.id)``."""
292
+ options = _body(m.CreateTranscription, fields)
293
+ if file is None:
294
+ data = await self._t.json("POST", self._base, json_body=options, idempotency_key=idempotency_key)
295
+ else:
296
+ part = await asyncio.to_thread(_file_part, file, file_name, "upload")
297
+ data = await self._t.json(
298
+ "POST",
299
+ self._base,
300
+ data={"options": json.dumps(options)},
301
+ files={"file": part},
302
+ idempotency_key=idempotency_key,
303
+ )
304
+ return _one(m.Transcription, data)
305
+
306
+ async def create_from_url(self, url: str, **fields: Any) -> m.Transcription:
307
+ """``create(url=url, ...)``."""
308
+ return await self.create(url=url, **fields)
309
+
310
+ async def create_live(self, *, idempotency_key: Optional[str] = None, **fields: Any) -> m.Transcription:
311
+ """Captured as it is spoken (a microphone, or a stream the server
312
+ pulls). Created idle: ``start(id)`` starts it."""
313
+ body = _body(m.CreateLiveTranscription, fields)
314
+ data = await self._t.json("POST", f"{self._base}/live", json_body=body, idempotency_key=idempotency_key)
315
+ return _one(m.Transcription, data)
316
+
317
+ async def lookup(self, url: str) -> Optional[m.Transcription]:
318
+ """The caller's newest active transcription of ``url`` (same YouTube video, or the same link), or None."""
319
+ data = await self._t.json("GET", f"{self._base}/lookup", query={"url": url})
320
+ t = (data or {}).get("transcription")
321
+ return None if t is None else _one(m.Transcription, t)
322
+
323
+ async def probe(self, url: str) -> m.LinkProbe:
324
+ """Whether a link is live (a live transcription) or a file."""
325
+ return _one(m.LinkProbe, await self._t.json("GET", f"{self._base}/probe", query={"url": url}))
326
+
327
+ async def attach_broadcast(self, id: str, broadcast_id: str) -> m.Transcription:
328
+ data = await self._t.json("PUT", self._path(id, f"/broadcasts/{_p(broadcast_id)}"))
329
+ return _one(m.Transcription, data)
330
+
331
+ async def detach_broadcast(self, id: str, broadcast_id: str) -> m.Transcription:
332
+ data = await self._t.json("DELETE", self._path(id, f"/broadcasts/{_p(broadcast_id)}"))
333
+ return _one(m.Transcription, data)
334
+
335
+ async def name_appearance(self, id: str, appearance: int, name: Optional[str]) -> None:
336
+ """Name one speaker of the transcription: ``appearance`` is their
337
+ display number ("Speaker <number>"); ``None`` clears the name."""
338
+ await self._t.json("PUT", self._path(id, f"/appearances/{appearance}"), json_body={"name": name})
339
+
340
+
341
+ async def start(
342
+ self, id: str, *, idempotency_key: Optional[str] = None, **fields: Any
343
+ ) -> m.PublishGrant:
344
+ """Start a live transcription made with ``create_live``. The grant's
345
+ ``stream_url`` is the publisher socket (``vs.transcriptions.publish(grant)``).
346
+ A transcription runs once: one already stopped is ``invalid_state``.
347
+ A 409 ``conflict`` with ``details["takeover"]`` means another device
348
+ is sending its audio: pass ``takeover=True`` to send it from here instead."""
349
+ body = _body(m.StartLiveTranscription, fields)
350
+ data = await self._t.json("POST", self._path(id, "/start"), json_body=body, idempotency_key=idempotency_key)
351
+ return _one(m.PublishGrant, data)
352
+
353
+ async def pause(self, id: str) -> m.Transcription:
354
+ return _one(m.Transcription, await self._t.json("POST", self._path(id, "/pause")))
355
+
356
+ async def resume(self, id: str) -> m.Transcription:
357
+ return _one(m.Transcription, await self._t.json("POST", self._path(id, "/resume")))
358
+
359
+ async def stop(self, id: str, reason: Optional[str] = None) -> m.Transcription:
360
+ """Only from paused. A stopped transcription cannot be started again."""
361
+ data = await self._t.json("POST", self._path(id, "/stop"), json_body={"reason": reason})
362
+ return _one(m.Transcription, data)
363
+
364
+ async def publish_token(self, id: str, *, takeover: bool = False) -> m.PublishGrant:
365
+ """A new grant for a running transcription's publisher socket (a
366
+ reconnect, or another device with ``takeover=True``)."""
367
+ data = await self._t.json("POST", self._path(id, "/publish-token"), json_body={"takeover": takeover})
368
+ return _one(m.PublishGrant, data)
369
+
370
+ async def publish(
371
+ self,
372
+ grant: m.PublishGrant,
373
+ *,
374
+ ready_deadline_s: Optional[float] = None,
375
+ on_frame: Optional[Callable[[Any], None]] = None,
376
+ ) -> "RealtimeSession":
377
+ """Open the publisher socket a grant names and wait until it is
378
+ ready: ``send_audio`` raw PCM (f32le, 16 kHz, mono), end with ``eof()``.
379
+ ``on_frame`` sees every server frame, lifecycle included."""
380
+ from .realtime import RealtimeSession
381
+
382
+ if not grant.stream_url:
383
+ raise VocalStackError("invalid_state", "this grant has no stream_url")
384
+ return await RealtimeSession.connect(
385
+ grant.session_id or grant.transcription.id,
386
+ grant.stream_url,
387
+ ready_deadline_s=ready_deadline_s or self._ready_deadline_s,
388
+ on_frame=on_frame,
389
+ )
390
+
391
+ async def job(self, id: str) -> m.TranscriptionJob:
392
+ """A file or link transcription's job. States: queued, fetching,
393
+ transcribing, done, failed, and cropping (waiting for ``start_job``)."""
394
+ return _one(m.TranscriptionJob, await self._t.json("GET", self._path(id, "/job")))
395
+
396
+ async def start_job(self, id: str, *, start_s: Optional[float] = None, end_s: Optional[float] = None) -> m.TranscriptionJob:
397
+ """Release a job waiting in ``cropping``: the window to transcribe, in seconds."""
398
+ body = _body(m.StartJob, {"start_s": start_s, "end_s": end_s})
399
+ return _one(m.TranscriptionJob, await self._t.json("POST", self._path(id, "/job/start"), json_body=body))
400
+
401
+ async def retry_job(self, id: str) -> m.TranscriptionJob:
402
+ """Re-queue a failed job from its stored source."""
403
+ return _one(m.TranscriptionJob, await self._t.json("POST", self._path(id, "/job/retry")))
404
+
405
+ async def job_preview(self, id: str) -> bytes:
406
+ """The file the server fetched for a link job waiting in ``cropping``."""
407
+ resp = await self._t.raw("GET", self._path(id, "/job/preview"), headers={"accept": "*/*"})
408
+ return resp.content
409
+
410
+ async def wait_for_job(
411
+ self,
412
+ id: str,
413
+ *,
414
+ interval_s: float = 2.0,
415
+ timeout_s: Optional[float] = None,
416
+ on_progress: Optional[Callable[[m.TranscriptionJob], None]] = None,
417
+ ) -> m.TranscriptionJob:
418
+ """Poll until the job is ``done``, ``failed`` or ``cropping`` and
419
+ return it. It does not raise on ``failed``: check ``job.state`` and ``job.error``.
420
+ ``on_progress`` sees every job read, the last one included: its
421
+ ``state`` and ``progress`` (``pct``, ``processed_s``, the fetch phase)."""
422
+ deadline = None if timeout_s is None else time.monotonic() + timeout_s
423
+ while True:
424
+ job = await self.job(id)
425
+ if on_progress is not None:
426
+ on_progress(job)
427
+ if job.state in _TERMINAL:
428
+ return job
429
+ if deadline is not None and time.monotonic() + interval_s > deadline:
430
+ raise VocalStackError("timeout", f"job still {job.state} after {timeout_s}s", retryable=True)
431
+ await asyncio.sleep(interval_s)
432
+
433
+ async def transcript(
434
+ self,
435
+ id: str,
436
+ *,
437
+ after: Optional[int] = None,
438
+ lang: Optional[str] = None,
439
+ listener_token: Optional[str] = None,
440
+ share_code: Optional[str] = None,
441
+ ) -> m.TranscriptSnapshot:
442
+ """Segments (with word timings), sentences and speakers; ``lang`` reads it translated."""
443
+ query = {**listener_query(listener_token, share_code), "after": after, "lang": lang}
444
+ data = await self._t.json("GET", self._path(id, "/transcript"), query=query)
445
+ return _one(m.TranscriptSnapshot, data)
446
+
447
+ async def translation(
448
+ self,
449
+ id: str,
450
+ lang: str,
451
+ sentences: Optional[List[int]] = None,
452
+ *,
453
+ listener_token: Optional[str] = None,
454
+ share_code: Optional[str] = None,
455
+ ) -> Dict[str, Any]:
456
+ """Translate the given sentence ids (at most 40): ``{"lang", "translations"}``."""
457
+ query = {**listener_query(listener_token, share_code), "lang": lang, "sentences": ",".join(map(str, sentences)) if sentences else None}
458
+ return await self._t.json("GET", self._path(id, "/translation"), query=query)
459
+
460
+ async def summarize(self, id: str, *, idempotency_key: Optional[str] = None) -> m.SummaryStatus:
461
+ data = await self._t.json("POST", self._path(id, "/summarize"), idempotency_key=idempotency_key)
462
+ return _one(m.SummaryStatus, data)
463
+
464
+ async def summary(
465
+ self, id: str, *, lang: Optional[str] = None, listener_token: Optional[str] = None, share_code: Optional[str] = None
466
+ ) -> m.SummaryStatus:
467
+ query = {**listener_query(listener_token, share_code), "lang": lang}
468
+ data = await self._t.json("GET", self._path(id, "/summary"), query=query)
469
+ return _one(m.SummaryStatus, data)
470
+
471
+ async def export(
472
+ self,
473
+ id: str,
474
+ format: str,
475
+ *,
476
+ lang: Optional[str] = None,
477
+ share_code: Optional[str] = None,
478
+ listener_token: Optional[str] = None,
479
+ speaker_labels: Optional[str] = None,
480
+ timestamps: Optional[str] = None,
481
+ start_s: Optional[float] = None,
482
+ end_s: Optional[float] = None,
483
+ summary: Optional[bool] = None,
484
+ ) -> bytes:
485
+ """An export file: ``pdf``, ``xlsx``, ``srt``, ``vtt``, ``txt``, ``md`` or ``json``; ``lang`` makes it read in that language. ``speaker_labels``: ``auto``, ``on`` or ``off`` for this file (default: the transcription's own); ``timestamps``: ``paragraph``, ``line`` or ``off``; ``start_s``/``end_s`` keep one window; ``summary`` puts the summary first. ``listener_token``: a broadcast listener's, once the transcription has ended."""
486
+ query = {
487
+ "format": format,
488
+ "lang": lang,
489
+ "shareCode": share_code,
490
+ "listenerToken": listener_token,
491
+ "speakerLabels": speaker_labels,
492
+ "timestamps": timestamps,
493
+ "startS": None if start_s is None else str(start_s),
494
+ "endS": None if end_s is None else str(end_s),
495
+ "summary": "true" if summary else None,
496
+ }
497
+ resp = await self._t.raw("GET", self._path(id, "/export"), headers={"accept": "*/*"}, query=query)
498
+ return resp.content
499
+
500
+ async def audio(
501
+ self,
502
+ id: str,
503
+ *,
504
+ kind: Optional[str] = None,
505
+ lang: Optional[str] = None,
506
+ format: Optional[str] = None,
507
+ listener_token: Optional[str] = None,
508
+ share_code: Optional[str] = None,
509
+ ) -> str:
510
+ """The signed media URL the server redirects to (``kind``: delivery, master, source)."""
511
+ query = {**listener_query(listener_token, share_code), "kind": kind, "lang": lang, "format": format}
512
+ resp = await self._t.raw("GET", self._path(id, "/audio"), query=query)
513
+ loc = resp.headers.get("location")
514
+ if not loc:
515
+ raise VocalStackError("not_found", "no signed URL in the redirect", status=resp.status_code)
516
+ return loc
517
+
518
+ async def audio_clip(
519
+ self, id: str, start_s: float, end_s: float, *, listener_token: Optional[str] = None, share_code: Optional[str] = None
520
+ ) -> bytes:
521
+ """A stretch of the transcription's audio, ``start_s`` to ``end_s`` seconds (at most 120 s)."""
522
+ query = {**listener_query(listener_token, share_code), "startS": start_s, "endS": end_s}
523
+ resp = await self._t.raw("GET", self._path(id, "/audio/clip"), headers={"accept": "*/*"}, query=query)
524
+ return resp.content
525
+
526
+ async def media_token(self, id: str) -> Dict[str, Any]:
527
+ return await self._t.json("GET", self._path(id, "/media-token"))
528
+
529
+ async def voice(
530
+ self, id: str, lang: Optional[str] = None, *, listener_token: Optional[str] = None, share_code: Optional[str] = None
531
+ ) -> List[m.VoiceTrack]:
532
+ query = {**listener_query(listener_token, share_code), "lang": lang}
533
+ data = await self._t.json("GET", self._path(id, "/voice"), query=query)
534
+ return [m.VoiceTrack.model_validate(x) for x in data or []]
535
+
536
+ async def request_voice(
537
+ self,
538
+ id: str,
539
+ langs: List[str],
540
+ *,
541
+ voices: Optional[str] = None,
542
+ voice: Optional[str] = None,
543
+ voice_by_speaker: Optional[Dict[str, str]] = None,
544
+ near: Optional[int] = None,
545
+ consent: Optional[bool] = None,
546
+ listener_token: Optional[str] = None,
547
+ share_code: Optional[str] = None,
548
+ idempotency_key: Optional[str] = None,
549
+ ) -> List[m.VoiceTrack]:
550
+ body: Dict[str, Any] = {"langs": langs}
551
+ if consent is not None:
552
+ body["consent"] = consent
553
+ if voices is not None:
554
+ body["voices"] = voices
555
+ if voice is not None:
556
+ body["voice"] = voice
557
+ if voice_by_speaker is not None:
558
+ body["voiceBySpeaker"] = {str(k): v for k, v in voice_by_speaker.items()}
559
+ if near is not None:
560
+ body["near"] = near
561
+ data = await self._t.json(
562
+ "POST", self._path(id, "/voice"), query=listener_query(listener_token, share_code), json_body=body, idempotency_key=idempotency_key
563
+ )
564
+ return [m.VoiceTrack.model_validate(x) for x in data or []]
565
+
566
+ async def voice_clip(
567
+ self,
568
+ id: str,
569
+ sentence: int,
570
+ lang: str,
571
+ *,
572
+ format: Optional[str] = None,
573
+ voices: Optional[str] = None,
574
+ voice: Optional[str] = None,
575
+ part: Optional[int] = None,
576
+ listener_token: Optional[str] = None,
577
+ share_code: Optional[str] = None,
578
+ ) -> bytes:
579
+ """One sentence spoken in ``lang``: ``sentence`` is a transcript sentence's
580
+ ``sentenceId``, not a segment's position. In the transcription's default reading: each
581
+ speaker in their granted clone, else a stock voice of their gender."""
582
+ query = {**listener_query(listener_token, share_code), "lang": lang, "voices": voices, "voice": voice, "format": format, "part": part or None}
583
+ resp = await self._t.raw("GET", self._path(id, f"/voice/{sentence}"), headers={"accept": "*/*"}, query=query)
584
+ return resp.content
585
+
586
+ async def corrections(self, id: str) -> List[m.Correction]:
587
+ """Every correction, newest first (every page of ``corrections_page``)."""
588
+ path = self._path(id, "/corrections")
589
+ items = await _all_pages(lambda c: self._t.json("GET", path, query={"cursor": c}), "corrections")
590
+ return [m.Correction.model_validate(x) for x in items]
591
+
592
+ async def corrections_page(self, id: str, *, cursor: Optional[str] = None, limit: Optional[int] = None) -> m.CorrectionPage:
593
+ """One page of corrections, newest first; ``cursor`` is the previous page's ``next_cursor``."""
594
+ data = await self._t.json("GET", self._path(id, "/corrections"), query={"cursor": cursor, "limit": limit})
595
+ return _one(m.CorrectionPage, data)
596
+
597
+ async def apply_corrections(self, id: str, **fields: Any) -> List[m.Correction]:
598
+ """Apply a staged batch atomically (``CorrectionBatch``); each one is
599
+ undone with ``vs.corrections.revert``."""
600
+ body = _body(m.CorrectionBatch, fields)
601
+ data = await self._t.json("POST", self._path(id, "/corrections"), json_body=body)
602
+ return _many(m.Correction, data, "corrections")
603
+
604
+ async def retranscribe(self, id: str, *, seqs: List[int], lang: str) -> List[m.Correction]:
605
+ """Read lines again with the language forced."""
606
+ data = await self._t.json("POST", self._path(id, "/retranscribe"), json_body={"seqs": seqs, "lang": lang})
607
+ return _many(m.Correction, data, "corrections")
608
+
609
+ async def history(self, id: str, *, after: Optional[int] = None, limit: Optional[int] = None) -> List[m.HistoryEvent]:
610
+ """The durable event log with wall times (owner only): every event
611
+ after ``after`` (a ``seq``; the whole log without it), read ``limit`` a page."""
612
+
613
+ def page(cursor: Optional[str]) -> Any:
614
+ q = {"cursor": cursor, "limit": limit} if cursor else {"after": after, "limit": limit}
615
+ return self._t.json("GET", self._path(id, "/history"), query=q)
616
+
617
+ return [m.HistoryEvent.model_validate(x) for x in await _all_pages(page, "events")]
618
+
619
+ async def history_page(
620
+ self, id: str, *, cursor: Optional[str] = None, after: Optional[int] = None, limit: Optional[int] = None
621
+ ) -> m.TranscriptionHistory:
622
+ """One page of the event log (500 by default, 1000 at most): from
623
+ ``after`` a ``seq``, or the previous page's ``next_cursor`` as ``cursor``."""
624
+ data = await self._t.json("GET", self._path(id, "/history"), query={"cursor": cursor, "after": after, "limit": limit})
625
+ return _one(m.TranscriptionHistory, data)
626
+
627
+ async def subscribe(
628
+ self,
629
+ id: str,
630
+ *,
631
+ lang: Optional[str] = None,
632
+ voice: Optional[str] = None,
633
+ listener_token: Optional[str] = None,
634
+ share_code: Optional[str] = None,
635
+ as_owner: bool = True,
636
+ ) -> Any:
637
+ """The transcription's live fan-out socket: a ``websockets`` connection
638
+ whose first frame is ``subscribe.ready``; read the backfill with
639
+ ``transcript(id, after=...)``."""
640
+ url = self._t.ws_url(
641
+ self._path(id, "/subscribe"),
642
+ {
643
+ "lang": lang,
644
+ "voice": voice,
645
+ **listener_query(listener_token, share_code),
646
+ "role": None if as_owner else "listener",
647
+ "device": self._t.device_id,
648
+ },
649
+ )
650
+ headers = self._t.auth_headers() if as_owner else {}
651
+ return await websockets.connect(url, max_size=None, additional_headers=headers)
652
+
653
+
654
+ _TERMINAL = {"done", "failed", "stopped", "cropping"}
655
+
656
+
657
+ class Corrections(_Group):
658
+ """``vs.corrections``: a correction made with ``transcriptions.apply_corrections``, undone."""
659
+
660
+ async def revert(self, correction_id: str) -> m.Correction:
661
+ return _one(m.Correction, await self._t.json("POST", f"/v1/corrections/{_p(correction_id)}/revert"))
662
+
663
+
664
+ class ShareLinks(_Group):
665
+ """``vs.share_links``: named public links (create and list them on their owner)."""
666
+
667
+ async def open(self, code: str) -> m.SharedTranscript:
668
+ """What a share code opens, with no credential: pass the code as ``share_code`` to the transcription's reads."""
669
+ return _one(m.SharedTranscript, await self._t.json("GET", f"/v1/shares/{_p(code)}", anonymous=True))
670
+
671
+ async def update(self, id: str, **fields: Any) -> m.ShareLink:
672
+ body = _body(m.UpdateShareLink, fields)
673
+ return _one(m.ShareLink, await self._t.json("PATCH", f"/v1/share-links/{_p(id)}", json_body=body))
674
+
675
+ async def revoke(self, id: str) -> m.ShareLink:
676
+ return _one(m.ShareLink, await self._t.json("DELETE", f"/v1/share-links/{_p(id)}"))
677
+
678
+
679
+ class Tags(_Group):
680
+ """``vs.tags``: the account's own labels for its transcriptions; each
681
+ transcription lists its own in ``tags``."""
682
+
683
+ async def list(self) -> List[m.Tag]:
684
+ items = await _all_pages(lambda c: self._t.json("GET", "/v1/tags", query={"cursor": c}), "tags")
685
+ return [m.Tag.model_validate(x) for x in items]
686
+
687
+ async def create(self, name: str, **fields: Any) -> m.Tag:
688
+ body = _body(m.CreateTag, {"name": name, **fields})
689
+ return _one(m.Tag, await self._t.json("POST", "/v1/tags", json_body=body))
690
+
691
+ async def update(self, id: str, **fields: Any) -> m.Tag:
692
+ body = _body(m.UpdateTag, fields)
693
+ return _one(m.Tag, await self._t.json("PATCH", f"/v1/tags/{_p(id)}", json_body=body))
694
+
695
+ async def delete(self, id: str) -> None:
696
+ """Delete a tag: it comes off every transcription it is on."""
697
+ await self._t.json("DELETE", f"/v1/tags/{_p(id)}")
698
+
699
+ async def tag_transcriptions(self, id: str, *, add: Optional[List[str]] = None, remove: Optional[List[str]] = None) -> m.Tag:
700
+ """Put the tag on the transcriptions in ``add`` and take it off those in ``remove``."""
701
+ body = _body(m.TagTranscriptions, {"add": add or [], "remove": remove or []})
702
+ return _one(m.Tag, await self._t.json("POST", f"/v1/tags/{_p(id)}/transcriptions", json_body=body))
703
+
704
+
705
+ class Uploads(_Group):
706
+ """``vs.uploads``: files sent straight to storage in parts, then
707
+ transcribed with ``vs.transcriptions.create(upload_id=...)``."""
708
+
709
+ async def create(self, name: str, *, bytes: int, mime: Optional[str] = None) -> m.FileUpload:
710
+ body = _body(m.CreateFileUpload, {"name": name, "bytes": bytes, "mime": mime})
711
+ return _one(m.FileUpload, await self._t.json("POST", "/v1/uploads", json_body=body))
712
+
713
+ async def complete(self, id: str, parts: List[Dict[str, Any]]) -> m.FileUpload:
714
+ body = _body(m.CompleteFileUpload, {"parts": parts})
715
+ return _one(m.FileUpload, await self._t.json("POST", f"/v1/uploads/{_p(id)}/complete", json_body=body))
716
+
717
+ async def send(
718
+ self,
719
+ file: Upload,
720
+ *,
721
+ file_name: Optional[str] = None,
722
+ mime: Optional[str] = None,
723
+ concurrency: int = 4,
724
+ on_progress: Optional[Callable[[int, int], Any]] = None,
725
+ ) -> m.FileUpload:
726
+ """Create an upload, PUT every part to its link (no credential), and
727
+ complete it. A path is read a part at a time."""
728
+ path: Optional[str] = None
729
+ data: Optional[bytes] = None
730
+ if isinstance(file, (str, os.PathLike)):
731
+ path = os.fspath(file)
732
+ size = os.path.getsize(path)
733
+ name = file_name or os.path.basename(path)
734
+ else:
735
+ name, data = _file_part(file, file_name, "upload")
736
+ size = len(data)
737
+ up = await self.create(name, bytes=size, mime=mime)
738
+ sent: Dict[int, int] = {}
739
+ etags: Dict[int, str] = {}
740
+ gate = asyncio.Semaphore(max(1, concurrency))
741
+
742
+ def chunk(start: int, n: int) -> bytes:
743
+ if data is not None:
744
+ return data[start : start + n]
745
+ with open(path, "rb") as fh: # type: ignore[arg-type]
746
+ fh.seek(start)
747
+ return fh.read(n)
748
+
749
+ async def one(part: m.FileUploadPart) -> None:
750
+ async with gate:
751
+ body = chunk((part.number - 1) * up.part_bytes, part.bytes)
752
+ for attempt in range(3):
753
+ try:
754
+ resp = await self._t.http.put(part.url, content=body)
755
+ except httpx.TransportError:
756
+ if attempt == 2:
757
+ raise VocalStackError("unavailable", f"part {part.number} could not reach storage", retryable=True)
758
+ continue
759
+ if resp.status_code < 300:
760
+ etag = resp.headers.get("etag")
761
+ if not etag:
762
+ raise VocalStackError("unavailable", f"part {part.number} was sent but storage gave no ETag")
763
+ etags[part.number] = etag
764
+ sent[part.number] = part.bytes
765
+ if on_progress:
766
+ on_progress(sum(sent.values()), size)
767
+ return
768
+ if resp.status_code < 500 or attempt == 2:
769
+ raise VocalStackError("invalid_state", f"storage refused part {part.number} ({resp.status_code})")
770
+
771
+ await asyncio.gather(*(one(p) for p in (up.parts or [])))
772
+ return await self.complete(up.id, [{"number": n, "etag": e} for n, e in sorted(etags.items())])
773
+
774
+
775
+ class Voices(_Group):
776
+ """``vs.voices``: the voices a language offers, and how each sounds."""
777
+
778
+ async def available(
779
+ self,
780
+ lang: str,
781
+ *,
782
+ transcription: Optional[str] = None,
783
+ listener_token: Optional[str] = None,
784
+ share_code: Optional[str] = None,
785
+ as_owner: bool = True,
786
+ ) -> m.VoiceCatalogue:
787
+ """The voices that can speak ``lang``, best first (with a token, also
788
+ the account's ready clones). ``transcription`` also offers the cloned
789
+ voices that transcription uses, to whoever may read it: its owner, or a
790
+ listener with ``listener_token`` or ``share_code``."""
791
+ data = await self._t.json(
792
+ "GET",
793
+ "/v1/voices/available",
794
+ query={**listener_query(listener_token, share_code), "lang": lang, "transcription": transcription},
795
+ anonymous=not as_owner,
796
+ )
797
+ return _one(m.VoiceCatalogue, data)
798
+
799
+ async def preview(self, voice: str, lang: str, *, format: Optional[str] = None) -> bytes:
800
+ resp = await self._t.raw(
801
+ "GET", "/v1/voices/preview", headers={"accept": "*/*"}, query={"voice": voice, "lang": lang, "format": format}
802
+ )
803
+ return resp.content
804
+
805
+
806
+ class Speakers(_Group):
807
+ """``vs.speakers``: the account's saved speakers, each with an optional
808
+ cloned voice (``voice``) built from their sample."""
809
+
810
+ async def list(self, *, lifecycle: Optional[str] = None) -> List[m.Speaker]:
811
+ items = await _all_pages(lambda c: self._t.json("GET", "/v1/speakers", query={"lifecycle": lifecycle, "cursor": c}), "speakers")
812
+ return [m.Speaker.model_validate(x) for x in items]
813
+
814
+ async def get(self, id: str) -> m.Speaker:
815
+ return _one(m.Speaker, await self._t.json("GET", f"/v1/speakers/{_p(id)}"))
816
+
817
+ async def archive(self, id: str) -> m.Speaker:
818
+ """Put a speaker away: their voice stops speaking and they are unlinked from their appearances."""
819
+ return _one(m.Speaker, await self._t.json("POST", f"/v1/speakers/{_p(id)}/archive"))
820
+
821
+ async def restore(self, id: str) -> m.Speaker:
822
+ return _one(m.Speaker, await self._t.json("POST", f"/v1/speakers/{_p(id)}/restore"))
823
+
824
+ async def archive_many(self, ids: List[str]) -> m.ManyResult:
825
+ return _one(m.ManyResult, await self._t.json("POST", "/v1/speakers/archive", json_body={"ids": ids}))
826
+
827
+ async def restore_many(self, ids: List[str]) -> m.ManyResult:
828
+ return _one(m.ManyResult, await self._t.json("POST", "/v1/speakers/restore", json_body={"ids": ids}))
829
+
830
+ async def delete_many(self, ids: List[str]) -> m.ManyResult:
831
+ return _one(m.ManyResult, await self._t.json("POST", "/v1/speakers/delete", json_body={"ids": ids}))
832
+
833
+ async def create(
834
+ self,
835
+ name: str,
836
+ *,
837
+ sample: Optional[Upload] = None,
838
+ sample_url: Optional[str] = None,
839
+ file_name: Optional[str] = None,
840
+ gender: Optional[str] = None,
841
+ color: Optional[str] = None,
842
+ draft: Optional[bool] = None,
843
+ consent: Optional[bool] = None,
844
+ idempotency_key: Optional[str] = None,
845
+ ) -> m.Speaker:
846
+ """Save a speaker from a sample or a link. Without ``consent`` they are
847
+ recognised only (``voice`` is ``None``); ``consent=True`` asserts you
848
+ have their permission and starts training their cloned voice."""
849
+ meta = _body(
850
+ m.CreateSpeaker,
851
+ {"name": name, "sample_url": sample_url, "gender": gender, "color": color, "draft": draft, "consent": consent},
852
+ )
853
+ files: Dict[str, Any] = {"meta": (None, json.dumps(meta), "application/json")}
854
+ if sample is not None:
855
+ files["sample"] = await asyncio.to_thread(_file_part, sample, file_name, "sample.webm")
856
+ data = await self._t.json("POST", "/v1/speakers", files=files, idempotency_key=idempotency_key)
857
+ return _one(m.Speaker, data)
858
+
859
+ async def create_from_appearance(
860
+ self,
861
+ *,
862
+ transcription_id: str,
863
+ appearance: int,
864
+ name: str,
865
+ color: Optional[str] = None,
866
+ consent: Optional[bool] = None,
867
+ spans: Optional[List[Dict[str, float]]] = None,
868
+ draft: Optional[bool] = None,
869
+ library: Optional[bool] = None,
870
+ idempotency_key: Optional[str] = None,
871
+ ) -> m.Speaker:
872
+ """Save a speaker from one appearance of a transcription (``appearance``
873
+ is the ``speaker`` index of their lines). ``consent=True`` asserts
874
+ permission and clones their voice; ``library=False`` keeps them with
875
+ that transcription only."""
876
+ body = _body(
877
+ m.CreateSpeakerFromAppearance,
878
+ {
879
+ "transcription_id": transcription_id,
880
+ "appearance": appearance,
881
+ "name": name,
882
+ "color": color,
883
+ "consent": consent,
884
+ "spans": spans,
885
+ "draft": draft,
886
+ "library": library,
887
+ },
888
+ )
889
+ data = await self._t.json("POST", "/v1/speakers/from-appearance", json_body=body, idempotency_key=idempotency_key)
890
+ return _one(m.Speaker, data)
891
+
892
+ async def appearance_samples(
893
+ self, *, transcription_id: str, appearance: int, spans: Optional[List[Dict[str, float]]] = None
894
+ ) -> m.AppearanceSamples:
895
+ """A speaker's sentences in a transcription judged as samples for a cloned
896
+ voice, and the ones the server would use (``chosen``). Pass the
897
+ ``start``/``end`` of the ones you want as ``spans`` to
898
+ ``create_from_appearance``. With ``spans``, ``picked`` says whether
899
+ those samples hold enough clear speech to build a voice."""
900
+ picked = ",".join(f"{s['start']}-{s['end']}" for s in spans) if spans else None
901
+ data = await self._t.json(
902
+ "GET",
903
+ "/v1/speakers/from-appearance/samples",
904
+ query={"transcription": transcription_id, "appearance": appearance, "spans": picked},
905
+ )
906
+ return _one(m.AppearanceSamples, data)
907
+
908
+ async def set_consent(self, id: str, consent: str, *, name: Optional[str] = None) -> m.Speaker:
909
+ """Record whether the speaker agreed to their clone: ``granted`` (with an
910
+ optional name) makes their voice speak; ``refused`` deletes its audio
911
+ and voice. Automatic clones start ``pending``."""
912
+ body = _body(m.SetConsent, {"consent": consent, "name": name})
913
+ return _one(m.Speaker, await self._t.json("POST", f"/v1/speakers/{_p(id)}/consent", json_body=body))
914
+
915
+ async def update(self, id: str, **fields: Any) -> m.Speaker:
916
+ """Rename or recolour; ``enabled`` turns the cloned voice on or off;
917
+ ``consent=True`` on a speaker without a clone starts one from their sample."""
918
+ body = _body(m.PatchSpeaker, fields)
919
+ return _one(m.Speaker, await self._t.json("PATCH", f"/v1/speakers/{_p(id)}", json_body=body))
920
+
921
+ async def delete(self, id: str) -> None:
922
+ await self._t.json("DELETE", f"/v1/speakers/{_p(id)}")
923
+
924
+ async def voice_preview(
925
+ self,
926
+ id: str,
927
+ *,
928
+ lang: Optional[str] = None,
929
+ format: Optional[str] = None,
930
+ transcription: Optional[str] = None,
931
+ listener_token: Optional[str] = None,
932
+ share_code: Optional[str] = None,
933
+ as_owner: bool = True,
934
+ ) -> bytes:
935
+ """The speaker's cloned voice speaking ``lang``. With ``transcription``, as
936
+ it speaks in that transcription, for whoever may read it (its owner, or a
937
+ listener with ``listener_token`` or ``share_code``)."""
938
+ resp = await self._t.raw(
939
+ "GET",
940
+ f"/v1/speakers/{_p(id)}/preview",
941
+ headers={"accept": "*/*"},
942
+ query={**listener_query(listener_token, share_code), "lang": lang, "format": format, "transcription": transcription},
943
+ anonymous=not as_owner,
944
+ )
945
+ return resp.content
946
+
947
+ async def sample(self, id: str) -> bytes:
948
+ resp = await self._t.raw("GET", f"/v1/speakers/{_p(id)}/sample", headers={"accept": "*/*"})
949
+ return resp.content
950
+
951
+ async def list_invites(self) -> List[m.SpeakerInvite]:
952
+ """Invitations still waiting for their person to record, newest first."""
953
+ return _many(m.SpeakerInvite, await self._t.json("GET", "/v1/speakers/invites"), "invites")
954
+
955
+ async def invite(
956
+ self, name: str, *, email: Optional[str] = None, gender: Optional[str] = None, color: Optional[str] = None
957
+ ) -> m.SpeakerInvite:
958
+ """Invite a person by link to record their own voice and agree to have it
959
+ cloned. ``url`` is the link to send them (emailed too with ``email``);
960
+ it works once and for 7 days."""
961
+ body = _body(m.CreateSpeakerInvite, {"name": name, "email": email, "gender": gender, "color": color})
962
+ return _one(m.SpeakerInvite, await self._t.json("POST", "/v1/speakers/invites", json_body=body))
963
+
964
+ async def cancel_invite(self, id: str) -> None:
965
+ await self._t.json("DELETE", f"/v1/speakers/invites/{_p(id)}")
966
+
967
+ async def renew_invite(self, id: str) -> m.SpeakerInvite:
968
+ """A new link for 7 more days; the old one stops working."""
969
+ return _one(m.SpeakerInvite, await self._t.json("POST", f"/v1/speakers/invites/{_p(id)}/renew"))
970
+
971
+
972
+ class SpeakerInvites(_Group):
973
+ """``vs.speaker_invites``: what an invited person does with their link, with no credential."""
974
+
975
+ async def get(self, token: str) -> m.OpenSpeakerInvite:
976
+ return _one(m.OpenSpeakerInvite, await self._t.json("GET", f"/v1/speaker-invites/{_p(token)}", anonymous=True))
977
+
978
+ async def submit(
979
+ self, token: str, *, sample: Upload, consent: bool, email: Optional[str] = None, file_name: Optional[str] = None
980
+ ) -> Dict[str, Any]:
981
+ """Send the invited person's own recording; ``consent=True`` is their
982
+ agreement to have their voice cloned. ``email`` gets a link to withdraw it."""
983
+ meta = _body(m.SubmitSpeakerInvite, {"consent": consent, "email": email})
984
+ files: Dict[str, Any] = {"meta": (None, json.dumps(meta), "application/json")}
985
+ files["sample"] = await asyncio.to_thread(_file_part, sample, file_name, "sample.webm")
986
+ return await self._t.json("POST", f"/v1/speaker-invites/{_p(token)}", files=files, anonymous=True)
987
+
988
+ async def withdrawal(self, token: str) -> m.SpeakerConsentWithdrawal:
989
+ return _one(m.SpeakerConsentWithdrawal, await self._t.json("GET", f"/v1/speaker-invites/withdraw/{_p(token)}", anonymous=True))
990
+
991
+ async def withdraw(self, token: str) -> m.SpeakerConsentWithdrawal:
992
+ """Take back consent: the cloned voice and the voice sample are deleted."""
993
+ return _one(m.SpeakerConsentWithdrawal, await self._t.json("POST", f"/v1/speaker-invites/withdraw/{_p(token)}", anonymous=True))
994
+
995
+
996
+ class Search(_Group):
997
+ """``vs.search``: full-text and vector search over the caller's transcripts."""
998
+
999
+ async def query(
1000
+ self,
1001
+ q: str,
1002
+ *,
1003
+ broadcasts: Optional[List[str]] = None,
1004
+ listener_tokens: Optional[List[str]] = None,
1005
+ transcription: Optional[str] = None,
1006
+ lang: Optional[str] = None,
1007
+ limit: Optional[int] = None,
1008
+ site: Optional[str] = None,
1009
+ language: Optional[str] = None,
1010
+ kind: Optional[str] = None,
1011
+ origin: Optional[str] = None,
1012
+ tag: Optional[str] = None,
1013
+ created_after: Optional[Union[str, datetime.date]] = None,
1014
+ created_before: Optional[Union[str, datetime.date]] = None,
1015
+ shared: Optional[bool] = None,
1016
+ ) -> m.SearchResults:
1017
+ """``q`` is 2 or more characters; ``broadcasts`` narrows to those links (codes).
1018
+ ``site``, ``language``, ``kind``, ``origin``, ``tag``, ``created_after``,
1019
+ ``created_before`` and ``shared`` are ``transcriptions.list``'s filters and
1020
+ narrow the search to the caller's own transcriptions; a hit's ``share_code``
1021
+ plays in ``@vocalstack/player`` from ``media_start``."""
1022
+ query = {
1023
+ "q": q,
1024
+ "broadcasts": ",".join(broadcasts) if broadcasts else None,
1025
+ "listenerTokens": ",".join(listener_tokens) if listener_tokens else None,
1026
+ "transcription": transcription,
1027
+ "lang": lang,
1028
+ "limit": limit,
1029
+ **_list_filters(
1030
+ site=site, language=language, kind=kind, origin=origin, tag=tag,
1031
+ created_after=created_after, created_before=created_before, shared=shared,
1032
+ ),
1033
+ }
1034
+ return _one(m.SearchResults, await self._t.json("GET", "/v1/search", query=query))
1035
+
1036
+ async def vector(
1037
+ self,
1038
+ q: str,
1039
+ *,
1040
+ transcription: Optional[str] = None,
1041
+ site: Optional[str] = None,
1042
+ language: Optional[str] = None,
1043
+ kind: Optional[str] = None,
1044
+ origin: Optional[str] = None,
1045
+ tag: Optional[str] = None,
1046
+ created_after: Optional[Union[str, datetime.date]] = None,
1047
+ created_before: Optional[Union[str, datetime.date]] = None,
1048
+ shared: Optional[bool] = None,
1049
+ ) -> m.VectorResults:
1050
+ """Vector search: the caller's paragraphs closest in meaning to ``q``, in any
1051
+ language. Each hit carries its whole paragraph as ``passage`` (context for
1052
+ your own model) and its ``similarity``; ``allowance`` is the plan's searches
1053
+ left this hour (``None`` with no limit)."""
1054
+ query = {
1055
+ "q": q,
1056
+ "transcription": transcription,
1057
+ **_list_filters(
1058
+ site=site, language=language, kind=kind, origin=origin, tag=tag,
1059
+ created_after=created_after, created_before=created_before, shared=shared,
1060
+ ),
1061
+ }
1062
+ return _one(m.VectorResults, await self._t.json("GET", "/v1/search/vector", query=query))
1063
+
1064
+
1065
+ class Me(_Group):
1066
+ """``vs.me``: who the credential is, and the workspace it works in
1067
+ (``workspace``: ``id``, ``name``, ``personal``, ``iconUrl``)."""
1068
+
1069
+ async def get(self) -> Dict[str, Any]:
1070
+ return await self._t.json("GET", "/v1/me")
1071
+
1072
+
1073
+ class Connect(_Group):
1074
+ """``vs.connect``: one-click Connect, on the app's server."""
1075
+
1076
+ async def token(self, *, code: str, code_verifier: str, redirect_uri: str) -> Dict[str, Any]:
1077
+ """Redeem the ``code`` the dashboard sent to the app's ``redirect_uri``
1078
+ for an API key (OAuth 2.0 authorization code + PKCE): ``code_verifier``
1079
+ is the verifier whose ``BASE64URL(SHA256(verifier))`` was the link's
1080
+ ``code_challenge``, ``redirect_uri`` exactly the link's. Returns the
1081
+ wire's ``{ access_token, token_type, key_id, scope, account }``;
1082
+ ``access_token`` is the key, shown once. No credential is sent, even
1083
+ when the client has one, and the call is never retried: the code
1084
+ works once. A refusal raises :class:`VocalStackError` whose ``code``
1085
+ is OAuth's ``error`` (``invalid_grant``: an unknown, spent or expired
1086
+ code, or a verifier or ``redirect_uri`` that does not match)."""
1087
+ form = {
1088
+ "grant_type": "authorization_code",
1089
+ "code": code,
1090
+ "code_verifier": code_verifier,
1091
+ "redirect_uri": redirect_uri,
1092
+ }
1093
+ return await self._t.json(
1094
+ "POST", "/v1/connect/token", data=form, anonymous=True, no_retry=True, oauth_errors=True
1095
+ )
1096
+
1097
+ async def revoke(self) -> None:
1098
+ """Revoke the API key this client is using, and only that one: sign
1099
+ out of the app or switch workspace. Every later call with the key
1100
+ raises ``invalid_token``. Never retried."""
1101
+ await self._t.json("POST", "/v1/connect/revoke", no_retry=True)
1102
+
1103
+
1104
+ class Billing(_Group):
1105
+ """``vs.billing``: the account's plan, credit balance and limits, the
1106
+ price list, the ledger and the per-transcription charges."""
1107
+
1108
+ async def get(self) -> m.BillingView:
1109
+ """The account: plan, rates, balance, limits, subscription, top-up URL."""
1110
+ return _one(m.BillingView, await self._t.json("GET", "/v1/billing"))
1111
+
1112
+ async def plans(self) -> m.PlanList:
1113
+ """The visible plans with their current rates and limits (no credential needed)."""
1114
+ return _one(m.PlanList, await self._t.json("GET", "/v1/billing/plans"))
1115
+
1116
+ async def ledger(self, *, cursor: Optional[str] = None, limit: Optional[int] = None) -> m.LedgerPage:
1117
+ """The ledger, newest first; ``cursor`` is the previous page's ``next_cursor``."""
1118
+ return _one(m.LedgerPage, await self._t.json("GET", "/v1/billing/ledger", query={"cursor": cursor, "limit": limit}))
1119
+
1120
+ async def charges(self, *, cursor: Optional[str] = None, limit: Optional[int] = None) -> m.ChargePage:
1121
+ """The per-transcription charges, newest first."""
1122
+ return _one(m.ChargePage, await self._t.json("GET", "/v1/billing/charges", query={"cursor": cursor, "limit": limit}))
1123
+
1124
+ async def create_checkout(self, *, idempotency_key: Optional[str] = None, **fields: Any) -> m.CheckoutView:
1125
+ """Open a checkout at the payment provider (``kind="topup", amount=``
1126
+ or ``kind="subscribe", plan_id=, interval=``, with ``accept_terms=True``:
1127
+ the Terms and the request that the purchase start now); send the
1128
+ customer to ``url``. A signed-in person only, never an API key."""
1129
+ body = _body(m.CreateCheckout, fields)
1130
+ return _one(m.CheckoutView, await self._t.json("POST", "/v1/billing/checkouts", json_body=body, idempotency_key=idempotency_key))
1131
+
1132
+ async def get_checkout(self, id: str) -> m.CheckoutView:
1133
+ """A checkout's status (by its id or the provider's)."""
1134
+ return _one(m.CheckoutView, await self._t.json("GET", f"/v1/billing/checkouts/{_p(id)}"))
1135
+
1136
+ async def cancel_subscription(self) -> m.SubscriptionView:
1137
+ """Cancel the subscription at the end of its period."""
1138
+ return _one(m.SubscriptionView, await self._t.json("POST", "/v1/billing/subscription/cancel"))
1139
+
1140
+ async def uncancel_subscription(self) -> m.SubscriptionView:
1141
+ """Take back a scheduled cancellation."""
1142
+ return _one(m.SubscriptionView, await self._t.json("POST", "/v1/billing/subscription/uncancel"))
1143
+
1144
+ async def set_auto_top_up(self, **fields: Any) -> m.AutoTopUpView:
1145
+ """Turn auto top-up on (``threshold`` and ``amount`` from the plan list's choices) or off."""
1146
+ body = _body(m.AutoTopUpSettings, fields)
1147
+ return _one(m.AutoTopUpView, await self._t.json("PUT", "/v1/billing/auto-top-up", json_body=body))
1148
+
1149
+ async def portal(self) -> m.PortalLink:
1150
+ """A link to the provider's customer portal (payment methods, invoices, receipts)."""
1151
+ return _one(m.PortalLink, await self._t.json("GET", "/v1/billing/portal"))
1152
+
1153
+ async def retry_auto_top_up(self) -> m.AutoTopUpView:
1154
+ """Charge the configured auto top-up amount now (under the day's cap)."""
1155
+ return _one(m.AutoTopUpView, await self._t.json("POST", "/v1/billing/auto-top-up/retry"))
1156
+
1157
+ async def set_low_balance_alert(self, **fields: Any) -> m.LowBalanceAlertView:
1158
+ """Turn the low-balance email on or off (``enabled``) and set its line (``threshold``)."""
1159
+ body = _body(m.LowBalanceAlertSettings, fields)
1160
+ return _one(m.LowBalanceAlertView, await self._t.json("PUT", "/v1/billing/low-balance-alert", json_body=body))
1161
+
1162
+ async def set_interval(self, **fields: Any) -> m.SubscriptionView:
1163
+ """Renew ``interval="month"`` or ``"year"`` from the next period, at
1164
+ ``subscription.switch_prices`` (needs ``accept_terms=True`` and
1165
+ ``no_new_withdrawal_period_shown=True``)."""
1166
+ body = _body(m.SetInterval, fields)
1167
+ return _one(m.SubscriptionView, await self._t.json("POST", "/v1/billing/subscription/interval", json_body=body))
1168
+
1169
+ async def opt_in_yearly(self, **fields: Any) -> m.SubscriptionView:
1170
+ """Keep the subscription by switching to yearly when monthly billing
1171
+ is withdrawn (``subscription.yearly_opt_in``); needs
1172
+ ``accept_terms=True`` and ``no_new_withdrawal_period_shown=True``."""
1173
+ body = _body(m.YearlyOptIn, fields)
1174
+ return _one(m.SubscriptionView, await self._t.json("POST", "/v1/billing/subscription/yearly-opt-in", json_body=body))
1175
+
1176
+ async def unset_interval(self) -> m.SubscriptionView:
1177
+ """Take back a scheduled interval switch."""
1178
+ return _one(m.SubscriptionView, await self._t.json("DELETE", "/v1/billing/subscription/interval"))
1179
+
1180
+ async def usage(self, *, start_date: Optional[str] = None, end_date: Optional[str] = None, tz: Optional[str] = None) -> m.UsageReport:
1181
+ """What the account spent per day (``YYYY-MM-DD`` in ``tz``), source and kind."""
1182
+ return _one(m.UsageReport, await self._t.json("GET", "/v1/billing/usage", query={"startDate": start_date, "endDate": end_date, "tz": tz}))
1183
+
1184
+ async def usage_charges(
1185
+ self,
1186
+ *,
1187
+ start_date: Optional[str] = None,
1188
+ end_date: Optional[str] = None,
1189
+ tz: Optional[str] = None,
1190
+ kind: Optional[str] = None,
1191
+ source: Optional[str] = None,
1192
+ cursor: Optional[str] = None,
1193
+ limit: Optional[int] = None,
1194
+ ) -> m.UsageChargePage:
1195
+ """The usage report's charges one by one, newest first; ``kind`` (``file``/``live``) and ``source`` (``dashboard`` or a key id) filter, ``count`` and ``total`` cover every match."""
1196
+ query = {"startDate": start_date, "endDate": end_date, "tz": tz, "kind": kind, "source": source, "cursor": cursor, "limit": limit}
1197
+ return _one(m.UsageChargePage, await self._t.json("GET", "/v1/billing/usage/charges", query=query))
1198
+
1199
+ async def payments(self, *, cursor: Optional[str] = None, limit: Optional[int] = None) -> m.PaymentPage:
1200
+ """The payments history, newest first."""
1201
+ return _one(m.PaymentPage, await self._t.json("GET", "/v1/billing/payments", query={"cursor": cursor, "limit": limit}))
1202
+
1203
+ async def payment_document(self, id: str) -> m.PaymentDocument:
1204
+ """A payment's invoice or receipt: ``url``, or ``pending`` while the provider makes it."""
1205
+ return _one(m.PaymentDocument, await self._t.json("GET", f"/v1/billing/payments/{_p(id)}/document"))
1206
+
1207
+ async def payment_methods(self) -> m.PaymentMethodList:
1208
+ """The saved payment methods."""
1209
+ return _one(m.PaymentMethodList, await self._t.json("GET", "/v1/billing/payment-methods"))
1210
+
1211
+ async def delete_payment_method(self, id: str) -> None:
1212
+ """Remove a saved payment method."""
1213
+ await self._t.json("DELETE", f"/v1/billing/payment-methods/{_p(id)}")
1214
+
1215
+ async def manage_payment_methods(self) -> m.PortalLink:
1216
+ """A link to the provider's portal to add a card or choose the default."""
1217
+ return _one(m.PortalLink, await self._t.json("POST", "/v1/billing/payment-methods/manage"))
1218
+
1219
+ async def details(self) -> m.BillingDetails:
1220
+ """The invoice details."""
1221
+ return _one(m.BillingDetails, await self._t.json("GET", "/v1/billing/details"))
1222
+
1223
+ async def set_details(self, **fields: Any) -> m.BillingDetails:
1224
+ """Save the invoice details (``name``, ``email``, ``line1``, ``city``, ``postal_code``, ``country``, ``tax_id``)."""
1225
+ body = _body(m.BillingDetails, fields)
1226
+ return _one(m.BillingDetails, await self._t.json("PUT", "/v1/billing/details", json_body=body))
1227
+
1228
+ async def check_promo_code(self, **fields: Any) -> m.PromoCodeView:
1229
+ """What a promo code gives (``code``, ``for_="topup"`` or ``"subscribe"``)."""
1230
+ body = _body(m.CheckPromoCode, fields)
1231
+ return _one(m.PromoCodeView, await self._t.json("POST", "/v1/billing/promo-codes/check", json_body=body))
1232
+
1233
+
1234
+ class Languages(_Group):
1235
+ async def list(self) -> m.LanguageLists:
1236
+ """Spoken and translation languages."""
1237
+ return _one(m.LanguageLists, await self._t.json("GET", "/v1/languages"))
1238
+
1239
+
1240
+ class Rtmp(_Group):
1241
+ async def status(self) -> m.RtmpStatus:
1242
+ """The account's RTMP ingest: server URL (RTMPS where available), the stream key (in full only in the answer that made it, masked_stream_key after), whether an encoder is sending."""
1243
+ return _one(m.RtmpStatus, await self._t.json("GET", "/v1/rtmp"))
1244
+
1245
+ async def create_key(self, **fields: Any) -> m.CreatedAppStreamKey:
1246
+ """A stream key of the app's own, beside the account's (``name``): ``stream_key`` is in full in this answer only. It works while the API key that made it does."""
1247
+ body = _body(m.CreateAppStreamKey, fields)
1248
+ return _one(m.CreatedAppStreamKey, await self._t.json("POST", "/v1/rtmp/keys", json_body=body))
1249
+
1250
+ async def list_keys(self) -> List[m.AppStreamKey]:
1251
+ """The account's app stream keys, oldest first: masked, each with whether an encoder is sending on it (``live``, ``audio``)."""
1252
+ items = await _all_pages(lambda c: self._t.json("GET", "/v1/rtmp/keys", query={"cursor": c}), "keys")
1253
+ return [m.AppStreamKey.model_validate(x) for x in items]
1254
+
1255
+ async def delete_key(self, id: str) -> None:
1256
+ """Delete an app stream key: an encoder publishing on it is dropped within seconds."""
1257
+ await self._t.json("DELETE", f"/v1/rtmp/keys/{_p(id)}")
1258
+
1259
+
1260
+ class Events(_Group):
1261
+ async def account(self) -> Any:
1262
+ """The account socket: ``events.ready``, then ``lists.changed``
1263
+ whenever a list of broadcasts or transcriptions is out of date."""
1264
+ return await websockets.connect(self._t.ws_url("/v1/events"), additional_headers=self._t.auth_headers())
1265
+
1266
+
1267
+ class Meta(_Group):
1268
+ async def health(self) -> m.Health:
1269
+ return _one(m.Health, await self._t.json("GET", "/v1/health"))
1270
+
1271
+ async def openapi(self) -> Dict[str, Any]:
1272
+ """The OpenAPI document the models are generated from."""
1273
+ return await self._t.json("GET", "/v1/openapi.json")
1274
+
1275
+ async def client_policy(self, client: str) -> m.ClientPolicy:
1276
+ """A VocalStack app's version policy: the newest build and which versions are deprecated or unsupported."""
1277
+ return _one(m.ClientPolicy, await self._t.json("GET", f"/v1/clients/{_p(client)}"))