@vocalstack/payload 0.2.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,6 +2,8 @@
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
+ 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
+
5
7
  ## Install
6
8
 
7
9
  ```sh
@@ -33,10 +35,11 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
33
35
  - `sentences`: `[{ start, end, speaker, text }]` in seconds.
34
36
  - `status`, `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
35
37
  - `POST /api/{collection}/:id/vocalstack/transcribe`, `POST …/vocalstack/stop`, `GET …/vocalstack/status` and `GET …/vocalstack/stream` (live progress as Server-Sent Events).
36
- - **Translations and readings**, under every finished transcript: translate it into any of 100 languages, and have the translation read aloud (in a cloned voice, or one of VocalStack's). Saved in the `vocalstack` group as:
37
- - `translations`: `{ [lang]: { translatedAt, sentences } }`, the transcript's sentences (same ids and times) translated.
38
- - `speech`: `{ [lang]: { voice, state, error, durationS, requestedAt, renderedAt, sentences } }`. `state` is `queued`, `running`, `failed` or `sealed`; once sealed, `sentences` are the translation in the reading's own timing, with words, for a read-along player.
39
- - `POST …/vocalstack/translate { langs }` (answers `more: true` when it stopped for time; call again), `DELETE …/vocalstack/translate?lang=`, `POST …/vocalstack/speak { langs, voice? }`, `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.
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.
40
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`.
41
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.
42
45
 
@@ -55,7 +58,7 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
55
58
  | `enabled` | `true` | `false` keeps the schema but removes the button and the endpoints. |
56
59
  | `voices` | none | Collections of people who get a cloned voice; see below. |
57
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. |
58
- | `speechVoice` | VocalStack's default | `({ collection, doc, row, req }) => voice`: the voice a transcript's translations are read in, e.g. its speaker's (`clonedVoiceKey(person.vocalstackVoice)`). |
61
+ | `listeners` | off | `true`, or `{ languages?, speak?, access?, perHour? }`: let visitors ask for a transcript in their language; see below. |
59
62
 
60
63
  ### Audio that isn't an upload
61
64
 
@@ -79,7 +82,7 @@ Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?fi
79
82
  ### Voices
80
83
 
81
84
  ```ts
82
- import { clonedVoiceKey, vocalstackPlugin } from '@vocalstack/payload'
85
+ import { vocalstackPlugin } from '@vocalstack/payload'
83
86
 
84
87
  vocalstackPlugin({
85
88
  voices: [
@@ -92,26 +95,38 @@ vocalstackPlugin({
92
95
  },
93
96
  },
94
97
  ],
95
- // Read each episode's translations in its speaker's voice, once there is one.
96
- speechVoice: async ({ doc, req }) => {
97
- const speaker = await req.payload.findByID({ collection: 'speakers', id: doc.speaker as number, req })
98
- return clonedVoiceKey(speaker.vocalstackVoice)
99
- },
100
98
  })
101
99
  ```
102
100
 
103
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.
104
102
 
105
- 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.
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.
106
104
 
107
105
  ### Translations and readings
108
106
 
109
- Translating an hour-long transcript takes a few minutes; the admin keeps calling until it is done, and what is translated is saved as it goes. 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).
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).
110
108
 
111
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.
112
110
 
113
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`.
114
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
+
115
130
  When VocalStack does not answer (an outage, an upgrade), the endpoints say *VocalStack is unavailable, try again shortly.* instead of waiting.
116
131
 
117
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.
@@ -140,3 +155,7 @@ tab: "Connected", BroadcastChannel('vocalstack') ─▶ admin refreshes; tab clo
140
155
  ```
141
156
 
142
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';
@@ -50,6 +53,8 @@ export type Transcript = {
50
53
  };
