@vocalstack/payload 0.1.0 → 0.4.0

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.
package/README.md CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  VocalStack for [Payload CMS](https://payloadcms.com) 3: a **Transcribe** button on every audio upload. The transcript is saved on the document as text plus timed sentences.
4
4
 
5
- ## Install
5
+ Read more about the [VocalStack transcription plugin for Payload CMS](https://vocalstack.com/payload-cms-transcription-plugin/) on the [VocalStack website](https://vocalstack.com/).
6
6
 
7
- Not on npm. Install from this repo; `dist/` is committed, so nothing builds on install (run `pnpm build` and commit `dist/` with every change):
7
+ ## Install
8
8
 
9
9
  ```sh
10
- pnpm add github:vocalstack/payload-plugin
10
+ pnpm add @vocalstack/payload
11
11
  ```
12
12
 
13
13
  ```ts
@@ -35,6 +35,12 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
35
35
  - `sentences`: `[{ start, end, speaker, text }]` in seconds.
36
36
  - `status`, `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
37
37
  - `POST /api/{collection}/:id/vocalstack/transcribe`, `POST …/vocalstack/stop`, `GET …/vocalstack/status` and `GET …/vocalstack/stream` (live progress as Server-Sent Events).
38
+ - **Translations and readings**, under every finished transcript: translate it into up to 10 of VocalStack's 100 languages (VocalStack's limit per recording), and have each translation read aloud where VocalStack has a voice for it. VocalStack picks the voices; a toggle on each transcript chooses between **synthetic** voices and the speakers' own **cloned** voices (where they have one, made with their permission), saved as `voices`. One click in the admin does both; the server carries on until it is done, with no one watching. Saved in the `vocalstack` group as:
39
+ - `translations`: `{ [lang]: { translatedAt, sentences, pending?, error?, requestedAt? } }`, the transcript's sentences (same ids and times) translated. `pending` while the server is still translating it.
40
+ - `speech`: `{ [lang]: { voice, state, error, durationS, requestedAt, renderedAt, sentences, audio } }`. `state` is `translating` (waiting for its translation), `queued`, `running`, `failed` or `sealed`; once sealed, `sentences` are the translation in the reading's own timing, with words, for a read-along player, and `audio` is the MP3 kept in your storage.
41
+ - `POST …/vocalstack/voices { voices: 'synthetic' | 'cloned' }`, `POST …/vocalstack/request { langs, speak? }` (translate, and read aloud unless `speak: false`; carried on by the server), `POST …/vocalstack/translate { langs }` (one step; answers `more: true` when it stopped for time), `DELETE …/vocalstack/translate?lang=`, `POST …/vocalstack/speak { langs }`, `GET …/vocalstack/speak`, and the public `GET …/vocalstack/audio?lang=`, which redirects to the reading's MP3 (or, with no `lang` or the spoken one, the recording's audio) for anyone who may read the document.
42
+ - **Languages for listeners** (opt in with `listeners`): visitors pick any language VocalStack offers, and it is made for them and kept for everyone after. `GET /api/vocalstack/languages` is public, `POST …/vocalstack/listen { lang }` asks for a language and `GET …/vocalstack/listen?lang=` says where it stands; see below.
43
+ - **Voices** (opt in with `voices`): documents of a collection of people get a sidebar panel to clone that person's voice from a minute of a recording they speak in, or from an uploaded sample, with their permission. Kept in a hidden `vocalstackVoice` group (`voiceId`, `state`: `none`/`training`/`ready`/`failed`, `progress`, `error`, `sampleS`, `consentAt`, `createdAt`), with `GET`/`POST`/`DELETE /api/{collection}/:id/vocalstack/voice`, `…/voice/sources` and `…/voice/preview`.
38
44
  - **Settings → VocalStack** (a global), where an editor connects an account. The key is stored server-side and is unreadable over the REST and GraphQL APIs.
39
45
 
40
46
  ## Options
@@ -46,10 +52,13 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
46
52
  | `audioFields` | none | Audio that isn't an upload document; see below. |
