@vocalstack/payload 0.1.0 → 0.2.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 +48 -4
- package/dist/api.d.ts +93 -0
- package/dist/api.js +111 -7
- package/dist/components/SpeechField.d.ts +7 -0
- package/dist/components/SpeechField.js +177 -0
- package/dist/components/TranscriptField.js +1 -1
- package/dist/components/VoiceField.d.ts +1 -0
- package/dist/components/VoiceField.js +226 -0
- package/dist/endpoints/speech.d.ts +12 -0
- package/dist/endpoints/speech.js +392 -0
- package/dist/endpoints/transcribe.d.ts +10 -2
- package/dist/endpoints/transcribe.js +14 -3
- package/dist/endpoints/voices.d.ts +20 -0
- package/dist/endpoints/voices.js +275 -0
- package/dist/exports/client.d.ts +2 -0
- package/dist/exports/client.js +2 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +76 -5
- package/dist/readings.d.ts +6 -0
- package/dist/readings.js +24 -0
- package/dist/text.d.ts +7 -0
- package/dist/text.js +26 -0
- package/dist/types.d.ts +96 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -4,10 +4,8 @@ VocalStack for [Payload CMS](https://payloadcms.com) 3: a **Transcribe** button
|
|
|
4
4
|
|
|
5
5
|
## Install
|
|
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):
|
|
8
|
-
|
|
9
7
|
```sh
|
|
10
|
-
pnpm add
|
|
8
|
+
pnpm add @vocalstack/payload
|
|
11
9
|
```
|
|
12
10
|
|
|
13
11
|
```ts
|
|
@@ -35,6 +33,11 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
|
|
|
35
33
|
- `sentences`: `[{ start, end, speaker, text }]` in seconds.
|
|
36
34
|
- `status`, `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
|
|
37
35
|
- `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.
|
|
40
|
+
- **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
41
|
- **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
42
|
|
|
40
43
|
## Options
|
|
@@ -46,10 +49,13 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
|
|
|
46
49
|
| `audioFields` | none | Audio that isn't an upload document; see below. |
|
|
47
50
|
| `spokenLanguage` | auto-detect | A Whisper language code (`en`, `ro`, …). |
|
|
48
51
|
| `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. |
|
|
52
|
+
| `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
53
|
| `oneClickConnect` | `false` | Show **Connect VocalStack** (see below). |
|
|
51
54
|
| `apiURL` / `dashboardURL` | `https://api.vocalstack.com` / `https://app.vocalstack.com` | |
|
|
52
55
|
| `enabled` | `true` | `false` keeps the schema but removes the button and the endpoints. |
|
|
56
|
+
| `voices` | none | Collections of people who get a cloned voice; see below. |
|
|
57
|
+
| `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)`). |
|
|
53
59
|
|
|
54
60
|
### Audio that isn't an upload
|
|
55
61
|
|
|
@@ -70,6 +76,44 @@ vocalstackPlugin({
|
|
|
70
76
|
|
|
71
77
|
Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?field=attachments&row=<row id>`. A new row needs saving first.
|
|
72
78
|
|
|
79
|
+
### Voices
|
|
80
|
+
|
|
81
|
+
```ts
|
|
82
|
+
import { clonedVoiceKey, vocalstackPlugin } from '@vocalstack/payload'
|
|
83
|
+
|
|
84
|
+
vocalstackPlugin({
|
|
85
|
+
voices: [
|
|
86
|
+
{
|
|
87
|
+
collection: 'speakers',
|
|
88
|
+
// Recordings this speaker is in, offered as the sample to clone from.
|
|
89
|
+
recordings: async ({ doc, req }) => {
|
|
90
|
+
const { docs } = await req.payload.find({ collection: 'episodes', where: { speaker: { equals: doc.id } }, req })
|
|
91
|
+
return docs.flatMap((e) => (e.vocalstack?.recordingId ? [{ label: e.title, recordingId: e.vocalstack.recordingId, sentences: e.vocalstack.sentences }] : []))
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
],
|
|
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
|
+
})
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
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
|
+
|
|
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.
|
|
106
|
+
|
|
107
|
+
### Translations and readings
|
|
108
|
+
|
|
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).
|
|
110
|
+
|
|
111
|
+
**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
|
+
|
|
113
|
+
**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
|
+
|
|
115
|
+
When VocalStack does not answer (an outage, an upgrade), the endpoints say *VocalStack is unavailable, try again shortly.* instead of waiting.
|
|
116
|
+
|
|
73
117
|
**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
118
|
|
|
75
119
|
## One-click connect (protocol)
|
package/dist/api.d.ts
CHANGED
|
@@ -48,6 +48,52 @@ export type Transcript = {
|
|
|
48
48
|
text: string;
|
|
49
49
|
}[];
|
|
50
50
|
};
|
|
51
|
+
export type Voice = {
|
|
52
|
+
createdAt: string;
|
|
53
|
+
error?: null | string;
|
|
54
|
+
id: string;
|
|
55
|
+
name: string;
|
|
56
|
+
progress: number;
|
|
57
|
+
sampleS: number;
|
|
58
|
+
/** `training`, `ready` or `failed`. */
|
|
59
|
+
state: string;
|
|
60
|
+
};
|
|
61
|
+
export type VoiceOption = {
|
|
62
|
+
cloned: boolean;
|
|
63
|
+
default: boolean;
|
|
64
|
+
gender?: null | string;
|
|
65
|
+
id: string;
|
|
66
|
+
name: string;
|
|
67
|
+
quality: number;
|
|
68
|
+
ready?: boolean;
|
|
69
|
+
};
|
|
70
|
+
/** A recording's spoken translation in one language and voice (`voiceKey` is `''` for the default voice). */
|
|
71
|
+
export type VoiceTrack = {
|
|
72
|
+
/** Seconds each sentence's clip lasts, by sentence id. */
|
|
73
|
+
clipDur?: Record<string, number>;
|
|
74
|
+
clips: number[];
|
|
75
|
+
durationS?: null | number;
|
|
76
|
+
error?: null | string;
|
|
77
|
+
lang: string;
|
|
78
|
+
/** `queued`, `running`, `failed`, `sealed` (the track is ready), or `clips` (sentences only). */
|
|
79
|
+
state: string;
|
|
80
|
+
voice?: null | string;
|
|
81
|
+
voiceKey: string;
|
|
82
|
+
/** Each sentence's words as [start, end] within its clip, by sentence id. */
|
|
83
|
+
wordTimes?: Record<string, [number, number][]>;
|
|
84
|
+
};
|
|
85
|
+
export type Languages = {
|
|
86
|
+
languages: {
|
|
87
|
+
code: string;
|
|
88
|
+
name: string;
|
|
89
|
+
native: string;
|
|
90
|
+
translation: boolean;
|
|
91
|
+
voice: boolean;
|
|
92
|
+
}[];
|
|
93
|
+
translation: string[];
|
|
94
|
+
voice: string[];
|
|
95
|
+
};
|
|
96
|
+
export declare const UNAVAILABLE = "VocalStack is unavailable, try again shortly.";
|
|
51
97
|
export declare class VocalStackAPIError extends Error {
|
|
52
98
|
code: string;
|
|
53
99
|
status: number;
|
|
@@ -57,6 +103,16 @@ export declare class VocalStackAPI {
|
|
|
57
103
|
private apiKey;
|
|
58
104
|
private baseURL;
|
|
59
105
|
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>;
|
|
60
116
|
private request;
|
|
61
117
|
me(): Promise<Record<string, unknown>>;
|
|
62
118
|
transcribeURL(url: string, opts: {
|
|
@@ -73,6 +129,43 @@ export declare class VocalStackAPI {
|
|
|
73
129
|
/** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
|
|
74
130
|
stop(recordingId: string, reason?: string): Promise<unknown>;
|
|
75
131
|
transcript(recordingId: string): Promise<Transcript>;
|
|
132
|
+
/**
|
|
133
|
+
* The translations VocalStack already holds for `lang`, by sentence id. `/translation`
|
|
134
|
+
* answers only the sentences it translates in that call, so stored ones are read here.
|
|
135
|
+
*/
|
|
136
|
+
storedTranslations(recordingId: string, lang: string): Promise<Record<string, string>>;
|
|
137
|
+
languages(): Promise<Languages>;
|
|
138
|
+
/** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
|
|
139
|
+
translation(recordingId: string, lang: string, sentenceIds: number[]): Promise<{
|
|
140
|
+
lang: string;
|
|
141
|
+
translations: Record<string, string>;
|
|
142
|
+
}>;
|
|
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[]>;
|
|
145
|
+
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
|
+
audioURL(recordingId: string, opts: {
|
|
148
|
+
format?: 'caf' | 'mp3' | 'ogg';
|
|
149
|
+
kind: 'delivery' | 'voice';
|
|
150
|
+
lang?: string;
|
|
151
|
+
voice?: string;
|
|
152
|
+
}): Promise<string>;
|
|
153
|
+
/** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
|
|
154
|
+
clip(recordingId: string, startS: number, endS: number): Promise<Response>;
|
|
155
|
+
voice(id: string): Promise<Voice>;
|
|
156
|
+
/** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
|
|
157
|
+
createVoice(sample: Blob, fileName: string, meta: {
|
|
158
|
+
consent: boolean;
|
|
159
|
+
name: string;
|
|
160
|
+
}, idempotencyKey: string): Promise<Voice>;
|
|
161
|
+
deleteVoice(id: string): Promise<unknown>;
|
|
162
|
+
availableVoices(lang: string, recordingId?: string): Promise<{
|
|
163
|
+
lang: string;
|
|
164
|
+
voices: VoiceOption[];
|
|
165
|
+
}>;
|
|
166
|
+
/** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
|
|
167
|
+
voicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
|
|
168
|
+
private raise;
|
|
76
169
|
}
|
|
77
170
|
/** A short label for the connected account, from whatever `/v1/me` carries. */
|
|
78
171
|
export declare function accountLabel(me: Record<string, unknown>): string | undefined;
|
package/dist/api.js
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
export const DEFAULT_API_URL = 'https://api.vocalstack.com';
|
|
6
6
|
export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
|
|
7
|
+
export const UNAVAILABLE = 'VocalStack is unavailable, try again shortly.';
|
|
7
8
|
export class VocalStackAPIError extends Error {
|
|
8
9
|
code;
|
|
9
10
|
status;
|
|
@@ -20,15 +21,37 @@ export class VocalStackAPI {
|
|
|
20
21
|
this.apiKey = apiKey;
|
|
21
22
|
this.baseURL = baseURL;
|
|
22
23
|
}
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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);
|
|
29
39
|
init.headers['content-type'] = 'application/json';
|
|
30
40
|
}
|
|
31
|
-
|
|
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 });
|
|
32
55
|
const data = await res.json().catch(() => undefined);
|
|
33
56
|
if (!res.ok) {
|
|
34
57
|
const err = (data?.error ?? data);
|
|
@@ -58,6 +81,87 @@ export class VocalStackAPI {
|
|
|
58
81
|
transcript(recordingId) {
|
|
59
82
|
return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript`);
|
|
60
83
|
}
|
|
84
|
+
/**
|
|
85
|
+
* The translations VocalStack already holds for `lang`, by sentence id. `/translation`
|
|
86
|
+
* answers only the sentences it translates in that call, so stored ones are read here.
|
|
87
|
+
*/
|
|
88
|
+
async storedTranslations(recordingId, lang) {
|
|
89
|
+
const t = await this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript?lang=${encodeURIComponent(lang)}`);
|
|
90
|
+
const out = {};
|
|
91
|
+
for (const s of t.sentences ?? []) {
|
|
92
|
+
const text = s.translations?.[lang];
|
|
93
|
+
if (text?.trim())
|
|
94
|
+
out[String(s.sentenceId)] = text;
|
|
95
|
+
}
|
|
96
|
+
return out;
|
|
97
|
+
}
|
|
98
|
+
languages() {
|
|
99
|
+
return this.request('GET', '/v1/languages');
|
|
100
|
+
}
|
|
101
|
+
/** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
|
|
102
|
+
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);
|
|
105
|
+
}
|
|
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 });
|
|
109
|
+
}
|
|
110
|
+
voiceTracks(recordingId, lang) {
|
|
111
|
+
return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/voice${lang ? `?lang=${encodeURIComponent(lang)}` : ''}`);
|
|
112
|
+
}
|
|
113
|
+
/** A freshly signed address (an hour) of the recording's audio, or of a spoken translation's. */
|
|
114
|
+
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
|
+
}
|
|
127
|
+
/** 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;
|
|
133
|
+
}
|
|
134
|
+
voice(id) {
|
|
135
|
+
return this.request('GET', `/v1/voices/${encodeURIComponent(id)}`);
|
|
136
|
+
}
|
|
137
|
+
/** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
|
|
138
|
+
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);
|
|
143
|
+
}
|
|
144
|
+
deleteVoice(id) {
|
|
145
|
+
return this.request('DELETE', `/v1/voices/${encodeURIComponent(id)}`);
|
|
146
|
+
}
|
|
147
|
+
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}`);
|
|
152
|
+
}
|
|
153
|
+
/** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
|
|
154
|
+
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}`);
|
|
164
|
+
}
|
|
61
165
|
}
|
|
62
166
|
/** A short label for the connected account, from whatever `/v1/me` carries. */
|
|
63
167
|
export function accountLabel(me) {
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
+
import { Button, toast, useConfig, useDocumentInfo, useForm, useFormFields } from '@payloadcms/ui';
|
|
4
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
5
|
+
import { BrandStyles } from './Brand.js';
|
|
6
|
+
import { useAPI } from './useConnection.js';
|
|
7
|
+
const POLL_MS = 5000;
|
|
8
|
+
const styles = `
|
|
9
|
+
.vs-speech { border: 1px solid var(--theme-elevation-150); border-radius: var(--style-radius-s, 4px); padding: 12px 16px; margin-top: 12px; }
|
|
10
|
+
.vs-speech h4 { margin: 0 0 8px; font-size: 14px; }
|
|
11
|
+
.vs-speech-row { display: grid; grid-template-columns: minmax(110px, 1fr) minmax(0, 2.4fr) auto; gap: 10px; align-items: center; padding: 8px 0;
|
|
12
|
+
border-top: 1px solid var(--theme-elevation-100); font-size: 13px; }
|
|
13
|
+
.vs-speech-row:first-of-type { border-top: 0; }
|
|
14
|
+
.vs-speech-muted { color: var(--theme-elevation-500); font-size: 13px; margin: 0; }
|
|
15
|
+
.vs-speech-error { color: var(--theme-error-500); font-size: 13px; margin: 0; }
|
|
16
|
+
.vs-speech select, .vs-speech input[type=search] { font: inherit; font-size: 13px; padding: 4px 6px; border: 1px solid var(--theme-elevation-150);
|
|
17
|
+
border-radius: var(--style-radius-s, 4px); background: var(--theme-input-bg, var(--theme-elevation-0)); color: var(--theme-text); max-width: 100%; }
|
|
18
|
+
.vs-speech audio { height: 32px; width: 100%; }
|
|
19
|
+
.vs-speech-langs { columns: 3 160px; max-height: 200px; overflow-y: auto; margin: 8px 0; font-size: 13px; }
|
|
20
|
+
.vs-speech-langs label { display: flex; gap: 6px; align-items: center; break-inside: avoid; padding: 2px 0; }
|
|
21
|
+
.vs-spin { display: inline-block; width: 10px; height: 10px; border: 2px solid var(--theme-elevation-200); border-top-color: var(--vs-accent);
|
|
22
|
+
border-radius: 50%; animation: vs-spin .8s linear infinite; margin-right: 6px; vertical-align: -1px; }
|
|
23
|
+
@keyframes vs-spin { to { transform: rotate(360deg); } }
|
|
24
|
+
`;
|
|
25
|
+
/** Translations of the transcript, and readings of them aloud: under the transcript once it is done. */
|
|
26
|
+
export const SpeechField = ({ field, path = '' }) => {
|
|
27
|
+
const { id, collectionSlug } = useDocumentInfo();
|
|
28
|
+
const { config: { routes: { api }, serverURL, }, } = useConfig();
|
|
29
|
+
const call = useAPI();
|
|
30
|
+
const { dispatchFields } = useForm();
|
|
31
|
+
// `attachments.3.vocalstack.vocalstackSpeech` → the group, and the row it is in.
|
|
32
|
+
const group = path.replace(/vocalstackSpeech$/, '');
|
|
33
|
+
const rowPrefix = group.replace(/vocalstack\.$/, '');
|
|
34
|
+
const rowId = useFormFields(([fields]) => (field ? fields[`${rowPrefix}id`]?.value : undefined));
|
|
35
|
+
const query = field ? `?${new URLSearchParams({ field, row: rowId ?? '' })}` : '';
|
|
36
|
+
const withQuery = (extra) => `?${new URLSearchParams({ ...(field ? { field, row: rowId ?? '' } : {}), ...extra })}`;
|
|
37
|
+
const translations = (useFormFields(([fields]) => fields[`${group}translations`]?.value) ?? {});
|
|
38
|
+
const speech = (useFormFields(([fields]) => fields[`${group}speech`]?.value) ?? {});
|
|
39
|
+
const spoken = useFormFields(([fields]) => fields[`${group}language`]?.value);
|
|
40
|
+
const recordingId = useFormFields(([fields]) => fields[`${group}recordingId`]?.value);
|
|
41
|
+
const [langs, setLangs] = useState();
|
|
42
|
+
const [defaultVoice, setDefaultVoice] = useState(null);
|
|
43
|
+
const [voices, setVoices] = useState({});
|
|
44
|
+
const [picked, setPicked] = useState({});
|
|
45
|
+
const [working, setWorking] = useState({});
|
|
46
|
+
const [error, setError] = useState();
|
|
47
|
+
const timer = useRef(undefined);
|
|
48
|
+
const base = `/${collectionSlug}/${id}/vocalstack`;
|
|
49
|
+
// The server saved these; make them the form's saved state too, so Save keeps them.
|
|
50
|
+
const apply = useCallback((data) => {
|
|
51
|
+
for (const key of ['translations', 'speech']) {
|
|
52
|
+
if (data && key in data)
|
|
53
|
+
dispatchFields({ type: 'UPDATE', initialValue: data[key], path: `${group}${key}`, value: data[key] });
|
|
54
|
+
}
|
|
55
|
+
}, [dispatchFields, group]);
|
|
56
|
+
const busySpeech = Object.values(speech).some((s) => s.state === 'queued' || s.state === 'running');
|
|
57
|
+
const check = useCallback(async () => {
|
|
58
|
+
clearTimeout(timer.current);
|
|
59
|
+
try {
|
|
60
|
+
const res = await call(`${base}/speak${query}`);
|
|
61
|
+
setDefaultVoice(res.defaultVoice ?? null);
|
|
62
|
+
apply(res.vocalstack);
|
|
63
|
+
const before = speech;
|
|
64
|
+
for (const [lang, s] of Object.entries(res.vocalstack.speech ?? {})) {
|
|
65
|
+
if (s.state === 'sealed' && before[lang]?.state !== 'sealed')
|
|
66
|
+
toast.success(`The ${lang.toUpperCase()} reading is ready.`);
|
|
67
|
+
}
|
|
68
|
+
setError(undefined);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
setError(err.message);
|
|
72
|
+
}
|
|
73
|
+
}, [apply, base, call, query, speech]);
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
if (!id)
|
|
76
|
+
return;
|
|
77
|
+
call('/vocalstack/languages').then(setLangs, (err) => setError(err.message));
|
|
78
|
+
void check();
|
|
79
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
80
|
+
}, [id, rowId]);
|
|
81
|
+
// Poll while a reading is being made.
|
|
82
|
+
useEffect(() => {
|
|
83
|
+
if (busySpeech)
|
|
84
|
+
timer.current = setTimeout(check, POLL_MS);
|
|
85
|
+
return () => clearTimeout(timer.current);
|
|
86
|
+
}, [busySpeech, check, speech]);
|
|
87
|
+
const loadVoices = useCallback((lang) => {
|
|
88
|
+
if (voices[lang])
|
|
89
|
+
return;
|
|
90
|
+
setVoices((v) => ({ ...v, [lang]: [] }));
|
|
91
|
+
call(`/vocalstack/voices?${new URLSearchParams({ lang, ...(recordingId ? { recording: recordingId } : {}) })}`).then((r) => setVoices((v) => ({ ...v, [lang]: r.voices })), () => undefined);
|
|
92
|
+
}, [call, recordingId, voices]);
|
|
93
|
+
const names = useMemo(() => new Map(langs?.languages.map((l) => [l.code, l.name])), [langs]);
|
|
94
|
+
const canSpeak = useMemo(() => new Set(langs?.voice), [langs]);
|
|
95
|
+
const shown = [...new Set([...Object.keys(translations), ...Object.keys(speech)])].sort((a, b) => (names.get(a) ?? a).localeCompare(names.get(b) ?? b));
|
|
96
|
+
const speakable = shown.filter((l) => canSpeak.has(l)).join();
|
|
97
|
+
useEffect(() => {
|
|
98
|
+
for (const l of speakable.split(','))
|
|
99
|
+
if (l)
|
|
100
|
+
loadVoices(l);
|
|
101
|
+
}, [loadVoices, speakable]);
|
|
102
|
+
/** Translate until done (each call stops after a while and says whether there is more). */
|
|
103
|
+
const translate = async (list) => {
|
|
104
|
+
if (!list.length)
|
|
105
|
+
return;
|
|
106
|
+
for (;;) {
|
|
107
|
+
const res = await call(`${base}/translate${query}`, { body: JSON.stringify({ langs: list }), method: 'POST' });
|
|
108
|
+
apply(res.vocalstack);
|
|
109
|
+
if (!res.more)
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const run = async (list, label, job) => {
|
|
114
|
+
if (!list.length)
|
|
115
|
+
return;
|
|
116
|
+
setError(undefined);
|
|
117
|
+
setWorking((w) => ({ ...w, ...Object.fromEntries(list.map((l) => [l, label])) }));
|
|
118
|
+
try {
|
|
119
|
+
await job();
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
setError(err.message);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
setWorking((w) => Object.fromEntries(Object.entries(w).filter(([l]) => !list.includes(l))));
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
const speak = (list, voice) => run(list, 'Translating…', async () => {
|
|
129
|
+
await translate(list.filter((l) => !translations[l]));
|
|
130
|
+
const res = await call(`${base}/speak${query}`, { body: JSON.stringify({ langs: list, voice: voice || undefined }), method: 'POST' });
|
|
131
|
+
apply(res.vocalstack);
|
|
132
|
+
setDefaultVoice(res.defaultVoice ?? null);
|
|
133
|
+
});
|
|
134
|
+
const remove = (lang) => window.confirm(`Remove the ${names.get(lang) ?? lang} translation${speech[lang] ? ' and its reading' : ''}?`) &&
|
|
135
|
+
run([lang], 'Removing…', async () => {
|
|
136
|
+
apply((await call(`${base}/translate${withQuery({ lang })}`, { method: 'DELETE' })).vocalstack);
|
|
137
|
+
});
|
|
138
|
+
const voiceName = (lang, key) => {
|
|
139
|
+
if (!key)
|
|
140
|
+
return 'VocalStack’s default voice';
|
|
141
|
+
return voices[lang]?.find((v) => v.id === key)?.name ?? (key.startsWith('clone:') ? 'a cloned voice' : key);
|
|
142
|
+
};
|
|
143
|
+
if (!id)
|
|
144
|
+
return null;
|
|
145
|
+
return (_jsxs("div", { className: "vs-brand vs-speech", children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsx("h4", { children: "Translations and readings" }), !shown.length && _jsx("p", { className: "vs-speech-muted", children: "Translate the transcript so listeners can read along, or hear it read aloud, in their language." }), shown.map((lang) => {
|
|
146
|
+
const t = translations[lang];
|
|
147
|
+
const s = speech[lang];
|
|
148
|
+
const busy = working[lang];
|
|
149
|
+
const voicesHere = voices[lang] ?? [];
|
|
150
|
+
return (_jsxs("div", { className: "vs-speech-row", children: [_jsxs("div", { children: [_jsx("strong", { children: names.get(lang) ?? lang }), _jsx("p", { className: "vs-speech-muted", children: t ? `${t.sentences.length} sentences translated` : 'Not translated' })] }), _jsxs("div", { style: { display: 'grid', gap: 6 }, children: [busy ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), busy] })) : s?.state === 'queued' || s?.state === 'running' ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), s.state === 'queued' ? 'Waiting to be read aloud…' : 'Being read aloud…', " (", voiceName(lang, s.voice), ")"] })) : s?.state === 'sealed' ? (_jsxs(_Fragment, { children: [_jsx("audio", { controls: true, preload: "none", src: `${serverURL}${api}${base}/audio${withQuery({ lang, v: s.renderedAt ?? '' })}` }, s.renderedAt ?? ''), _jsxs("span", { className: "vs-speech-muted", children: ["Read by ", voiceName(lang, s.voice)] })] })) : s?.state === 'failed' ? (_jsxs("p", { className: "vs-speech-error", children: ["Reading failed: ", s.error ?? 'no reason given'] })) : !canSpeak.has(lang) ? (_jsxs("span", { className: "vs-speech-muted", children: ["VocalStack cannot read ", names.get(lang) ?? lang, " aloud yet."] })) : null, canSpeak.has(lang) && !busy && s?.state !== 'queued' && s?.state !== 'running' && (_jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, children: [_jsxs("select", { "aria-label": "Voice", onChange: (e) => setPicked((p) => ({ ...p, [lang]: e.target.value })), value: picked[lang] ?? '', children: [_jsxs("option", { value: "", children: ["Default for this recording (", voiceName(lang, defaultVoice), ")"] }), voicesHere.map((v) => (_jsxs("option", { disabled: v.ready === false && v.cloned, value: v.id, children: [v.name, v.cloned ? ' (cloned)' : ''] }, v.id)))] }), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => speak([lang], picked[lang]), size: "small", children: s ? 'Read again' : 'Read aloud' })] }))] }), _jsx(Button, { buttonStyle: "secondary", disabled: Boolean(busy), margin: false, onClick: () => remove(lang), size: "small", children: "Remove" })] }, lang));
|
|
151
|
+
}), _jsx(AddLanguages, { busy: Object.keys(working).length > 0, canSpeak: canSpeak, exclude: new Set([...shown, ...(spoken ? [spoken] : [])]), langs: langs, onSpeak: (list) => speak(list), onTranslate: (list) => run(list, 'Translating…', () => translate(list)) }), error && _jsx("p", { className: "vs-speech-error", children: error })] }));
|
|
152
|
+
};
|
|
153
|
+
const AddLanguages = ({ busy, canSpeak, exclude, langs, onSpeak, onTranslate }) => {
|
|
154
|
+
const [open, setOpen] = useState(false);
|
|
155
|
+
const [filter, setFilter] = useState('');
|
|
156
|
+
const [chosen, setChosen] = useState([]);
|
|
157
|
+
if (!langs)
|
|
158
|
+
return null;
|
|
159
|
+
const options = langs.languages
|
|
160
|
+
.filter((l) => l.translation && !exclude.has(l.code))
|
|
161
|
+
.filter((l) => !filter || `${l.name} ${l.native} ${l.code}`.toLowerCase().includes(filter.toLowerCase()));
|
|
162
|
+
const go = async (fn) => {
|
|
163
|
+
const list = chosen;
|
|
164
|
+
setChosen([]);
|
|
165
|
+
setOpen(false);
|
|
166
|
+
await fn(list);
|
|
167
|
+
};
|
|
168
|
+
if (!open) {
|
|
169
|
+
return (_jsx("div", { style: { marginTop: 10 }, children: _jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setOpen(true), size: "small", children: "Add languages" }) }));
|
|
170
|
+
}
|
|
171
|
+
// A reading is at most a few languages at a time.
|
|
172
|
+
const speakable = chosen.filter((l) => canSpeak.has(l));
|
|
173
|
+
return (_jsxs("div", { style: { borderTop: '1px solid var(--theme-elevation-100)', marginTop: 10, paddingTop: 10 }, children: [_jsx("input", { onChange: (e) => setFilter(e.target.value), placeholder: "Find a language", type: "search", value: filter }), _jsx("div", { className: "vs-speech-langs", children: options.map((l) => (_jsxs("label", { children: [_jsx("input", { checked: chosen.includes(l.code), onChange: (e) => setChosen((c) => (e.target.checked ? [...c, l.code] : c.filter((x) => x !== l.code))), type: "checkbox" }), l.name, canSpeak.has(l.code) ? ' 🔊' : ''] }, l.code))) }), _jsx("p", { className: "vs-speech-muted", style: { marginBottom: 8 }, children: "\uD83D\uDD0A can also be read aloud. Translating a long recording takes a few minutes." }), _jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, children: [_jsx(Button, { disabled: busy || !chosen.length, margin: false, onClick: () => go(onTranslate), size: "small", children: "Translate" }), _jsx(Button, { disabled: busy || !speakable.length || speakable.length > 3, margin: false, onClick: () => go(async (list) => {
|
|
174
|
+
await onTranslate(list.filter((l) => !canSpeak.has(l)));
|
|
175
|
+
await onSpeak(list.filter((l) => canSpeak.has(l)));
|
|
176
|
+
}), size: "small", children: speakable.length > 3 ? 'Read aloud: 3 at a time' : 'Translate and read aloud' }), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setOpen(false), size: "small", children: "Cancel" })] })] }));
|
|
177
|
+
};
|
|
@@ -142,7 +142,7 @@ export const TranscriptField = ({ path }) => {
|
|
|
142
142
|
const remove = () => {
|
|
143
143
|
if (!window.confirm('Delete this transcript? It is removed when you save.'))
|
|
144
144
|
return;
|
|
145
|
-
for (const name of ['sentences', 'language', 'error', 'recordingId', 'transcriptionId', 'transcribedAt']) {
|
|
145
|
+
for (const name of ['sentences', 'language', 'error', 'recordingId', 'transcriptionId', 'transcribedAt', 'translations', 'speech']) {
|
|
146
146
|
dispatchFields({ type: 'UPDATE', path: `${base}${name}`, value: null });
|
|
147
147
|
}
|
|
148
148
|
dispatchFields({ type: 'UPDATE', path: `${base}status`, value: 'idle' });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const VoiceField: React.FC;
|