51
54
  export type Voice = {
52
55
  createdAt: string;
56
+ /** A trial voice, to hear before it is kept. */
57
+ draft?: boolean;
53
58
  error?: null | string;
54
59
  id: string;
55
60
  name: string;
@@ -77,19 +82,21 @@ export type VoiceTrack = {
77
82
  lang: string;
78
83
  /** `queued`, `running`, `failed`, `sealed` (the track is ready), or `clips` (sentences only). */
79
84
  state: string;
85
+ /** `synthetic` or `cloned` (the API's voice modes); older APIs answer a voice name here, or nothing. */
80
86
  voice?: null | string;
81
87
  voiceKey: string;
82
88
  /** Each sentence's words as [start, end] within its clip, by sentence id. */
83
89
  wordTimes?: Record<string, [number, number][]>;
84
90
  };
91
+ export type Language = {
92
+ code: string;
93
+ name: string;
94
+ native: string;
95
+ translation: boolean;
96
+ voice: boolean;
97
+ };
85
98
  export type Languages = {
86
- languages: {
87
- code: string;
88
- name: string;
89
- native: string;
90
- translation: boolean;
91
- voice: boolean;
92
- }[];
99
+ languages: Language[];
93
100
  translation: string[];
94
101
  voice: string[];
95
102
  };
@@ -100,20 +107,8 @@ export declare class VocalStackAPIError extends Error {
100
107
  constructor(status: number, code: string, message: string);
101
108
  }
102
109
  export declare class VocalStackAPI {
103
- private apiKey;
104
- private baseURL;
110
+ readonly sdk: VocalStack;
105
111
  constructor(apiKey: string, baseURL?: string);
106
- /**
107
- * The raw answer. An engine that is down or does not answer in time (an upgrade, an
108
- * outage) is one error, `unavailable`, so the admin says so instead of hanging.
109
- */
110
- fetch(method: string, path: string, opts?: {
111
- body?: BodyInit | object;
112
- headers?: Record<string, string>;
113
- redirect?: RequestRedirect;
114
- timeoutMs?: number;
115
- }): Promise<Response>;
116
- private request;
117
112
  me(): Promise<Record<string, unknown>>;
118
113
  transcribeURL(url: string, opts: {
119
114
  idempotencyKey: string;
@@ -140,10 +135,16 @@ export declare class VocalStackAPI {
140
135
  lang: string;
141
136
  translations: Record<string, string>;
142
137
  }>;
143
- /** Render spoken translations, one job per language, in `voice` (the default voice when left out). */
144
- speak(recordingId: string, langs: string[], voice?: string): Promise<VoiceTrack[]>;
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[]>;
145
146
  voiceTracks(recordingId: string, lang?: string): Promise<VoiceTrack[]>;
146
- /** A freshly signed address (an hour) of the recording's audio, or of a spoken translation's. */
147
+ /** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
147
148
  audioURL(recordingId: string, opts: {
148
149
  format?: 'caf' | 'mp3' | 'ogg';
149
150
  kind: 'delivery' | 'voice';
@@ -158,6 +159,22 @@ export declare class VocalStackAPI {
158
159
  consent: boolean;
159
160
  name: string;
160
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>;
161
178
  deleteVoice(id: string): Promise<unknown>;
162
179
  availableVoices(lang: string, recordingId?: string): Promise<{
163
180
  lang: string;
@@ -165,7 +182,6 @@ export declare class VocalStackAPI {
165
182
  }>;
166
183
  /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
167
184
  voicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
168
- private raise;
169
185
  }
170
186
  /** A short label for the connected account, from whatever `/v1/me` carries. */
171
187
  export declare function accountLabel(me: Record<string, unknown>): string | undefined;
package/dist/api.js 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, 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';
7
10
  export const UNAVAILABLE = 'VocalStack is unavailable, try again shortly.';
@@ -14,79 +17,75 @@ export class VocalStackAPIError extends Error {
14
17
  this.status = status;
15
18
  }
16
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
+ };
17
53
  export class VocalStackAPI {
18
- apiKey;
19
- baseURL;
54
+ sdk;
20
55
  constructor(apiKey, baseURL = DEFAULT_API_URL) {
21
- this.apiKey = apiKey;
22
- this.baseURL = baseURL;
23
- }
24
- /**
25
- * The raw answer. An engine that is down or does not answer in time (an upgrade, an
26
- * outage) is one error, `unavailable`, so the admin says so instead of hanging.
27
- */
28
- async fetch(method, path, opts = {}) {
29
- const init = {
30
- headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, ...opts.headers },
31
- method,
32
- redirect: opts.redirect,
33
- signal: AbortSignal.timeout(opts.timeoutMs ?? 30_000),
34
- };
35
- if (opts.body instanceof FormData)
36
- init.body = opts.body;
37
- else if (opts.body !== undefined) {
38
- init.body = JSON.stringify(opts.body);
39
- init.headers['content-type'] = 'application/json';
40
- }
41
- let res;
42
- try {
43
- res = await fetch(`${this.baseURL}${path}`, init);
44
- }
45
- catch {
46
- throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
47
- }
48
- if (res.status === 502 || res.status === 504 || (res.status === 503 && !res.headers.get('content-type')?.includes('json'))) {
49
- throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
50
- }
51
- return res;
52
- }
53
- async request(method, path, body, headers = {}, timeoutMs) {
54
- const res = await this.fetch(method, path, { body, headers, timeoutMs });
55
- const data = await res.json().catch(() => undefined);
56
- if (!res.ok) {
57
- const err = (data?.error ?? data);
58
- throw new VocalStackAPIError(res.status, err?.code ?? 'http_error', err?.message ?? `VocalStack answered ${res.status}`);
59
- }
60
- 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
+ });
61
63
  }
62
64
  me() {
63
- return this.request('GET', '/v1/me');
65
+ return call(() => this.sdk.me.get());
64
66
  }
65
67
  transcribeURL(url, opts) {
66
- 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 }));
67
69
  }