47
53
  | `spokenLanguage` | auto-detect | A Whisper language code (`en`, `ro`, …). |
48
54
  | `fileURL` | the doc's `url`, made absolute | `({ doc, collection, req }) => string`: the address VocalStack fetches. Point it at your bucket's public URL to skip the Payload file proxy. |
49
- | `access` | signed-in users who can update the doc | Extra check for transcribing and for changing the connection. |
55
+ | `access` | signed-in users who can update the doc | Extra check for transcribing, translating, voices and the admin lookups, and for changing the connection. |
50
56
  | `oneClickConnect` | `false` | Show **Connect VocalStack** (see below). |
51
57
  | `apiURL` / `dashboardURL` | `https://api.vocalstack.com` / `https://app.vocalstack.com` | |
52
58
  | `enabled` | `true` | `false` keeps the schema but removes the button and the endpoints. |
59
+ | `voices` | none | Collections of people who get a cloned voice; see below. |
60
+ | `readings` | `{ slug: 'vocalstack-readings' }` | The upload collection finished readings are kept in, added by the plugin; `overrides: (collection) => collection` adjusts it. `false` streams readings from VocalStack instead. See below for bringing your own. |
61
+ | `listeners` | off | `true`, or `{ languages?, speak?, access?, perHour? }`: let visitors ask for a transcript in their language; see below. |
53
62
 
54
63
  ### Audio that isn't an upload
55
64
 
