@vocalstack/payload 0.2.0 → 0.5.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 +42 -13
- package/dist/api.d.ts +52 -27
- package/dist/api.js +108 -97
- package/dist/components/SpeechField.js +88 -53
- package/dist/components/VoiceField.js +31 -58
- package/dist/components/VoiceSamples.d.ts +21 -0
- package/dist/components/VoiceSamples.js +341 -0
- package/dist/endpoints/speech.d.ts +22 -7
- package/dist/endpoints/speech.js +523 -121
- package/dist/endpoints/voices.d.ts +8 -3
- package/dist/endpoints/voices.js +152 -16
- package/dist/index.d.ts +1 -3
- package/dist/index.js +20 -3
- package/dist/languages.d.ts +17 -0
- package/dist/languages.js +64 -0
- package/dist/languagesSnapshot.d.ts +2 -0
- package/dist/languagesSnapshot.js +112 -0
- package/dist/types.d.ts +75 -9
- package/package.json +6 -2
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
|
|
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
|
|
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, cast, readIn, 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,8 @@ 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
|
-
| `
|
|
61
|
+
| `listeners` | off | `true`, or `{ languages?, speak?, access?, perHour? }`: let visitors ask for a transcript in their language; see below. |
|
|
62
|
+
| `voiceMode` | the transcript's toggle | `({ collection, doc, req, row }) => 'synthetic' \| 'cloned' \| undefined`: the site decides how transcripts are read aloud, and the toggle is hidden. See below. |
|
|
59
63
|
|
|
60
64
|
### Audio that isn't an upload
|
|
61
65
|
|
|
@@ -79,7 +83,7 @@ Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?fi
|
|
|
79
83
|
### Voices
|
|
80
84
|
|
|
81
85
|
```ts
|
|
82
|
-
import {
|
|
86
|
+
import { vocalstackPlugin } from '@vocalstack/payload'
|
|
83
87
|
|
|
84
88
|
vocalstackPlugin({
|
|
85
89
|
voices: [
|
|
@@ -92,26 +96,47 @@ vocalstackPlugin({
|
|
|
92
96
|
},
|
|
93
97
|
},
|
|
94
98
|
],
|
|
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
99
|
})
|
|
101
100
|
```
|
|
102
101
|
|
|
103
102
|
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
103
|
|
|
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.
|
|
104
|
+
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. Voices are kept as library voices: when VocalStack transcribes a new recording, it checks the speakers against them first.
|
|
105
|
+
|
|
106
|
+
A cloned voice only ever reads words its own speaker said. With `cloned` (from the toggle, or from `voiceMode` once a person has a voice), each speaker VocalStack has matched to a clone is read in it: the speaker it was made from, or one VocalStack recognised as the same person when it transcribed the recording. Everyone else is read in a stock voice. VocalStack doesn't always recognise a speaker, and recordings transcribed before the voice existed are not matched, so a reading reports what it got as `speech[lang].readIn`: `cloned`, `synthetic`, or `mixed`.
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
voiceMode: async ({ doc, req }) => {
|
|
110
|
+
const speaker = await req.payload.findByID({ collection: 'speakers', id: doc.speaker, depth: 0, req })
|
|
111
|
+
return speaker.vocalstackVoice?.state === 'ready' ? 'cloned' : 'synthetic'
|
|
112
|
+
}
|
|
113
|
+
```
|
|
106
114
|
|
|
107
115
|
### Translations and readings
|
|
108
116
|
|
|
109
|
-
Translating an hour-long transcript takes a few minutes
|
|
117
|
+
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
118
|
|
|
111
119
|
**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
120
|
|
|
113
121
|
**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
122
|
|
|
123
|
+
### Languages for listeners
|
|
124
|
+
|
|
125
|
+
With `listeners: true`, anyone who may read a document can ask for its transcript in another language, from your own site:
|
|
126
|
+
|
|
127
|
+
```ts
|
|
128
|
+
// What can be asked for: { languages: [{ code, name, native, translation, voice }], translation, voice }
|
|
129
|
+
await fetch('/api/vocalstack/languages')
|
|
130
|
+
// Ask (on an array row add ?field=&row= as for transcribing). Asked already: answers where it stands.
|
|
131
|
+
await fetch(`/api/sermons/${id}/vocalstack/listen`, { method: 'POST', body: JSON.stringify({ lang: 'pl' }) })
|
|
132
|
+
// Follow it: { state: 'translating' | 'ready' | 'failed' | 'none', done, total, voice, speech: { state, audio }, version }
|
|
133
|
+
await fetch(`/api/sermons/${id}/vocalstack/listen?lang=pl`)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
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.
|
|
137
|
+
|
|
138
|
+
**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.
|
|
139
|
+
|
|
115
140
|
When VocalStack does not answer (an outage, an upgrade), the endpoints say *VocalStack is unavailable, try again shortly.* instead of waiting.
|
|
116
141
|
|
|
117
142
|
**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 +165,7 @@ tab: "Connected", BroadcastChannel('vocalstack') ─▶ admin refreshes; tab clo
|
|
|
140
165
|
```
|
|
141
166
|
|
|
142
167
|
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.
|
|
168
|
+
|
|
169
|
+
## Releasing
|
|
170
|
+
|
|
171
|
+
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
|
|
3
|
-
*
|
|
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;
|
|
@@ -67,7 +72,7 @@ export type VoiceOption = {
|
|
|
67
72
|
quality: number;
|
|
68
73
|
ready?: boolean;
|
|
69
74
|
};
|
|
70
|
-
/** A recording's spoken translation in one language
|
|
75
|
+
/** A recording's spoken translation in one language, in one cast of voices. */
|
|
71
76
|
export type VoiceTrack = {
|
|
72
77
|
/** Seconds each sentence's clip lasts, by sentence id. */
|
|
73
78
|
clipDur?: Record<string, number>;
|
|
@@ -77,19 +82,28 @@ 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
|
+
/** The voice it was asked in by name, if it was. */
|
|
80
86
|
voice?: null | string;
|
|
87
|
+
/** The track's key: `''` for the default voice on older tracks, else its cast (`cast:0=M1;1=F1`). */
|
|
81
88
|
voiceKey: string;
|
|
89
|
+
/** What it is read in: `cloned`, `synthetic`, or `mixed` (some speakers had no usable clone). Null on older tracks. */
|
|
90
|
+
voices?: 'cloned' | 'mixed' | 'synthetic' | null;
|
|
82
91
|
/** Each sentence's words as [start, end] within its clip, by sentence id. */
|
|
83
92
|
wordTimes?: Record<string, [number, number][]>;
|
|
84
93
|
};
|
|
94
|
+
/** How a reading is voiced: in the speakers' cloned voices where VocalStack has them, or in stock voices. */
|
|
95
|
+
export type SpeakAs = {
|
|
96
|
+
cloned: boolean;
|
|
97
|
+
};
|
|
98
|
+
export type Language = {
|
|
99
|
+
code: string;
|
|
100
|
+
name: string;
|
|
101
|
+
native: string;
|
|
102
|
+
translation: boolean;
|
|
103
|
+
voice: boolean;
|
|
104
|
+
};
|
|
85
105
|
export type Languages = {
|
|
86
|
-
languages:
|
|
87
|
-
code: string;
|
|
88
|
-
name: string;
|
|
89
|
-
native: string;
|
|
90
|
-
translation: boolean;
|
|
91
|
-
voice: boolean;
|
|
92
|
-
}[];
|
|
106
|
+
languages: Language[];
|
|
93
107
|
translation: string[];
|
|
94
108
|
voice: string[];
|
|
95
109
|
};
|
|
@@ -100,20 +114,9 @@ export declare class VocalStackAPIError extends Error {
|
|
|
100
114
|
constructor(status: number, code: string, message: string);
|
|
101
115
|
}
|
|
102
116
|
export declare class VocalStackAPI {
|
|
103
|
-
private
|
|
104
|
-
|
|
117
|
+
#private;
|
|
118
|
+
readonly sdk: VocalStack;
|
|
105
119
|
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
120
|
me(): Promise<Record<string, unknown>>;
|
|
118
121
|
transcribeURL(url: string, opts: {
|
|
119
122
|
idempotencyKey: string;
|
|
@@ -140,10 +143,16 @@ export declare class VocalStackAPI {
|
|
|
140
143
|
lang: string;
|
|
141
144
|
translations: Record<string, string>;
|
|
142
145
|
}>;
|
|
143
|
-
/**
|
|
144
|
-
|
|
146
|
+
/**
|
|
147
|
+
* Read translations aloud, one job per language. `cloned` reads each speaker in their own cloned
|
|
148
|
+
* voice where VocalStack can use one (a clone of that speaker, made with their permission, or a
|
|
149
|
+
* saved voice VocalStack recognised as them) and in a stock voice otherwise; `synthetic` reads
|
|
150
|
+
* everyone in stock voices. Each track says which it got (`voices`: cloned, synthetic or mixed).
|
|
151
|
+
* A clone only ever reads words its own speaker said.
|
|
152
|
+
*/
|
|
153
|
+
speak(recordingId: string, langs: string[], as?: SpeakAs): Promise<VoiceTrack[]>;
|
|
145
154
|
voiceTracks(recordingId: string, lang?: string): Promise<VoiceTrack[]>;
|
|
146
|
-
/**
|
|
155
|
+
/** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
|
|
147
156
|
audioURL(recordingId: string, opts: {
|
|
148
157
|
format?: 'caf' | 'mp3' | 'ogg';
|
|
149
158
|
kind: 'delivery' | 'voice';
|
|
@@ -158,6 +167,23 @@ export declare class VocalStackAPI {
|
|
|
158
167
|
consent: boolean;
|
|
159
168
|
name: string;
|
|
160
169
|
}, idempotencyKey: string): Promise<Voice>;
|
|
170
|
+
/**
|
|
171
|
+
* Clone a speaker's voice from stretches of a transcribed recording (5–60 s in all). `draft`
|
|
172
|
+
* makes a trial voice to hear first; keep it with `keepVoice`, or delete it. A library voice:
|
|
173
|
+
* VocalStack looks for library voices first when it works out who speaks in a new recording.
|
|
174
|
+
*/
|
|
175
|
+
voiceFromSpeaker(opts: {
|
|
176
|
+
draft: boolean;
|
|
177
|
+
name: string;
|
|
178
|
+
recordingId: string;
|
|
179
|
+
spans: {
|
|
180
|
+
end: number;
|
|
181
|
+
start: number;
|
|
182
|
+
}[];
|
|
183
|
+
speaker: number;
|
|
184
|
+
}, idempotencyKey: string): Promise<Voice>;
|
|
185
|
+
/** Keep a trial voice, as `name`, with the speaker's permission, in the library. */
|
|
186
|
+
keepVoice(id: string, name: string): Promise<Voice>;
|
|
161
187
|
deleteVoice(id: string): Promise<unknown>;
|
|
162
188
|
availableVoices(lang: string, recordingId?: string): Promise<{
|
|
163
189
|
lang: string;
|
|
@@ -165,7 +191,6 @@ export declare class VocalStackAPI {
|
|
|
165
191
|
}>;
|
|
166
192
|
/** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
|
|
167
193
|
voicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
|
|
168
|
-
private raise;
|
|
169
194
|
}
|
|
170
195
|
/** A short label for the connected account, from whatever `/v1/me` carries. */
|
|
171
196
|
export declare function accountLabel(me: Record<string, unknown>): string | undefined;
|
package/dist/api.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The
|
|
3
|
-
*
|
|
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,79 @@ 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
|
-
|
|
19
|
-
|
|
54
|
+
sdk;
|
|
55
|
+
#apiKey;
|
|
56
|
+
#baseURL;
|
|
20
57
|
constructor(apiKey, baseURL = DEFAULT_API_URL) {
|
|
21
|
-
this
|
|
22
|
-
this
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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;
|
|
58
|
+
this.#apiKey = apiKey;
|
|
59
|
+
this.#baseURL = baseURL.replace(/\/+$/, '');
|
|
60
|
+
this.sdk = new VocalStack({
|
|
61
|
+
apiKey,
|
|
62
|
+
baseUrl: baseURL,
|
|
63
|
+
// One retry of a busy or restarting API; the admin and listeners ask again anyway.
|
|
64
|
+
maxRetries: 1,
|
|
65
|
+
fetch: (input, init) => fetch(input, { ...init, signal: init?.signal ?? AbortSignal.timeout(timeoutFor(String(input instanceof Request ? input.url : input), init?.method)) }),
|
|
66
|
+
});
|
|
61
67
|
}
|
|
62
68
|
me() {
|
|
63
|
-
return this.
|
|
69
|
+
return call(() => this.sdk.me.get());
|
|
64
70
|
}
|
|
65
71
|
transcribeURL(url, opts) {
|
|
66
|
-
return this.
|
|
72
|
+
return call(() => this.sdk.transcriptions.create({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined, url }, { idempotencyKey: opts.idempotencyKey }));
|
|
67
73
|
}
|
|
68
74
|
transcribeFile(file, fileName, opts) {
|
|
69
|
-
|
|
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 });
|
|
75
|
+
return call(() => this.sdk.transcriptions.create({ file, fileName, name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }, { idempotencyKey: opts.idempotencyKey }));
|
|
73
76
|
}
|
|
74
77
|
job(recordingId) {
|
|
75
|
-
return this.
|
|
78
|
+
return call(() => this.sdk.jobs.get(recordingId));
|
|
76
79
|
}
|
|
77
80
|
/** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
|
|
78
81
|
stop(recordingId, reason) {
|
|
79
|
-
return this.
|
|
82
|
+
return call(() => this.sdk.recordings.stop(recordingId, reason));
|
|
80
83
|
}
|
|
81
84
|
transcript(recordingId) {
|
|
82
|
-
return this.
|
|
85
|
+
return call(() => this.sdk.recordings.transcript(recordingId));
|
|
83
86
|
}
|
|
84
87
|
/**
|
|
85
88
|
* The translations VocalStack already holds for `lang`, by sentence id. `/translation`
|
|
86
89
|
* answers only the sentences it translates in that call, so stored ones are read here.
|
|
87
90
|
*/
|
|
88
91
|
async storedTranslations(recordingId, lang) {
|
|
89
|
-
const t = await this.
|
|
92
|
+
const t = (await call(() => this.sdk.recordings.transcript(recordingId, { lang })));
|
|
90
93
|
const out = {};
|
|
91
94
|
for (const s of t.sentences ?? []) {
|
|
92
95
|
const text = s.translations?.[lang];
|
|
@@ -96,71 +99,79 @@ export class VocalStackAPI {
|
|
|
96
99
|
return out;
|
|
97
100
|
}
|
|
98
101
|
languages() {
|
|
99
|
-
return this.
|
|
102
|
+
return call(() => this.sdk.languages.list());
|
|
100
103
|
}
|
|
101
104
|
/** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
|
|
102
105
|
translation(recordingId, lang, sentenceIds) {
|
|
103
|
-
|
|
104
|
-
return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/translation?${q}`, undefined, {}, 180_000);
|
|
106
|
+
return call(() => this.sdk.recordings.translation(recordingId, lang, sentenceIds));
|
|
105
107
|
}
|
|
106
|
-
/**
|
|
107
|
-
|
|
108
|
-
|
|
108
|
+
/**
|
|
109
|
+
* Read translations aloud, one job per language. `cloned` reads each speaker in their own cloned
|
|
110
|
+
* voice where VocalStack can use one (a clone of that speaker, made with their permission, or a
|
|
111
|
+
* saved voice VocalStack recognised as them) and in a stock voice otherwise; `synthetic` reads
|
|
112
|
+
* everyone in stock voices. Each track says which it got (`voices`: cloned, synthetic or mixed).
|
|
113
|
+
* A clone only ever reads words its own speaker said.
|
|
114
|
+
*/
|
|
115
|
+
async speak(recordingId, langs, as = { cloned: false }) {
|
|
116
|
+
const ask = { langs, voices: as.cloned ? 'cloned' : 'synthetic' };
|
|
117
|
+
// Straight to the API: the SDK on npm (2.0.0-alpha.1) leaves `voices` out of the body.
|
|
118
|
+
const res = await call(() => fetch(`${this.#baseURL}/v1/recordings/${encodeURIComponent(recordingId)}/voice`, {
|
|
119
|
+
body: JSON.stringify(ask),
|
|
120
|
+
headers: { authorization: `Bearer ${this.#apiKey}`, 'content-type': 'application/json' },
|
|
121
|
+
method: 'POST',
|
|
122
|
+
signal: AbortSignal.timeout(30_000),
|
|
123
|
+
}));
|
|
124
|
+
const body = (await res.json().catch(() => null));
|
|
125
|
+
if (res.ok)
|
|
126
|
+
return body;
|
|
127
|
+
if (res.status === 502 || res.status === 503 || res.status === 504)
|
|
128
|
+
throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
|
|
129
|
+
throw new VocalStackAPIError(res.status, body?.code ?? 'http_error', body?.message ?? `VocalStack answered ${res.status}`);
|
|
109
130
|
}
|
|
110
131
|
voiceTracks(recordingId, lang) {
|
|
111
|
-
return this.
|
|
132
|
+
return call(() => this.sdk.recordings.voice(recordingId, lang));
|
|
112
133
|
}
|
|
113
|
-
/**
|
|
134
|
+
/** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
|
|
114
135
|
async audioURL(recordingId, opts) {
|
|
115
|
-
const
|
|
116
|
-
if (opts.
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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}`);
|
|
136
|
+
const format = opts.format ?? 'mp3';
|
|
137
|
+
if (opts.kind === 'delivery')
|
|
138
|
+
return call(() => this.sdk.recordings.audioUrl(recordingId, { format, kind: 'delivery' }));
|
|
139
|
+
// A reading in a named voice: a short-lived media token carries the voice in the address.
|
|
140
|
+
const { token } = await call(() => this.sdk.recordings.mediaToken(recordingId));
|
|
141
|
+
return this.sdk.recordings.audioSrc(recordingId, { format, kind: 'voice', lang: opts.lang, media: token, voice: opts.voice });
|
|
126
142
|
}
|
|
127
143
|
/** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if (!res.ok)
|
|
131
|
-
await this.raise(res);
|
|
132
|
-
return res;
|
|
144
|
+
clip(recordingId, startS, endS) {
|
|
145
|
+
return call(() => this.sdk.recordings.clip(recordingId, startS, endS));
|
|
133
146
|
}
|
|
134
147
|
voice(id) {
|
|
135
|
-
return this.
|
|
148
|
+
return call(() => this.sdk.voices.get(id));
|
|
136
149
|
}
|
|
137
150
|
/** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
|
|
138
151
|
createVoice(sample, fileName, meta, idempotencyKey) {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
152
|
+
return call(() => this.sdk.voices.create({ ...meta, fileName, sample }, { idempotencyKey }));
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Clone a speaker's voice from stretches of a transcribed recording (5–60 s in all). `draft`
|
|
156
|
+
* makes a trial voice to hear first; keep it with `keepVoice`, or delete it. A library voice:
|
|
157
|
+
* VocalStack looks for library voices first when it works out who speaks in a new recording.
|
|
158
|
+
*/
|
|
159
|
+
voiceFromSpeaker(opts, idempotencyKey) {
|
|
160
|
+
return call(() => this.sdk.voices.createFromSpeaker({ ...opts, consent: true, library: true }, { idempotencyKey }));
|
|
161
|
+
}
|
|
162
|
+
/** Keep a trial voice, as `name`, with the speaker's permission, in the library. */
|
|
163
|
+
keepVoice(id, name) {
|
|
164
|
+
return call(() => this.sdk.voices.update(id, { consent: true, draft: false, library: true, name }));
|
|
143
165
|
}
|
|
144
166
|
deleteVoice(id) {
|
|
145
|
-
return this.
|
|
167
|
+
return call(() => this.sdk.voices.delete(id));
|
|
146
168
|
}
|
|
147
169
|
availableVoices(lang, recordingId) {
|
|
148
|
-
|
|
149
|
-
if (recordingId)
|
|
150
|
-
q.set('recording', recordingId);
|
|
151
|
-
return this.request('GET', `/v1/voices/available?${q}`);
|
|
170
|
+
return call(() => this.sdk.voices.available(lang, { recording: recordingId }));
|
|
152
171
|
}
|
|
153
172
|
/** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
|
|
154
173
|
voicePreview(id, lang, format = 'ogg') {
|
|
155
|
-
|
|
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}`);
|
|
174
|
+
return call(() => this.sdk.voices.clonePreview(id, { format, lang }));
|
|
164
175
|
}
|
|
165
176
|
}
|
|
166
177
|
/** A short label for the connected account, from whatever `/v1/me` carries. */
|