68
70
  transcribeFile(file, fileName, opts) {
69
- const form = new FormData();
70
- form.append('options', JSON.stringify({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }));
71
- form.append('file', file, fileName);
72
- 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 }));
73
72
  }
74
73
  job(recordingId) {
75
- return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/job`);
74
+ return call(() => this.sdk.jobs.get(recordingId));
76
75
  }
77
76
  /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
78
77
  stop(recordingId, reason) {
79
- return this.request('POST', `/v1/recordings/${encodeURIComponent(recordingId)}/stop`, { reason: reason ?? null });
78
+ return call(() => this.sdk.recordings.stop(recordingId, reason));
80
79
  }
81
80
  transcript(recordingId) {
82
- return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript`);
81
+ return call(() => this.sdk.recordings.transcript(recordingId));
83
82
  }
84
83
  /**
85
84
  * The translations VocalStack already holds for `lang`, by sentence id. `/translation`
86
85
  * answers only the sentences it translates in that call, so stored ones are read here.
87
86
  */
88
87
  async storedTranslations(recordingId, lang) {
89
- const t = await this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript?lang=${encodeURIComponent(lang)}`);
88
+ const t = (await call(() => this.sdk.recordings.transcript(recordingId, { lang })));
90
89
  const out = {};
91
90
  for (const s of t.sentences ?? []) {
92
91
  const text = s.translations?.[lang];
@@ -96,71 +95,72 @@ export class VocalStackAPI {
96
95
  return out;
97
96
  }
98
97
  languages() {
99
- return this.request('GET', '/v1/languages');
98
+ return call(() => this.sdk.languages.list());
100
99
  }
101
100
  /** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
102
101
  translation(recordingId, lang, sentenceIds) {
103
- const q = new URLSearchParams({ lang, sentences: sentenceIds.join(',') });
104
- return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/translation?${q}`, undefined, {}, 180_000);
102
+ return call(() => this.sdk.recordings.translation(recordingId, lang, sentenceIds));
105
103
  }