@@ -70,6 +79,56 @@ vocalstackPlugin({
70
79
 
71
80
  Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?field=attachments&row=<row id>`. A new row needs saving first.
72
81
 
82
+ ### Voices
83
+
84
+ ```ts
85
+ import { vocalstackPlugin } from '@vocalstack/payload'
86
+
87
+ vocalstackPlugin({
88
+ voices: [
89
+ {
90
+ collection: 'speakers',
91
+ // Recordings this speaker is in, offered as the sample to clone from.
92
+ recordings: async ({ doc, req }) => {
93
+ const { docs } = await req.payload.find({ collection: 'episodes', where: { speaker: { equals: doc.id } }, req })
94
+ return docs.flatMap((e) => (e.vocalstack?.recordingId ? [{ label: e.title, recordingId: e.vocalstack.recordingId, sentences: e.vocalstack.sentences }] : []))
95
+ },
96
+ },
97
+ ],
98
+ })
99
+ ```
100
+
101
+ A sample from a recording can only come from the recordings `recordings` returns for that document: cloning, and hearing a stretch first (`GET /:id/vocalstack/voice/clip`), refuse any other.
102
+
103
+ Cloning needs at least 30 seconds of the person speaking alone (a minute is better, at most two), and the editor confirms they have the person's permission. From a recording, the editor clicks where the stretch starts and hears it before cloning; the plugin takes it from VocalStack. An uploaded sample is sent through your server, so on hosts that cap request bodies (Vercel: 4.5 MB) keep it to a minute or two of MP3 or M4A. Training takes a few minutes; the panel follows it. Deleting the voice deletes it in VocalStack too. Readings don't name a voice: VocalStack picks it for each recording.
104
+
105
+ ### Translations and readings
106
+
107
+ Translating an hour-long transcript takes a few minutes. The server does it in steps of about 20 seconds, each saved as it goes, and carries on after each response whenever the document is read or its progress is asked for, so an editor can close the page (and a translation started by a listener finishes on its own). A recording has at most 10 languages besides its spoken one; asking for an 11th answers 409 `language_limit_reached`. A reading is rendered by VocalStack (a few languages at a time per recording) and saved once ready. The reading keeps each sentence where it was said, unless the one before still runs, so a player can follow along with `speech[lang].sentences` (`timedTokens()` works on them as on the transcript).
108
+
109
+ **Everything is asked for once and kept.** The transcript (text, sentences, word times) and each translation are saved on the document. Translating again only asks for sentences that have none, and reads ones VocalStack already translated back from `/transcript?lang=` rather than translating them again. A finished reading's MP3 is downloaded once and saved as an upload in the `vocalstack-readings` collection (option `readings`), so listeners are served from your storage: `GET …/vocalstack/audio` redirects to that file, or for the spoken language to your own audio file, and only falls back to VocalStack while a reading isn't kept yet. Point your storage adapter at the readings collection, e.g. `s3Storage({ collections: { 'vocalstack-readings': { prefix: 'readings', disablePayloadAccessControl: true } } })` for direct public URLs.
110
+
111
+ **The readings collection.** By default the plugin adds `vocalstack-readings`: public read, and create, update and delete for signed-in users. Change it with `readings: { overrides: (collection) => ({ ...collection, access: { ... } }) }`, or define an upload collection with that slug (or `readings.slug`) yourself; the plugin then uses yours as it is. It needs to accept `audio/mpeg` and to have text fields `lang`, `recordingId` and `voice`.
112
+
113
+ ### Languages for listeners
114
+
115
+ With `listeners: true`, anyone who may read a document can ask for its transcript in another language, from your own site:
116
+
117
+ ```ts
118
+ // What can be asked for: { languages: [{ code, name, native, translation, voice }], translation, voice }
119
+ await fetch('/api/vocalstack/languages')
120
+ // Ask (on an array row add ?field=&row= as for transcribing). Asked already: answers where it stands.
121
+ await fetch(`/api/sermons/${id}/vocalstack/listen`, { method: 'POST', body: JSON.stringify({ lang: 'pl' }) })
122
+ // Follow it: { state: 'translating' | 'ready' | 'failed' | 'none', done, total, voice, speech: { state, audio }, version }
123
+ await fetch(`/api/sermons/${id}/vocalstack/listen?lang=pl`)
124
+ ```
125
+
126
+ The translation is saved on the document, and where VocalStack can read the language aloud, the reading follows (in the voice VocalStack picks) and its MP3 is kept in the readings collection. Once `speech.state` is `ready`, `speech.audio` is that file in your own storage. Nothing is made twice: a language someone already asked for is answered from the document. Visitors can only ask for languages VocalStack offers (narrowed by `languages`), within the 10-language limit, and each one (by IP address) can ask for `perHour` new languages an hour (10 by default); `access: ({ lang, req }) => boolean` adds your own check. The language list keeps working when VocalStack can't be reached: the plugin falls back to its last answer, or to the list it ships with.
127
+
128
+ **Your site keeps working without VocalStack.** Everything a listener reads or hears (the transcript, every translation, every reading's MP3 and word timings) is served from your database and storage. VocalStack is only needed to make something new.
129
+
130
+ When VocalStack does not answer (an outage, an upgrade), the endpoints say *VocalStack is unavailable, try again shortly.* instead of waiting.
131
+
73
132
  **How the audio reaches VocalStack.** If the file has a public address, VocalStack fetches it (`POST /v1/transcriptions { url }`). Otherwise (localhost, a private network) the plugin uploads the bytes. Either way the job runs on VocalStack, and the admin polls every 3 s. The account is billed per second, with a 5-minute minimum per transcription.
74
133
 
75
134
  ## One-click connect (protocol)
@@ -96,3 +155,7 @@ tab: "Connected", BroadcastChannel('vocalstack') ─▶ admin refreshes; tab clo
96
155
  ```
97
156
 
98
157
  Cancel redirects with `?error=access_denied&state=…`. The key appears in the dashboard's API keys list as `example.com (Payload CMS)`, where it can be revoked.
158
+
159
+ ## Releasing
160
+
161
+ Bump `version` in `package.json` and push to `main`. The `publish` workflow publishes that version to npm (trusted publishing, with provenance), tags `v<version>` and creates the GitHub release. A version npm already has is skipped. A prerelease (`0.5.0-beta.1`) goes to the `next` dist-tag. Nobody publishes from a laptop.
package/dist/api.d.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  /**
2
- * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
- * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
2
+ * The VocalStack API calls the plugin needs, made through the VocalStack JS SDK
3
+ * (`@vocalstack/js-sdk`). This adapter keeps the plugin's own shapes and one error
4
+ * type, so an engine that is down reads the same everywhere.
5
+ * Contract: https://api.vocalstack.com/v1/openapi.json
4
6
  */
7
+ import { VocalStack } from '@vocalstack/js-sdk';
5
8
  export declare const DEFAULT_API_URL = "https://api.vocalstack.com";
6
9
  export declare const DEFAULT_DASHBOARD_URL = "https://app.vocalstack.com";
7
10
  export type JobState = 'cropping' | 'done' | 'failed' | 'fetching' | 'queued' | 'stopped' | 'transcribing';
@@ -48,16 +51,64 @@ export type Transcript = {
48
51
  text: string;
49
52
  }[];
50
53
  };
54
+ export type Voice = {
55
+ createdAt: string;
56
+ /** A trial voice, to hear before it is kept. */
57
+ draft?: boolean;
58
+ error?: null | string;
59
+ id: string;
60
+ name: string;
61
+ progress: number;
62
+ sampleS: number;
63
+ /** `training`, `ready` or `failed`. */
64
+ state: string;
65
+ };
66
+ export type VoiceOption = {
67
+ cloned: boolean;
68
+ default: boolean;
69
+ gender?: null | string;
70
+ id: string;
71
+ name: string;
72
+ quality: number;
73
+ ready?: boolean;
74
+ };
75
+ /** A recording's spoken translation in one language and voice (`voiceKey` is `''` for the default voice). */
76
+ export type VoiceTrack = {
77
+ /** Seconds each sentence's clip lasts, by sentence id. */
78
+ clipDur?: Record<string, number>;
79
+ clips: number[];
80
+ durationS?: null | number;
81
+ error?: null | string;
82
+ lang: string;
83
+ /** `queued`, `running`, `failed`, `sealed` (the track is ready), or `clips` (sentences only). */
84
+ state: string;
85
+ /** `synthetic` or `cloned` (the API's voice modes); older APIs answer a voice name here, or nothing. */
86
+ voice?: null | string;
87
+ voiceKey: string;
88
+ /** Each sentence's words as [start, end] within its clip, by sentence id. */
89
+ wordTimes?: Record<string, [number, number][]>;
90
+ };
91
+ export type Language = {
92
+ code: string;
93
+ name: string;
94
+ native: string;
95
+ translation: boolean;
96
+ voice: boolean;
97
+ };
98
+ export type Languages = {
99
+ languages: Language[];
100
+ translation: string[];
101
+ voice: string[];
102
+ };
103
+ export declare const UNAVAILABLE = "VocalStack is unavailable, try again shortly.";
51
104
  export declare class VocalStackAPIError extends Error {
52
105
  code: string;
53
106
  status: number;
54
107
  constructor(status: number, code: string, message: string);
55
108
  }
56
109
  export declare class VocalStackAPI {
57
- private apiKey;
58
- private baseURL;
110
+ readonly sdk: VocalStack;
59
111
  constructor(apiKey: string, baseURL?: string);
60
- private request;
61
112
  me(): Promise<Record<string, unknown>>;
62
113
  transcribeURL(url: string, opts: {
63
114
  idempotencyKey: string;
@@ -73,6 +124,64 @@ export declare class VocalStackAPI {
73
124
  /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
74
125
  stop(recordingId: string, reason?: string): Promise<unknown>;
75
126
  transcript(recordingId: string): Promise<Transcript>;
127
+ /**
128
+ * The translations VocalStack already holds for `lang`, by sentence id. `/translation`
129
+ * answers only the sentences it translates in that call, so stored ones are read here.
130
+ */
131
+ storedTranslations(recordingId: string, lang: string): Promise<Record<string, string>>;
132
+ languages(): Promise<Languages>;
133
+ /** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
134
+ translation(recordingId: string, lang: string, sentenceIds: number[]): Promise<{
135
+ lang: string;
136
+ translations: Record<string, string>;
137
+ }>;
138
+ /**
139
+ * Render spoken translations, one job per language, in the recording's default cast: VocalStack
140
+ * picks each speaker's voice. `cloned` lets it use speakers' own cloned voices (each made with
141
+ * that speaker's permission); otherwise it reads in stock voices.
142
+ */
143
+ speak(recordingId: string, langs: string[], opts?: {
144
+ cloned?: boolean;
145
+ }): Promise<VoiceTrack[]>;
146
+ voiceTracks(recordingId: string, lang?: string): Promise<VoiceTrack[]>;
147
+ /** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
148
+ audioURL(recordingId: string, opts: {
149
+ format?: 'caf' | 'mp3' | 'ogg';
150
+ kind: 'delivery' | 'voice';
151
+ lang?: string;
152
+ voice?: string;
153
+ }): Promise<string>;
154
+ /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
155
+ clip(recordingId: string, startS: number, endS: number): Promise<Response>;
156
+ voice(id: string): Promise<Voice>;
157
+ /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
158
+ createVoice(sample: Blob, fileName: string, meta: {
159
+ consent: boolean;
160
+ name: string;
161
+ }, idempotencyKey: string): Promise<Voice>;
162
+ /**
163
+ * Clone a speaker's voice from stretches of a transcribed recording (5–60 s in all). `draft`
164
+ * makes a trial voice to hear first; keep it with `keepVoice`, or delete it.
165
+ */
166
+ voiceFromSpeaker(opts: {
167
+ draft: boolean;
168
+ name: string;
169
+ recordingId: string;
170
+ spans: {
171
+ end: number;
172
+ start: number;
173
+ }[];
174
+ speaker: number;
175
+ }, idempotencyKey: string): Promise<Voice>;
176
+ /** Keep a trial voice, as `name`, with the speaker's permission. */
177
+ keepVoice(id: string, name: string): Promise<Voice>;
178
+ deleteVoice(id: string): Promise<unknown>;
179
+ availableVoices(lang: string, recordingId?: string): Promise<{
180
+ lang: string;
181
+ voices: VoiceOption[];
182
+ }>;
183
+ /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
184
+ voicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
76
185
  }
77
186
  /** A short label for the connected account, from whatever `/v1/me` carries. */
78
187
  export declare function accountLabel(me: Record<string, unknown>): string | undefined;
package/dist/api.js CHANGED
@@ -1,9 +1,13 @@
1
1
  /**
2
- * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
- * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
2
+ * The VocalStack API calls the plugin needs, made through the VocalStack JS SDK
3
+ * (`@vocalstack/js-sdk`). This adapter keeps the plugin's own shapes and one error
4
+ * type, so an engine that is down reads the same everywhere.
5
+ * Contract: https://api.vocalstack.com/v1/openapi.json
4
6
  */
7
+ import { VocalStack, VocalStackError } from '@vocalstack/js-sdk';
5
8
  export const DEFAULT_API_URL = 'https://api.vocalstack.com';
6
9
  export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
10
+ export const UNAVAILABLE = 'VocalStack is unavailable, try again shortly.';
7
11
  export class VocalStackAPIError extends Error {
8
12
  code;
9
13
  status;
@@ -13,50 +17,150 @@ export class VocalStackAPIError extends Error {
13
17
  this.status = status;
14
18
  }
15
19
  }
20
+ /** How long a call may take before VocalStack counts as unavailable. Translating and cloning are slow. */
21
+ function timeoutFor(url, method = 'GET') {
22
+ const path = new URL(url).pathname;
23
+ if (path.endsWith('/translation'))
24
+ return 180_000;
25
+ if (method === 'POST' && path === '/v1/voices')
26
+ return 120_000;
27
+ if (path.endsWith('/audio/clip') || path.endsWith('/preview'))
28
+ return 60_000;
29
+ return 30_000;
30
+ }
31
+ /** One error type: an engine that is down or slow (an upgrade, an outage) is `unavailable`. */
32
+ function toAPIError(err) {
33
+ if (err instanceof VocalStackAPIError)
34
+ return err;
35
+ if (err instanceof VocalStackError) {
36
+ const down = err.code === 'unavailable' || (err.code === 'internal' && (err.status === 502 || err.status === 503 || err.status === 504));
37
+ if (down)
38
+ return new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
39
+ return new VocalStackAPIError(err.status ?? 500, err.code, err.message);
40
+ }
41
+ if (err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError'))
42
+ return new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
43
+ return new VocalStackAPIError(500, 'http_error', err instanceof Error ? err.message : String(err));
44
+ }
45
+ const call = async (run) => {
46
+ try {
47
+ return await run();
48
+ }
49
+ catch (err) {
50
+ throw toAPIError(err);
51
+ }
52
+ };
16
53
  export class VocalStackAPI {
17
- apiKey;
18
- baseURL;
54
+ sdk;
19
55
  constructor(apiKey, baseURL = DEFAULT_API_URL) {
20
- this.apiKey = apiKey;
21
- this.baseURL = baseURL;
22
- }
23
- async request(method, path, body, headers = {}) {
24
- const init = { headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, ...headers }, method };
25
- if (body instanceof FormData)
26
- init.body = body;
27
- else if (body !== undefined) {
28
- init.body = JSON.stringify(body);
29
- init.headers['content-type'] = 'application/json';
30
- }
31
- const res = await fetch(`${this.baseURL}${path}`, init);
32
- const data = await res.json().catch(() => undefined);
33
- if (!res.ok) {
34
- const err = (data?.error ?? data);
35
- throw new VocalStackAPIError(res.status, err?.code ?? 'http_error', err?.message ?? `VocalStack answered ${res.status}`);
36
- }
37
- return data;
56
+ this.sdk = new VocalStack({
57
+ apiKey,
58
+ baseUrl: baseURL,
59
+ // One retry of a busy or restarting API; the admin and listeners ask again anyway.
60
+ maxRetries: 1,
61
+ fetch: (input, init) => fetch(input, { ...init, signal: init?.signal ?? AbortSignal.timeout(timeoutFor(String(input instanceof Request ? input.url : input), init?.method)) }),
62
+ });
38
63
  }
39
64
  me() {
40
- return this.request('GET', '/v1/me');
65
+ return call(() => this.sdk.me.get());
41
66
  }
42
67
  transcribeURL(url, opts) {
43
- return this.request('POST', '/v1/transcriptions', { name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined, url }, { 'idempotency-key': opts.idempotencyKey });
68
+ return call(() => this.sdk.transcriptions.create({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined, url }, { idempotencyKey: opts.idempotencyKey }));
44
69
  }
45
70
  transcribeFile(file, fileName, opts) {
46
- const form = new FormData();
47
- form.append('options', JSON.stringify({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }));
48
- form.append('file', file, fileName);
49
- return this.request('POST', '/v1/transcriptions', form, { 'idempotency-key': opts.idempotencyKey });
71
+ return call(() => this.sdk.transcriptions.create({ file, fileName, name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }, { idempotencyKey: opts.idempotencyKey }));
50
72
  }
51
73
  job(recordingId) {
52
- return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/job`);
74
+ return call(() => this.sdk.jobs.get(recordingId));
53
75
  }
54
76
  /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
55
77
  stop(recordingId, reason) {
56
- return this.request('POST', `/v1/recordings/${encodeURIComponent(recordingId)}/stop`, { reason: reason ?? null });
78
+ return call(() => this.sdk.recordings.stop(recordingId, reason));
57
79
  }
58
80
  transcript(recordingId) {
59
- return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript`);
81
+ return call(() => this.sdk.recordings.transcript(recordingId));
82
+ }
83
+ /**
84
+ * The translations VocalStack already holds for `lang`, by sentence id. `/translation`
85
+ * answers only the sentences it translates in that call, so stored ones are read here.
86
+ */
87
+ async storedTranslations(recordingId, lang) {
88
+ const t = (await call(() => this.sdk.recordings.transcript(recordingId, { lang })));
89
+ const out = {};
90
+ for (const s of t.sentences ?? []) {
91
+ const text = s.translations?.[lang];
92
+ if (text?.trim())
93
+ out[String(s.sentenceId)] = text;
94
+ }
95
+ return out;
96
+ }
97
+ languages() {
98
+ return call(() => this.sdk.languages.list());
99
+ }
100
+ /** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
101
+ translation(recordingId, lang, sentenceIds) {
102
+ return call(() => this.sdk.recordings.translation(recordingId, lang, sentenceIds));
103
+ }
104
+ /**
105
+ * Render spoken translations, one job per language, in the recording's default cast: VocalStack
106
+ * picks each speaker's voice. `cloned` lets it use speakers' own cloned voices (each made with
107
+ * that speaker's permission); otherwise it reads in stock voices.
108
+ */
109
+ async speak(recordingId, langs, opts = {}) {
110
+ const render = (body) => call(() => this.sdk.recordings.renderVoice(recordingId, body));
111
+ try {
112
+ return await render({ langs, voice: opts.cloned ? 'cloned' : 'synthetic' });
113
+ }
114
+ catch (err) {
115
+ // An API from before `voice: 'synthetic' | 'cloned'` takes it for a voice id: there, consent turns clones on.
116
+ if (!(err instanceof VocalStackAPIError && err.status === 400 && /no voice '(cloned|synthetic)'/.test(err.message)))
117
+ throw err;
118
+ return render({ consent: opts.cloned ? true : undefined, langs });
119
+ }
120
+ }
121
+ voiceTracks(recordingId, lang) {
122
+ return call(() => this.sdk.recordings.voice(recordingId, lang));
123
+ }
124
+ /** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
125
+ async audioURL(recordingId, opts) {
126
+ const format = opts.format ?? 'mp3';
127
+ if (opts.kind === 'delivery')
128
+ return call(() => this.sdk.recordings.audioUrl(recordingId, { format, kind: 'delivery' }));
129
+ // A reading in a named voice: a short-lived media token carries the voice in the address.
130
+ const { token } = await call(() => this.sdk.recordings.mediaToken(recordingId));
131
+ return this.sdk.recordings.audioSrc(recordingId, { format, kind: 'voice', lang: opts.lang, media: token, voice: opts.voice });
132
+ }
133
+ /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
134
+ clip(recordingId, startS, endS) {
135
+ return call(() => this.sdk.recordings.clip(recordingId, startS, endS));
136
+ }
137
+ voice(id) {
138
+ return call(() => this.sdk.voices.get(id));
139
+ }
140
+ /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
141
+ createVoice(sample, fileName, meta, idempotencyKey) {
142
+ return call(() => this.sdk.voices.create({ ...meta, fileName, sample }, { idempotencyKey }));
143
+ }
144
+ /**
145
+ * Clone a speaker's voice from stretches of a transcribed recording (5–60 s in all). `draft`
146
+ * makes a trial voice to hear first; keep it with `keepVoice`, or delete it.
147
+ */
148
+ voiceFromSpeaker(opts, idempotencyKey) {
149
+ return call(() => this.sdk.voices.createFromSpeaker({ ...opts, consent: true, library: false }, { idempotencyKey }));
150
+ }
151
+ /** Keep a trial voice, as `name`, with the speaker's permission. */
152
+ keepVoice(id, name) {
153
+ return call(() => this.sdk.voices.update(id, { consent: true, draft: false, name }));
154
+ }
155
+ deleteVoice(id) {
156
+ return call(() => this.sdk.voices.delete(id));
157
+ }
158
+ availableVoices(lang, recordingId) {
159
+ return call(() => this.sdk.voices.available(lang, { recording: recordingId }));
160
+ }
161
+ /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
162
+ voicePreview(id, lang, format = 'ogg') {
163
+ return call(() => this.sdk.voices.clonePreview(id, { format, lang }));
60
164
  }
61
165
  }
62
166
  /** A short label for the connected account, from whatever `/v1/me` carries. */
@@ -0,0 +1,7 @@
1
+ type Props = {
2
+ field?: string;
3
+ path?: string;
4
+ };
5
+ /** Translations of the transcript, and readings of them aloud: under the transcript once it is done. */
6
+ export declare const SpeechField: React.FC<Props>;
7
+ export {};