106
- /** Render spoken translations, one job per language, in `voice` (the default voice when left out). */
107
- speak(recordingId, langs, voice) {
108
- return this.request('POST', `/v1/recordings/${encodeURIComponent(recordingId)}/voice`, voice ? { langs, voice } : { langs });
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
+ }
109
120
  }
110
121
  voiceTracks(recordingId, lang) {
111
- return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/voice${lang ? `?lang=${encodeURIComponent(lang)}` : ''}`);
122
+ return call(() => this.sdk.recordings.voice(recordingId, lang));
112
123
  }
113
- /** A freshly signed address (an hour) of the recording's audio, or of a spoken translation's. */
124
+ /** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
114
125
  async audioURL(recordingId, opts) {
115
- const q = new URLSearchParams({ format: opts.format ?? 'mp3', kind: opts.kind });
116
- if (opts.lang)
117
- q.set('lang', opts.lang);
118
- if (opts.voice)
119
- q.set('voice', opts.voice);
120
- const res = await this.fetch('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/audio?${q}`, { redirect: 'manual' });
121
- const location = res.headers.get('location');
122
- if (res.status >= 300 && res.status < 400 && location)
123
- return new URL(location, this.baseURL).toString();
124
- const data = (await res.json().catch(() => undefined));
125
- throw new VocalStackAPIError(res.ok ? 502 : res.status, data?.code ?? 'http_error', data?.message ?? `VocalStack answered ${res.status}`);
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 });
126
132
  }
127
133
  /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
128
- async clip(recordingId, startS, endS) {
129
- const res = await this.fetch('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/audio/clip?startS=${startS}&endS=${endS}`, { timeoutMs: 60_000 });
130
- if (!res.ok)
131
- await this.raise(res);
132
- return res;
134
+ clip(recordingId, startS, endS) {
135
+ return call(() => this.sdk.recordings.clip(recordingId, startS, endS));
133
136
  }
134
137
  voice(id) {
135
- return this.request('GET', `/v1/voices/${encodeURIComponent(id)}`);
138
+ return call(() => this.sdk.voices.get(id));
136
139
  }
137
140
  /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
138
141
  createVoice(sample, fileName, meta, idempotencyKey) {
139
- const form = new FormData();
140
- form.append('meta', JSON.stringify(meta));
141
- form.append('sample', sample, fileName);
142
- return this.request('POST', '/v1/voices', form, { 'idempotency-key': idempotencyKey }, 120_000);
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 }));
143
154
  }
144
155
  deleteVoice(id) {
145
- return this.request('DELETE', `/v1/voices/${encodeURIComponent(id)}`);
156
+ return call(() => this.sdk.voices.delete(id));
146
157
  }
147
158
  availableVoices(lang, recordingId) {
148
- const q = new URLSearchParams({ lang });
149
- if (recordingId)
150
- q.set('recording', recordingId);
151
- return this.request('GET', `/v1/voices/available?${q}`);
159
+ return call(() => this.sdk.voices.available(lang, { recording: recordingId }));
152
160
  }
153
161
  /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
154
162
  voicePreview(id, lang, format = 'ogg') {
155
- const q = new URLSearchParams({ format });
156
- if (lang)
157
- q.set('lang', lang);
158
- return this.fetch('GET', `/v1/voices/${encodeURIComponent(id)}/preview?${q}`, { timeoutMs: 60_000 });
159
- }
160
- async raise(res) {
161
- const data = (await res.json().catch(() => undefined));
162
- const err = data?.error ?? data;
163
- throw new VocalStackAPIError(res.status, err?.code ?? 'http_error', err?.message ?? `VocalStack answered ${res.status}`);
163
+ return call(() => this.sdk.voices.clonePreview(id, { format, lang }));
164
164
  }
165
165
  }
166
166
  /** A short label for the connected account, from whatever `/v1/me` carries. */