@vocalstack/payload 0.5.0 → 0.6.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
@@ -40,7 +40,7 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
40
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
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
42
  - **Languages for listeners** (opt in with `listeners`): visitors pick any language VocalStack offers, and it is made for them and kept for everyone after. `GET /api/vocalstack/languages` is public, `POST …/vocalstack/listen { lang }` asks for a language and `GET …/vocalstack/listen?lang=` says where it stands; see below.
43
- - **Voices** (opt in with `voices`): documents of a collection of people get a sidebar panel to clone that person's voice from a minute of a recording they speak in, or from an uploaded sample, with their permission. Kept in a hidden `vocalstackVoice` group (`voiceId`, `state`: `none`/`training`/`ready`/`failed`, `progress`, `error`, `sampleS`, `consentAt`, `createdAt`), with `GET`/`POST`/`DELETE /api/{collection}/:id/vocalstack/voice`, `…/voice/sources` and `…/voice/preview`.
43
+ - **Speakers** (opt in with `speakers`): documents of a collection of people get a sidebar panel that saves that person as a VocalStack speaker and clones their voice, from a minute of a recording they speak in or from an uploaded sample, with their permission. Kept in a hidden `vocalstackSpeaker` group (`speakerId`, `cloneId`, `state` of the voice: `none`/`training`/`ready`/`failed`, `progress`, `error`, `sampleS`, `consentAt`, `createdAt`), with `GET`/`POST`/`DELETE /api/{collection}/:id/vocalstack/speaker`, `…/speaker/sources` and `…/speaker/preview`.
44
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.
45
45
 
46
46
  ## Options
@@ -52,11 +52,11 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
52
52
  | `audioFields` | none | Audio that isn't an upload document; see below. |
53
53
  | `spokenLanguage` | auto-detect | A Whisper language code (`en`, `ro`, …). |
54
54
  | `fileURL` | the doc's `url`, made absolute | `({ doc, collection, req }) => string`: the address VocalStack fetches. Point it at your bucket's public URL to skip the Payload file proxy. |
55
- | `access` | signed-in users who can update the doc | Extra check for transcribing, translating, voices and the admin lookups, and for changing the connection. |
55
+ | `access` | signed-in users who can update the doc | Extra check for transcribing, translating, speakers, voices and the admin lookups, and for changing the connection. |
56
56
  | `oneClickConnect` | `false` | Show **Connect VocalStack** (see below). |
57
57
  | `apiURL` / `dashboardURL` | `https://api.vocalstack.com` / `https://app.vocalstack.com` | |
58
58
  | `enabled` | `true` | `false` keeps the schema but removes the button and the endpoints. |
59
- | `voices` | none | Collections of people who get a cloned voice; see below. |
59
+ | `speakers` | none | Collections of people saved as VocalStack speakers, each with a cloned voice; see below. (`voices`, its name in 0.5, still works.) |
60
60
  | `readings` | `{ slug: 'vocalstack-readings' }` | The upload collection finished readings are kept in, added by the plugin; `overrides: (collection) => collection` adjusts it. `false` streams readings from VocalStack instead. See below for bringing your own. |
61
61
  | `listeners` | off | `true`, or `{ languages?, speak?, access?, perHour? }`: let visitors ask for a transcript in their language; see below. |
62
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. |
@@ -80,38 +80,61 @@ vocalstackPlugin({
80
80
 
81
81
  Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?field=attachments&row=<row id>`. A new row needs saving first.
82
82
 
83
- ### Voices
83
+ ### Speakers
84
84
 
85
85
  ```ts
86
86
  import { vocalstackPlugin } from '@vocalstack/payload'
87
87
 
88
88
  vocalstackPlugin({
89
- voices: [
89
+ speakers: [
90
90
  {
91
91
  collection: 'speakers',
92
92
  // Recordings this speaker is in, offered as the sample to clone from.
93
93
  recordings: async ({ doc, req }) => {
94
94
  const { docs } = await req.payload.find({ collection: 'episodes', where: { speaker: { equals: doc.id } }, req })
95
- return docs.flatMap((e) => (e.vocalstack?.recordingId ? [{ label: e.title, recordingId: e.vocalstack.recordingId, sentences: e.vocalstack.sentences }] : []))
95
+ return docs.flatMap((e) => (e.vocalstack?.recordingId ? [{ label: e.title, recordingId: e.vocalstack.recordingId, sentences: e.vocalstack.sentences, transcriptionId: e.vocalstack.transcriptionId }] : []))
96
96
  },
97
97
  },
98
98
  ],
99
99
  })
100
100
  ```
101
101
 
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.
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/speaker/clip`), refuse any other. Pass each recording's `transcriptionId` too, or the plugin looks it up.
103
103
 
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.
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 speaker deletes them and their voice in VocalStack too. When VocalStack transcribes a new recording, it checks who speaks against your saved speakers first.
105
105
 
106
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
107
 
108
108
  ```ts
109
109
  voiceMode: async ({ doc, req }) => {
110
110
  const speaker = await req.payload.findByID({ collection: 'speakers', id: doc.speaker, depth: 0, req })
111
- return speaker.vocalstackVoice?.state === 'ready' ? 'cloned' : 'synthetic'
111
+ return speakerData(speaker).state === 'ready' ? 'cloned' : 'synthetic'
112
112
  }
113
113
  ```
114
114
 
115
+ `speakerData(doc)` (from `@vocalstack/payload`) reads the `vocalstackSpeaker` group, or the `vocalstackVoice` group of a document 0.5 saved and nobody has opened since.
116
+
117
+ ### Upgrading from 0.5
118
+
119
+ 0.6 follows VocalStack's rename of saved voices to **speakers** (`/v1/speakers`; a speaker's voice is only the sound, its clone). It talks to VocalStack before and after that change: it calls `/v1/speakers` first and falls back to `/v1/voices` on a 404, so nothing needs doing on the day the API changes.
120
+
121
+ - **Option**: `voices` is now `speakers`. `voices` is still read when `speakers` is not set. Types: `SpeakerCollectionConfig`, `SpeakerSource`, `SpeakerFieldData`, `CloneState` (the old names are deprecated aliases).
122
+ - **Fields**: speaker collections get a new hidden group, `vocalstackSpeaker` (`speakerId`, `cloneId`, and the fields `vocalstackVoice` had). The `vocalstackVoice` group stays in the schema and is kept in step (`voiceId` is the clone's id) for one more minor version, so code reading it keeps working; move it to `speakerData(doc)` or `vocalstackSpeaker`. The sidebar field is now `vocalstackSpeakerPanel` (a UI field, nothing stored).
123
+ - **Data**: nothing is lost. A document still holding only `vocalstackVoice` is read through it and copied into `vocalstackSpeaker` the first time its panel opens. To copy them all at once, call `migrateSpeakerFields({ collection, payload, req })` from a migration:
124
+
125
+ ```ts
126
+ // migrations/20261107_vocalstack_speakers.ts, after `payload migrate:create`
127
+ import { migrateSpeakerFields } from '@vocalstack/payload'
128
+ import type { MigrateUpArgs } from '@payloadcms/db-postgres'
129
+
130
+ export async function up({ payload, req }: MigrateUpArgs) {
131
+ await migrateSpeakerFields({ collection: 'speakers', payload, req })
132
+ }
133
+ ```
134
+
135
+ - **Run** `payload generate:importmap` (the panel's component is now `SpeakerField`), and with Postgres or SQLite `payload migrate:create` for the new columns (the old ones are kept).
136
+ - **Endpoints**: `/:id/vocalstack/speaker…` replaces `/:id/vocalstack/voice…`; the old paths still answer. Answers carry `vocalstackSpeaker` (and `vocalstackVoice` as before).
137
+
115
138
  ### Translations and readings
116
139
 
117
140
  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).
package/dist/api.d.ts CHANGED
@@ -51,16 +51,15 @@ export type Transcript = {
51
51
  text: string;
52
52
  }[];
53
53
  };
54
- export type Voice = {
54
+ export type SavedSpeaker = {
55
+ cloneId: null | string;
55
56
  createdAt: string;
56
- /** A trial voice, to hear before it is kept. */
57
57
  draft?: boolean;
58
58
  error?: null | string;
59
59
  id: string;
60
60
  name: string;
61
61
  progress: number;
62
62
  sampleS: number;
63
- /** `training`, `ready` or `failed`. */
64
63
  state: string;
65
64
  };
66
65
  export type VoiceOption = {
@@ -145,8 +144,8 @@ export declare class VocalStackAPI {
145
144
  }>;
146
145
  /**
147
146
  * 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
147
+ * voice where VocalStack can use one (a clone of that speaker, made with their permission, or the
148
+ * clone of a saved speaker VocalStack recognised as them) and in a stock voice otherwise; `synthetic` reads
150
149
  * everyone in stock voices. Each track says which it got (`voices`: cloned, synthetic or mixed).
151
150
  * A clone only ever reads words its own speaker said.
152
151
  */
@@ -161,18 +160,18 @@ export declare class VocalStackAPI {
161
160
  }): Promise<string>;
162
161
  /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
163
162
  clip(recordingId: string, startS: number, endS: number): Promise<Response>;
164
- voice(id: string): Promise<Voice>;
165
- /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
166
- createVoice(sample: Blob, fileName: string, meta: {
163
+ savedSpeaker(id: string): Promise<SavedSpeaker>;
164
+ /** Save a speaker from a recorded sample (30 s or more), cloning their voice. Needs the speaker's permission. */
165
+ createSpeaker(sample: Blob, fileName: string, meta: {
167
166
  consent: boolean;
168
167
  name: string;
169
- }, idempotencyKey: string): Promise<Voice>;
168
+ }, idempotencyKey: string): Promise<SavedSpeaker>;
170
169
  /**
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.
170
+ * Save a speaker from stretches of a transcribed recording (5–60 s in all), cloning their voice.
171
+ * `draft` makes a trial to hear first; keep it with `keepSpeaker`, or delete it. Saved speakers
172
+ * are the ones VocalStack looks for first when it works out who speaks in a new recording.
174
173
  */
175
- voiceFromSpeaker(opts: {
174
+ speakerFromAppearance(opts: {
176
175
  draft: boolean;
177
176
  name: string;
178
177
  recordingId: string;
@@ -181,16 +180,17 @@ export declare class VocalStackAPI {
181
180
  start: number;
182
181
  }[];
183
182
  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>;
187
- deleteVoice(id: string): Promise<unknown>;
183
+ transcriptionId?: string;
184
+ }, idempotencyKey: string): Promise<SavedSpeaker>;
185
+ /** Keep a trial speaker, as `name`, with the speaker's permission. */
186
+ keepSpeaker(id: string, name: string): Promise<SavedSpeaker>;
187
+ deleteSpeaker(id: string): Promise<void>;
188
+ /** The saved speaker's cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
189
+ speakerVoicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
188
190
  availableVoices(lang: string, recordingId?: string): Promise<{
189
191
  lang: string;
190
192
  voices: VoiceOption[];
191
193
  }>;
192
- /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
193
- voicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
194
194
  }
195
195
  /** A short label for the connected account, from whatever `/v1/me` carries. */
196
196
  export declare function accountLabel(me: Record<string, unknown>): string | undefined;
package/dist/api.js CHANGED
@@ -7,6 +7,22 @@
7
7
  import { VocalStack, VocalStackError } from '@vocalstack/js-sdk';
8
8
  export const DEFAULT_API_URL = 'https://api.vocalstack.com';
9
9
  export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
10
+ function savedSpeakerOf(raw) {
11
+ const clone = 'voice' in raw ? (raw.voice ?? null) : raw;
12
+ return {
13
+ cloneId: clone?.id ?? null,
14
+ createdAt: raw.createdAt,
15
+ draft: raw.draft ?? clone?.draft,
16
+ error: clone?.error ?? null,
17
+ id: raw.id,
18
+ name: raw.name,
19
+ progress: clone?.progress ?? 0,
20
+ sampleS: clone?.sampleS ?? 0,
21
+ state: clone?.state ?? 'none',
22
+ };
23
+ }
24
+ const speakerRoutes = new Map();
25
+ const both = (rest) => ({ speakers: `/v1/speakers${rest}`, voices: `/v1/voices${rest}` });
10
26
  export const UNAVAILABLE = 'VocalStack is unavailable, try again shortly.';
11
27
  export class VocalStackAPIError extends Error {
12
28
  code;
@@ -22,7 +38,7 @@ function timeoutFor(url, method = 'GET') {
22
38
  const path = new URL(url).pathname;
23
39
  if (path.endsWith('/translation'))
24
40
  return 180_000;
25
- if (method === 'POST' && path === '/v1/voices')
41
+ if (method === 'POST' && (path === '/v1/speakers' || path === '/v1/voices'))
26
42
  return 120_000;
27
43
  if (path.endsWith('/audio/clip') || path.endsWith('/preview'))
28
44
  return 60_000;
@@ -107,8 +123,8 @@ export class VocalStackAPI {
107
123
  }
108
124
  /**
109
125
  * 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
126
+ * voice where VocalStack can use one (a clone of that speaker, made with their permission, or the
127
+ * clone of a saved speaker VocalStack recognised as them) and in a stock voice otherwise; `synthetic` reads
112
128
  * everyone in stock voices. Each track says which it got (`voices`: cloned, synthetic or mixed).
113
129
  * A clone only ever reads words its own speaker said.
114
130
  */
@@ -144,35 +160,86 @@ export class VocalStackAPI {
144
160
  clip(recordingId, startS, endS) {
145
161
  return call(() => this.sdk.recordings.clip(recordingId, startS, endS));
146
162
  }
147
- voice(id) {
148
- return call(() => this.sdk.voices.get(id));
163
+ async #speakerRequest(method, paths, init = {}) {
164
+ const first = speakerRoutes.get(this.#baseURL) ?? 'speakers';
165
+ const order = first === 'speakers' ? ['speakers', 'voices'] : ['voices', 'speakers'];
166
+ const query = Object.entries(init.query ?? {}).filter((e) => e[1] !== undefined);
167
+ const qs = query.length ? `?${new URLSearchParams(query)}` : '';
168
+ let last;
169
+ for (const route of order) {
170
+ const path = paths[route];
171
+ if (!path)
172
+ continue;
173
+ const url = `${this.#baseURL}${path}${qs}`;
174
+ const headers = { accept: init.audio ? '*/*' : 'application/json', authorization: `Bearer ${this.#apiKey}` };
175
+ if (init.body)
176
+ headers['content-type'] = 'application/json';
177
+ if (init.idempotencyKey)
178
+ headers['idempotency-key'] = init.idempotencyKey;
179
+ const body = init.form ?? (init.body ? JSON.stringify(init.body(route)) : undefined);
180
+ const res = await call(() => fetch(url, { body, headers, method, signal: AbortSignal.timeout(timeoutFor(url, method)) }));
181
+ if (res.status !== 404) {
182
+ speakerRoutes.set(this.#baseURL, route);
183
+ return res;
184
+ }
185
+ last = res;
186
+ }
187
+ if (!last)
188
+ throw new VocalStackAPIError(404, 'not_found', 'Not found.');
189
+ return last;
190
+ }
191
+ async #speaker(method, paths, init) {
192
+ const res = await this.#speakerRequest(method, paths, init);
193
+ const body = (await res.json().catch(() => null));
194
+ if (res.ok && body)
195
+ return savedSpeakerOf(body);
196
+ if (res.status === 502 || res.status === 503 || res.status === 504)
197
+ throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
198
+ throw new VocalStackAPIError(res.status, body?.code ?? 'http_error', body?.message ?? `VocalStack answered ${res.status}`);
199
+ }
200
+ savedSpeaker(id) {
201
+ return this.#speaker('GET', both(`/${encodeURIComponent(id)}`));
149
202
  }
150
- /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
151
- createVoice(sample, fileName, meta, idempotencyKey) {
152
- return call(() => this.sdk.voices.create({ ...meta, fileName, sample }, { idempotencyKey }));
203
+ /** Save a speaker from a recorded sample (30 s or more), cloning their voice. Needs the speaker's permission. */
204
+ createSpeaker(sample, fileName, meta, idempotencyKey) {
205
+ const form = new FormData();
206
+ form.append('meta', JSON.stringify(meta));
207
+ form.append('sample', sample, fileName);
208
+ return this.#speaker('POST', both(''), { form, idempotencyKey });
153
209
  }
154
210
  /**
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.
211
+ * Save a speaker from stretches of a transcribed recording (5–60 s in all), cloning their voice.
212
+ * `draft` makes a trial to hear first; keep it with `keepSpeaker`, or delete it. Saved speakers
213
+ * are the ones VocalStack looks for first when it works out who speaks in a new recording.
158
214
  */
159
- voiceFromSpeaker(opts, idempotencyKey) {
160
- return call(() => this.sdk.voices.createFromSpeaker({ ...opts, consent: true, library: true }, { idempotencyKey }));
215
+ speakerFromAppearance(opts, idempotencyKey) {
216
+ const { recordingId, speaker, transcriptionId, ...rest } = opts;
217
+ const common = { ...rest, consent: true, library: true };
218
+ return this.#speaker('POST', { speakers: transcriptionId ? '/v1/speakers/from-appearance' : undefined, voices: '/v1/voices/from-speaker' }, {
219
+ body: (route) => (route === 'speakers' ? { ...common, appearance: speaker, transcriptionId } : { ...common, recordingId, speaker }),
220
+ idempotencyKey,
221
+ });
222
+ }
223
+ /** Keep a trial speaker, as `name`, with the speaker's permission. */
224
+ keepSpeaker(id, name) {
225
+ return this.#speaker('PATCH', both(`/${encodeURIComponent(id)}`), { body: () => ({ consent: true, draft: false, library: true, name }) });
161
226
  }
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 }));
227
+ async deleteSpeaker(id) {
228
+ const res = await this.#speakerRequest('DELETE', both(`/${encodeURIComponent(id)}`));
229
+ if (res.ok)
230
+ return;
231
+ const body = (await res.json().catch(() => null));
232
+ if (res.status === 502 || res.status === 503 || res.status === 504)
233
+ throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
234
+ throw new VocalStackAPIError(res.status, body?.code ?? 'http_error', body?.message ?? `VocalStack answered ${res.status}`);
165
235
  }
166
- deleteVoice(id) {
167
- return call(() => this.sdk.voices.delete(id));
236
+ /** The saved speaker's cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
237
+ speakerVoicePreview(id, lang, format = 'ogg') {
238
+ return this.#speakerRequest('GET', both(`/${encodeURIComponent(id)}/preview`), { audio: true, query: { format, lang } });
168
239
  }
169
240
  availableVoices(lang, recordingId) {
170
241
  return call(() => this.sdk.voices.available(lang, { recording: recordingId }));
171
242
  }
172
- /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
173
- voicePreview(id, lang, format = 'ogg') {
174
- return call(() => this.sdk.voices.clonePreview(id, { format, lang }));
175
- }
176
243
  }
177
244
  /** A short label for the connected account, from whatever `/v1/me` carries. */
178
245
  export function accountLabel(me) {
@@ -0,0 +1 @@
1
+ export declare const SpeakerField: React.FC;
@@ -15,25 +15,27 @@ const styles = `
15
15
  `;
16
16
  /** Ogg/Opus where the browser plays it, else CAF (Safari). */
17
17
  const previewFormat = () => (typeof Audio !== 'undefined' && new Audio().canPlayType('audio/ogg; codecs=opus') ? 'ogg' : 'caf');
18
- export const VoiceField = () => {
18
+ export const SpeakerField = () => {
19
19
  const { id, collectionSlug } = useDocumentInfo();
20
20
  const { dispatchFields } = useForm();
21
21
  const { connection } = useConnection();
22
22
  const call = useAPI();
23
- const base = `/${collectionSlug}/${id}/vocalstack/voice`;
23
+ const base = `/${collectionSlug}/${id}/vocalstack/speaker`;
24
24
  const [voice, setVoice] = useState();
25
25
  const [name, setName] = useState('');
26
26
  const [error, setError] = useState();
27
27
  const [busy, setBusy] = useState(false);
28
28
  const [creating, setCreating] = useState(false);
29
29
  const timer = useRef(undefined);
30
- // Keep the form's copy in step with the server's, so saving the document keeps the voice.
30
+ // Keep the form's copy in step with the server's, so saving the document keeps the speaker.
31
31
  const apply = useCallback((res) => {
32
- setVoice(res.vocalstackVoice);
32
+ setVoice(res.vocalstackSpeaker);
33
33
  if (res.name)
34
34
  setName(res.name);
35
- for (const [key, value] of Object.entries(res.vocalstackVoice)) {
36
- dispatchFields({ type: 'UPDATE', initialValue: value, path: `vocalstackVoice.${key}`, value });
35
+ for (const group of ['vocalstackSpeaker', 'vocalstackVoice']) {
36
+ for (const [key, value] of Object.entries(res[group] ?? {})) {
37
+ dispatchFields({ type: 'UPDATE', initialValue: value, path: `${group}.${key}`, value });
38
+ }
37
39
  }
38
40
  }, [dispatchFields]);
39
41
  const refresh = useCallback(async () => {
@@ -42,7 +44,7 @@ export const VoiceField = () => {
42
44
  const res = await call(base);
43
45
  apply(res);
44
46
  setError(undefined);
45
- if (res.vocalstackVoice.state === 'training')
47
+ if (res.vocalstackSpeaker.state === 'training')
46
48
  timer.current = setTimeout(refresh, POLL_MS);
47
49
  }
48
50
  catch (err) {
@@ -60,12 +62,12 @@ export const VoiceField = () => {
60
62
  // eslint-disable-next-line react-hooks/exhaustive-deps
61
63
  }, [id, connection?.connected]);
62
64
  const remove = async () => {
63
- if (!window.confirm(`Delete ${name || 'this'} voice? Readings already made with it stay as they are.`))
65
+ if (!window.confirm(`Delete ${name || 'this speaker'} from VocalStack, with their cloned voice? Readings already made with it stay as they are.`))
64
66
  return;
65
67
  setBusy(true);
66
68
  try {
67
69
  apply(await call(base, { method: 'DELETE' }));
68
- toast.success('Voice deleted.');
70
+ toast.success('Speaker deleted.');
69
71
  }
70
72
  catch (err) {
71
73
  setError(err.message);
@@ -76,7 +78,7 @@ export const VoiceField = () => {
76
78
  };
77
79
  const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
78
80
  const state = voice?.state ?? 'none';
79
- return (_jsxs("div", { className: "field-type vs-brand vs-voice", style: { marginBottom: 'var(--base)' }, children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsxs("div", { className: "field-label", style: { alignItems: 'center', display: 'flex', gap: 8, marginBottom: 'calc(var(--base) / 2)' }, children: [_jsx(Logo, { height: 14 }), " ", _jsx("span", { children: "Voice" })] }), !id ? (_jsx("p", { style: muted, children: "Save first, then create a voice." })) : connection && !connection.connected ? (_jsx("p", { style: muted, children: "Connect VocalStack (Settings \u2192 VocalStack) to create a voice." })) : !voice ? (_jsx("p", { style: muted, children: error ?? 'Checking…' })) : creating || state === 'none' || state === 'failed' ? (creating ? (_jsx(CreateVoice, { base: base, name: name, onCancel: () => setCreating(false), onCreated: (res) => {
81
+ return (_jsxs("div", { className: "field-type vs-brand vs-voice", style: { marginBottom: 'var(--base)' }, children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsxs("div", { className: "field-label", style: { alignItems: 'center', display: 'flex', gap: 8, marginBottom: 'calc(var(--base) / 2)' }, children: [_jsx(Logo, { height: 14 }), " ", _jsx("span", { children: "Speaker" })] }), !id ? (_jsx("p", { style: muted, children: "Save first, then save them as a speaker." })) : connection && !connection.connected ? (_jsx("p", { style: muted, children: "Connect VocalStack (Settings \u2192 VocalStack) to save them as a speaker." })) : !voice ? (_jsx("p", { style: muted, children: error ?? 'Checking…' })) : creating || state === 'none' || state === 'failed' ? (creating ? (_jsx(CreateVoice, { base: base, name: name, onCancel: () => setCreating(false), onCreated: (res) => {
80
82
  apply(res);
81
83
  setCreating(false);
82
84
  timer.current = setTimeout(refresh, POLL_MS);
@@ -123,7 +125,7 @@ const ReadyVoice = ({ base, busy, onDelete, voice }) => {
123
125
  };
124
126
  const names = new Map(langs?.languages.map((l) => [l.code, l.name]));
125
127
  const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
126
- return (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [_jsxs("p", { style: muted, children: ["Ready", voice.sampleS ? `, cloned from ${Math.round(voice.sampleS)} s of speech` : '', ". Translations are read in this voice."] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx("select", { "aria-label": "Preview language", onChange: (e) => setLang(e.target.value), value: lang, children: (langs?.voice ?? ['en']).map((code) => (_jsx("option", { value: code, children: names.get(code) ?? code }, code))) }), _jsx(Button, { buttonStyle: "secondary", disabled: waiting, margin: false, onClick: play, size: "small", children: waiting ? 'Making…' : '▶ Hear' })] }), src && _jsx("audio", { controls: true, ref: audio, src: src, style: { width: '100%' } }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsx("div", { children: _jsx(Button, { buttonStyle: "error", disabled: busy, margin: false, onClick: onDelete, size: "small", children: "Delete voice" }) })] }));
128
+ return (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [_jsxs("p", { style: muted, children: ["Ready", voice.sampleS ? `, cloned from ${Math.round(voice.sampleS)} s of speech` : '', ". Translations are read in this voice."] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx("select", { "aria-label": "Preview language", onChange: (e) => setLang(e.target.value), value: lang, children: (langs?.voice ?? ['en']).map((code) => (_jsx("option", { value: code, children: names.get(code) ?? code }, code))) }), _jsx(Button, { buttonStyle: "secondary", disabled: waiting, margin: false, onClick: play, size: "small", children: waiting ? 'Making…' : '▶ Hear' })] }), src && _jsx("audio", { controls: true, ref: audio, src: src, style: { width: '100%' } }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsx("div", { children: _jsx(Button, { buttonStyle: "error", disabled: busy, margin: false, onClick: onDelete, size: "small", children: "Delete speaker" }) })] }));
127
129
  };
128
130
  const CreateVoice = ({ base, name, onCancel, onCreated }) => {
129
131
  const call = useAPI();
@@ -1,4 +1,4 @@
1
- import type { VoiceFieldData, VoiceSource } from '../types.js';
1
+ import type { SpeakerAnswer, SpeakerSource } from '../types.js';
2
2
  /** As in the VocalStack dashboard: at least 5 s makes a voice, 20 s a steadier one, 25 s is plenty; 60 s at most. */
3
3
  export declare const PICK_MIN_S = 5;
4
4
  export declare const sampleStyles = "\n .vs-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 4px; }\n .vs-step { border-top: 3px solid var(--theme-elevation-150); padding-top: 6px; font-size: 12px; color: var(--theme-elevation-500); }\n .vs-step--on { border-color: var(--vs-accent); color: var(--theme-text); font-weight: 600; }\n .vs-step--done { border-color: color-mix(in srgb, var(--vs-accent) 45%, transparent); }\n .vs-sample { border: 1px solid var(--theme-elevation-150); border-radius: 8px; overflow: hidden; }\n .vs-sample-body { padding: 10px 12px; display: grid; gap: 8px; }\n .vs-sample-head { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: var(--theme-elevation-500); }\n .vs-sample-text { font-size: 14px; line-height: 1.45; min-height: 2.9em; }\n .vs-sample-play { display: flex; align-items: center; gap: 10px; }\n .vs-play { width: 34px; height: 34px; flex: none; border-radius: 50%; border: 0; background: var(--vs-accent); color: #fff; cursor: pointer; font-size: 12px; }\n .vs-play:disabled { opacity: .5; cursor: default; }\n .vs-wave { flex: 1; display: flex; align-items: center; gap: 2px; height: 28px; min-width: 0; }\n .vs-wave span { flex: 1; border-radius: 1px; background: var(--theme-elevation-250); }\n .vs-wave span.on { background: var(--vs-accent); }\n .vs-sample-use { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--theme-elevation-150);\n background: var(--theme-elevation-50); font-size: 14px; cursor: pointer; }\n .vs-pager { display: flex; gap: 4px; }\n .vs-pager button { border: 0; background: none; color: var(--theme-text); cursor: pointer; font-size: 16px; padding: 0 6px; }\n .vs-pager button:disabled { opacity: .3; cursor: default; }\n .vs-meter { position: relative; height: 6px; border-radius: 3px; background: var(--theme-elevation-100); overflow: hidden; }\n .vs-meter span { position: absolute; inset: 0 auto 0 0; background: var(--vs-accent); transition: width .3s; }\n .vs-meter-marks { position: relative; height: 16px; font-size: 11px; color: var(--theme-elevation-500); }\n .vs-meter-marks span { position: absolute; transform: translateX(-50%); }\n .vs-chips { display: flex; flex-wrap: wrap; gap: 6px; }\n .vs-chip { display: inline-flex; gap: 6px; align-items: center; border: 1px solid var(--theme-elevation-150); border-radius: 12px; padding: 2px 4px 2px 10px; font-size: 12px; }\n .vs-chip button { border: 0; background: none; cursor: pointer; color: var(--theme-elevation-500); }\n .vs-chips--none { border: 1px dashed var(--theme-elevation-200); border-radius: 12px; padding: 4px 10px; font-size: 12px; color: var(--theme-elevation-500); }\n";
@@ -9,11 +9,8 @@ export declare const sampleStyles = "\n .vs-steps { display: grid; grid-templat
9
9
  export declare const VoiceFromRecording: React.FC<{
10
10
  base: string;
11
11
  name: string;
12
- onCreated: (res: {
13
- name?: string;
14
- vocalstackVoice: VoiceFieldData;
15
- }) => void;
16
- sources: VoiceSource[];
12
+ onCreated: (res: SpeakerAnswer) => void;
13
+ sources: SpeakerSource[];
17
14
  }>;
18
15
  /** Record them speaking, in the browser, as the sample to clone from. */
19
16
  export declare const RecordSample: React.FC<{
@@ -217,7 +217,7 @@ export const VoiceFromRecording = ({ base, name, onCreated, sources }) => {
217
217
  method: 'POST',
218
218
  });
219
219
  kept.current = true;
220
- toast.success('Voice saved.');
220
+ toast.success('Speaker saved.');
221
221
  onCreated(res);
222
222
  }
223
223
  catch (err) {
@@ -245,7 +245,7 @@ export const VoiceFromRecording = ({ base, name, onCreated, sources }) => {
245
245
  ? `Enough for a voice. ${PICK_GOOD_S}s or more sounds steadier.`
246
246
  : `Good. About ${PICK_TARGET_S}s gives it more to choose from.` }), picked.size ? (_jsx("div", { className: "vs-chips", children: [...picked]
247
247
  .sort((a, b) => a - b)
248
- .map((i) => (_jsxs("span", { className: "vs-chip", children: [_jsxs("button", { onClick: () => setIdx(i), style: { color: 'inherit', padding: 0 }, type: "button", children: [i + 1, " \u00B7 ", Math.round(secs(clips[i])), "s"] }), _jsx("button", { "aria-label": `Leave sample ${i + 1} out`, onClick: () => toggle(i), type: "button", children: "\u2715" })] }, i))) })) : (_jsx("span", { className: "vs-chips--none", children: "No samples picked yet" })), _jsx("div", { children: _jsx(Button, { disabled: !enough || busy, margin: false, onClick: tryVoice, size: "small", children: "Next" }) })] })), step === 2 && (_jsxs(_Fragment, { children: [!trial || trial.state === 'training' || trial.state === 'queued' ? (_jsxs("p", { style: muted, children: ["Making the voice", trial?.progress ? ` · ${trial.progress}%` : '…', " It takes a minute or two."] })) : trial.state === 'failed' ? (_jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["The voice could not be made: ", trial.error ?? 'no reason given', ". Pick other samples."] })) : (_jsx(TrialPreview, { base: base, voice: trial.id })), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setStep(1), size: "small", children: "Back" }), _jsx(Button, { disabled: trial?.state !== 'ready', margin: false, onClick: () => setStep(3), size: "small", children: "Next" })] })] })), step === 3 && (_jsxs(_Fragment, { children: [_jsxs("label", { style: { display: 'grid', fontSize: 13, gap: 4 }, children: ["Name", _jsx("input", { maxLength: 60, onChange: (e) => setVoiceName(e.target.value), style: { font: 'inherit', padding: '6px 8px' }, value: voiceName })] }), _jsxs("label", { style: { alignItems: 'flex-start', display: 'flex', fontSize: 13, gap: 8 }, children: [_jsx("input", { checked: consent, onChange: (e) => setConsent(e.target.checked), style: { marginTop: 3 }, type: "checkbox" }), _jsxs("span", { children: ["I have ", name || 'their', "\u2019s permission to clone their voice."] })] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setStep(2), size: "small", children: "Back" }), _jsx(Button, { disabled: busy || !consent || !voiceName.trim(), margin: false, onClick: keep, size: "small", children: busy ? 'Saving…' : 'Save voice' })] })] })), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error })] }));
248
+ .map((i) => (_jsxs("span", { className: "vs-chip", children: [_jsxs("button", { onClick: () => setIdx(i), style: { color: 'inherit', padding: 0 }, type: "button", children: [i + 1, " \u00B7 ", Math.round(secs(clips[i])), "s"] }), _jsx("button", { "aria-label": `Leave sample ${i + 1} out`, onClick: () => toggle(i), type: "button", children: "\u2715" })] }, i))) })) : (_jsx("span", { className: "vs-chips--none", children: "No samples picked yet" })), _jsx("div", { children: _jsx(Button, { disabled: !enough || busy, margin: false, onClick: tryVoice, size: "small", children: "Next" }) })] })), step === 2 && (_jsxs(_Fragment, { children: [!trial || trial.state === 'training' || trial.state === 'queued' ? (_jsxs("p", { style: muted, children: ["Making the voice", trial?.progress ? ` · ${trial.progress}%` : '…', " It takes a minute or two."] })) : trial.state === 'failed' ? (_jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["The voice could not be made: ", trial.error ?? 'no reason given', ". Pick other samples."] })) : (_jsx(TrialPreview, { base: base, voice: trial.id })), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setStep(1), size: "small", children: "Back" }), _jsx(Button, { disabled: trial?.state !== 'ready', margin: false, onClick: () => setStep(3), size: "small", children: "Next" })] })] })), step === 3 && (_jsxs(_Fragment, { children: [_jsxs("label", { style: { display: 'grid', fontSize: 13, gap: 4 }, children: ["Name", _jsx("input", { maxLength: 60, onChange: (e) => setVoiceName(e.target.value), style: { font: 'inherit', padding: '6px 8px' }, value: voiceName })] }), _jsxs("label", { style: { alignItems: 'flex-start', display: 'flex', fontSize: 13, gap: 8 }, children: [_jsx("input", { checked: consent, onChange: (e) => setConsent(e.target.checked), style: { marginTop: 3 }, type: "checkbox" }), _jsxs("span", { children: ["I have ", name || 'their', "\u2019s permission to clone their voice."] })] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setStep(2), size: "small", children: "Back" }), _jsx(Button, { disabled: busy || !consent || !voiceName.trim(), margin: false, onClick: keep, size: "small", children: busy ? 'Saving…' : 'Save speaker' })] })] })), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error })] }));
249
249
  };
250
250
  /** Ogg/Opus where the browser plays it, else CAF (Safari). */
251
251
  const previewFormat = () => (typeof Audio !== 'undefined' && new Audio().canPlayType('audio/ogg; codecs=opus') ? 'ogg' : 'caf');
@@ -1,22 +1,32 @@
1
- import type { Endpoint } from 'payload';
2
- import type { VoiceCollectionConfig, VocalStackPluginOptions } from '../types.js';
1
+ import type { CollectionSlug, Endpoint, Payload, PayloadRequest } from 'payload';
2
+ import type { SpeakerCollectionConfig, SpeakerFieldData, VocalStackPluginOptions, VoiceFieldData } from '../types.js';
3
3
  export declare const PICK_MIN_S = 5;
4
4
  export declare const PICK_MAX_S = 60;
5
+ /** The document's saved speaker: the `vocalstackSpeaker` group, else the `vocalstackVoice` group of 0.5 and earlier. */
6
+ export declare function speakerData(doc: Record<string, unknown>): SpeakerFieldData;
7
+ /** Copy every document's `vocalstackVoice` group (0.5) into `vocalstackSpeaker`, e.g. from a Payload migration. Answers how many moved. */
8
+ export declare function migrateSpeakerFields({ collection, payload, req }: {
9
+ collection: CollectionSlug;
10
+ payload: Payload;
11
+ req?: PayloadRequest;
12
+ }): Promise<number>;
13
+ export declare const legacyVoiceData: ({ cloneId, speakerId, ...rest }: SpeakerFieldData) => VoiceFieldData;
5
14
  /**
6
- * A person's cloned voice, kept in the `vocalstackVoice` group of their document:
7
- * GET /:id/vocalstack/voice where its training stands
8
- * POST /:id/vocalstack/voice clone it: JSON { recordingId, startS, endS, consent },
9
- * or multipart with a `file` sample and `_payload` { consent }
10
- * DELETE /:id/vocalstack/voice delete it, in VocalStack too
11
- * GET /:id/vocalstack/voice/sources recordings to take the sample from
12
- * GET /:id/vocalstack/voice/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
13
- * GET /:id/vocalstack/voice/preview the voice speaking (?lang=&format=ogg|caf)
14
- * POST /:id/vocalstack/voice/trial a trial voice from picked sentences { recordingId, speaker, spans, replace? }
15
- * GET /:id/vocalstack/voice/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
16
- * POST /:id/vocalstack/voice/trial/keep { voice, name, consent } keep it as their voice; DELETE …/trial?voice= drop it
15
+ * A person saved as a VocalStack speaker, with their cloned voice, kept in the `vocalstackSpeaker` group of their document:
16
+ * GET /:id/vocalstack/speaker where its voice's training stands
17
+ * POST /:id/vocalstack/speaker save and clone them: JSON { recordingId, startS, endS, consent },
18
+ * or multipart with a `file` sample and `_payload` { consent }
19
+ * DELETE /:id/vocalstack/speaker delete it, and its voice, in VocalStack too
20
+ * GET /:id/vocalstack/speaker/sources recordings to take the sample from
21
+ * GET /:id/vocalstack/speaker/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
22
+ * GET /:id/vocalstack/speaker/preview the voice speaking (?lang=&format=ogg|caf)
23
+ * POST /:id/vocalstack/speaker/trial a trial from picked sentences { recordingId, speaker, spans, replace? }
24
+ * GET /:id/vocalstack/speaker/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
25
+ * POST /:id/vocalstack/speaker/trial/keep { voice, name, consent } keep it as their speaker; DELETE …/trial?voice= drop it
26
+ * Each also answers under /:id/vocalstack/voice…, its path in 0.5.
17
27
  * A sample is only ever taken from the recordings `config.recordings` offers for that document.
18
28
  */
19
- export declare function voiceEndpoints(config: VoiceCollectionConfig, options: VocalStackPluginOptions): Endpoint[];
29
+ export declare function speakerEndpoints(config: SpeakerCollectionConfig, options: VocalStackPluginOptions): Endpoint[];
20
30
  /**
21
31
  * Shared lookups:
22
32
  * GET /vocalstack/languages what can be translated and spoken (public with `listeners` on)
@@ -9,52 +9,85 @@ const json = (body, status = 200, headers) => Response.json(body, { headers, sta
9
9
  const MIN_SAMPLE_S = 30;
10
10
  const MAX_SAMPLE_S = 120;
11
11
  const STATES = new Set(['failed', 'ready', 'training']);
12
- /** VocalStack's voice as the document keeps it. */
12
+ /** VocalStack's saved speaker as the document keeps it. */
13
13
  const fieldData = (v) => ({
14
+ cloneId: v.cloneId,
14
15
  createdAt: v.createdAt,
15
16
  error: v.error ?? null,
16
17
  progress: v.progress,
17
18
  sampleS: v.sampleS,
18
- state: STATES.has(v.state) ? v.state : 'training',
19
- voiceId: v.id,
19
+ speakerId: v.id,
20
+ state: !v.cloneId ? 'none' : STATES.has(v.state) ? v.state : 'training',
20
21
  });
21
- /** A trial voice, as the panel follows it. */
22
+ /** A trial, as the panel follows it. */
22
23
  const trialOf = (v) => ({ error: v.error ?? null, id: v.id, progress: v.progress, state: v.state });
23
- /** Delete a trial voice; a kept one is never deleted this way. */
24
+ /** Delete a trial; a kept speaker is never deleted this way. */
24
25
  async function dropTrial(api, id) {
25
26
  if (!id)
26
27
  return;
27
- const voice = await api.voice(id).catch(() => null);
28
- if (voice?.draft)
29
- await api.deleteVoice(id).catch(() => undefined);
28
+ const speaker = await api.savedSpeaker(id).catch(() => null);
29
+ if (speaker?.draft)
30
+ await api.deleteSpeaker(id).catch(() => undefined);
30
31
  }
31
32
  // Picked from a recording, as in the VocalStack dashboard: at least 5 s makes a voice, at most 60 s.
32
33
  export const PICK_MIN_S = 5;
33
34
  export const PICK_MAX_S = 60;
34
- const EMPTY = { consentAt: null, createdAt: null, error: null, progress: null, sampleS: null, state: 'none', voiceId: null };
35
+ const EMPTY = { cloneId: null, consentAt: null, createdAt: null, error: null, progress: null, sampleS: null, speakerId: null, state: 'none' };
36
+ /** The document's saved speaker: the `vocalstackSpeaker` group, else the `vocalstackVoice` group of 0.5 and earlier. */
37
+ export function speakerData(doc) {
38
+ const now = doc.vocalstackSpeaker;
39
+ if (now?.speakerId)
40
+ return now;
41
+ const old = doc.vocalstackVoice;
42
+ if (old?.voiceId) {
43
+ const { voiceId, ...rest } = old;
44
+ return { ...EMPTY, ...rest, cloneId: voiceId, speakerId: voiceId };
45
+ }
46
+ return { ...EMPTY, ...now };
47
+ }
48
+ /** Copy every document's `vocalstackVoice` group (0.5) into `vocalstackSpeaker`, e.g. from a Payload migration. Answers how many moved. */
49
+ export async function migrateSpeakerFields({ collection, payload, req }) {
50
+ let moved = 0;
51
+ for (let page = 1;; page++) {
52
+ const res = await payload.find({ collection, depth: 0, limit: 100, overrideAccess: true, page, req, where: { 'vocalstackVoice.voiceId': { exists: true } } });
53
+ for (const doc of res.docs) {
54
+ if (doc.vocalstackSpeaker?.speakerId)
55
+ continue;
56
+ const data = speakerData(doc);
57
+ if (!data.speakerId)
58
+ continue;
59
+ await payload.update({ id: doc.id, collection, data: { vocalstackSpeaker: data }, depth: 0, overrideAccess: true, req });
60
+ moved++;
61
+ }
62
+ if (!res.hasNextPage)
63
+ return moved;
64
+ }
65
+ }
66
+ export const legacyVoiceData = ({ cloneId, speakerId, ...rest }) => ({ ...rest, voiceId: cloneId ?? speakerId ?? null });
35
67
  /**
36
- * A person's cloned voice, kept in the `vocalstackVoice` group of their document:
37
- * GET /:id/vocalstack/voice where its training stands
38
- * POST /:id/vocalstack/voice clone it: JSON { recordingId, startS, endS, consent },
39
- * or multipart with a `file` sample and `_payload` { consent }
40
- * DELETE /:id/vocalstack/voice delete it, in VocalStack too
41
- * GET /:id/vocalstack/voice/sources recordings to take the sample from
42
- * GET /:id/vocalstack/voice/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
43
- * GET /:id/vocalstack/voice/preview the voice speaking (?lang=&format=ogg|caf)
44
- * POST /:id/vocalstack/voice/trial a trial voice from picked sentences { recordingId, speaker, spans, replace? }
45
- * GET /:id/vocalstack/voice/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
46
- * POST /:id/vocalstack/voice/trial/keep { voice, name, consent } keep it as their voice; DELETE …/trial?voice= drop it
68
+ * A person saved as a VocalStack speaker, with their cloned voice, kept in the `vocalstackSpeaker` group of their document:
69
+ * GET /:id/vocalstack/speaker where its voice's training stands
70
+ * POST /:id/vocalstack/speaker save and clone them: JSON { recordingId, startS, endS, consent },
71
+ * or multipart with a `file` sample and `_payload` { consent }
72
+ * DELETE /:id/vocalstack/speaker delete it, and its voice, in VocalStack too
73
+ * GET /:id/vocalstack/speaker/sources recordings to take the sample from
74
+ * GET /:id/vocalstack/speaker/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
75
+ * GET /:id/vocalstack/speaker/preview the voice speaking (?lang=&format=ogg|caf)
76
+ * POST /:id/vocalstack/speaker/trial a trial from picked sentences { recordingId, speaker, spans, replace? }
77
+ * GET /:id/vocalstack/speaker/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
78
+ * POST /:id/vocalstack/speaker/trial/keep { voice, name, consent } keep it as their speaker; DELETE …/trial?voice= drop it
79
+ * Each also answers under /:id/vocalstack/voice…, its path in 0.5.
47
80
  * A sample is only ever taken from the recordings `config.recordings` offers for that document.
48
81
  */
49
- export function voiceEndpoints(config, options) {
82
+ export function speakerEndpoints(config, options) {
50
83
  const { collection } = config;
51
84
  const apiURL = options.apiURL ?? DEFAULT_API_URL;
52
85
  const open = async (req, verb) => {
53
86
  const id = req.routeParams?.id;
54
87
  if (!(await canUpdate(req, collection, id)))
55
- return json({ error: `You may not ${verb} this voice.` }, 403);
88
+ return json({ error: `You may not ${verb} this speaker.` }, 403);
56
89
  if (options.access && !(await options.access({ req })))
57
- return json({ error: `You may not ${verb} this voice.` }, 403);
90
+ return json({ error: `You may not ${verb} this speaker.` }, 403);
58
91
  const apiKey = await resolveAPIKey(req, options);
59
92
  if (!apiKey)
60
93
  return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
@@ -63,46 +96,48 @@ export function voiceEndpoints(config, options) {
63
96
  return json({ error: 'Not found.' }, 404);
64
97
  return { api: new VocalStackAPI(apiKey, apiURL), doc, id };
65
98
  };
66
- /** Whether the recording is one the host offers for this person (`config.recordings`). */
67
- const ownRecording = async (req, doc, recordingId) => ((await config.recordings?.({ doc, req })) ?? []).some((s) => s.recordingId === recordingId);
99
+ /** The recording, when the host offers it for this person (`config.recordings`). */
100
+ const ownRecording = async (req, doc, recordingId) => ((await config.recordings?.({ doc, req })) ?? []).find((s) => s.recordingId === recordingId);
68
101
  const save = async (req, id, data) => {
69
- await req.payload.update({ id, collection, data: { vocalstackVoice: data }, depth: 0, overrideAccess: true, req });
102
+ await req.payload.update({ id, collection, data: { vocalstackSpeaker: data, vocalstackVoice: legacyVoiceData(data) }, depth: 0, overrideAccess: true, req });
70
103
  return data;
71
104
  };
105
+ const answer = (name, data, status = 200) => json({ name, vocalstackSpeaker: data, vocalstackVoice: legacyVoiceData(data) }, status);
72
106
  const nameOf = (req, doc) => {
73
107
  const title = req.payload.collections[collection]?.config.admin?.useAsTitle;
74
108
  const name = config.name?.({ doc }) ?? (title && typeof doc[title] === 'string' ? doc[title] : typeof doc.name === 'string' ? doc.name : `${collection} ${doc.id}`);
75
109
  // VocalStack takes 1–60 characters.
76
110
  return name.trim().slice(0, 60) || `${collection} ${doc.id}`;
77
111
  };
78
- return [
112
+ const endpoints = [
79
113
  {
80
114
  method: 'get',
81
- path: '/:id/vocalstack/voice',
115
+ path: '/:id/vocalstack/speaker',
82
116
  handler: async (req) => {
83
117
  const found = await open(req, 'see');
84
118
  if (found instanceof Response)
85
119
  return found;
86
120
  const { api, doc, id } = found;
87
- const current = (doc.vocalstackVoice ?? {});
88
- if (!current.voiceId || current.state === 'ready')
89
- return json({ name: nameOf(req, doc), vocalstackVoice: current });
121
+ const stored = speakerData(doc);
122
+ const migrated = !doc.vocalstackSpeaker?.speakerId && !!stored.speakerId;
123
+ const current = migrated ? await save(req, id, stored) : stored;
124
+ if (!current.speakerId || current.state === 'ready')
125
+ return answer(nameOf(req, doc), current);
90
126
  try {
91
- const next = { ...current, ...fieldData(await api.voice(current.voiceId)) };
92
- const changed = next.state !== current.state || next.progress !== current.progress || next.error !== current.error;
93
- return json({ name: nameOf(req, doc), vocalstackVoice: changed ? await save(req, id, next) : current });
127
+ const next = { ...current, ...fieldData(await api.savedSpeaker(current.speakerId)) };
128
+ const changed = next.state !== current.state || next.progress !== current.progress || next.error !== current.error || next.cloneId !== current.cloneId;
129
+ return answer(nameOf(req, doc), changed ? await save(req, id, next) : current);
94
130
  }
95
131
  catch (err) {
96
- // Deleted in the VocalStack dashboard: there is no voice any more.
97
132
  if (err instanceof VocalStackAPIError && err.status === 404)
98
- return json({ name: nameOf(req, doc), vocalstackVoice: await save(req, id, EMPTY) });
133
+ return answer(nameOf(req, doc), await save(req, id, EMPTY));
99
134
  return apiError(err);
100
135
  }
101
136
  },
102
137
  },
103
138
  {
104
139
  method: 'post',
105
- path: '/:id/vocalstack/voice',
140
+ path: '/:id/vocalstack/speaker',
106
141
  handler: async (req) => {
107
142
  const found = await open(req, 'create');
108
143
  if (found instanceof Response)
@@ -135,13 +170,13 @@ export function voiceEndpoints(config, options) {
135
170
  }
136
171
  if (!consent)
137
172
  return json({ error: 'Confirm you have their permission to clone their voice.' }, 400);
138
- const previous = doc.vocalstackVoice?.voiceId;
139
- const voice = await api.createVoice(sample.blob, sample.name, { consent: true, name: nameOf(req, doc) }, `payload:${collection}:${id}:voice:${randomUUID()}`);
140
- const data = await save(req, id, { ...fieldData(voice), consentAt: new Date().toISOString() });
141
- // One voice per person: the old one goes once the new one exists.
142
- if (previous && previous !== voice.id)
143
- await api.deleteVoice(previous).catch(() => undefined);
144
- return json({ name: nameOf(req, doc), vocalstackVoice: data }, 201);
173
+ const previous = speakerData(doc).speakerId;
174
+ const speaker = await api.createSpeaker(sample.blob, sample.name, { consent: true, name: nameOf(req, doc) }, `payload:${collection}:${id}:voice:${randomUUID()}`);
175
+ const data = await save(req, id, { ...fieldData(speaker), consentAt: new Date().toISOString() });
176
+ // One saved speaker per person: the old one goes once the new one exists.
177
+ if (previous && previous !== speaker.id)
178
+ await api.deleteSpeaker(previous).catch(() => undefined);
179
+ return answer(nameOf(req, doc), data, 201);
145
180
  }
146
181
  catch (err) {
147
182
  return apiError(err);
@@ -150,27 +185,27 @@ export function voiceEndpoints(config, options) {
150
185
  },
151
186
  {
152
187
  method: 'delete',
153
- path: '/:id/vocalstack/voice',
188
+ path: '/:id/vocalstack/speaker',
154
189
  handler: async (req) => {
155
190
  const found = await open(req, 'delete');
156
191
  if (found instanceof Response)
157
192
  return found;
158
193
  const { api, doc, id } = found;
159
- const voiceId = doc.vocalstackVoice?.voiceId;
194
+ const { speakerId } = speakerData(doc);
160
195
  try {
161
- if (voiceId)
162
- await api.deleteVoice(voiceId);
196
+ if (speakerId)
197
+ await api.deleteSpeaker(speakerId);
163
198
  }
164
199
  catch (err) {
165
200
  if (!(err instanceof VocalStackAPIError && err.status === 404))
166
201
  return apiError(err);
167
202
  }
168
- return json({ name: nameOf(req, doc), vocalstackVoice: await save(req, id, EMPTY) });
203
+ return answer(nameOf(req, doc), await save(req, id, EMPTY));
169
204
  },
170
205
  },
171
206
  {
172
207
  method: 'get',
173
- path: '/:id/vocalstack/voice/sources',
208
+ path: '/:id/vocalstack/speaker/sources',
174
209
  handler: async (req) => {
175
210
  const found = await open(req, 'create');
176
211
  if (found instanceof Response)
@@ -187,7 +222,7 @@ export function voiceEndpoints(config, options) {
187
222
  },
188
223
  {
189
224
  method: 'get',
190
- path: '/:id/vocalstack/voice/clip',
225
+ path: '/:id/vocalstack/speaker/clip',
191
226
  handler: async (req) => {
192
227
  const found = await open(req, 'create');
193
228
  if (found instanceof Response)
@@ -210,7 +245,7 @@ export function voiceEndpoints(config, options) {
210
245
  {
211
246
  // A trial voice from sentences of one of their recordings, to hear before keeping it.
212
247
  method: 'post',
213
- path: '/:id/vocalstack/voice/trial',
248
+ path: '/:id/vocalstack/speaker/trial',
214
249
  handler: async (req) => {
215
250
  const found = await open(req, 'create');
216
251
  if (found instanceof Response)
@@ -224,14 +259,16 @@ export function voiceEndpoints(config, options) {
224
259
  if (typeof body.recordingId !== 'string' || !Number.isInteger(body.speaker) || total < PICK_MIN_S - 0.05 || total > PICK_MAX_S + 0.5) {
225
260
  return json({ error: `Pick ${PICK_MIN_S} to ${PICK_MAX_S} seconds of their speech.` }, 400);
226
261
  }
227
- if (!(await ownRecording(req, doc, body.recordingId)))
262
+ const source = await ownRecording(req, doc, body.recordingId);
263
+ if (!source)
228
264
  return json({ error: 'That recording is not one of theirs.' }, 403);
229
265
  try {
230
- const voice = await api.voiceFromSpeaker({ draft: true, name: nameOf(req, doc), recordingId: body.recordingId, spans, speaker: body.speaker }, `payload:${collection}:${id}:trial:${randomUUID()}`);
266
+ const transcriptionId = source.transcriptionId ?? (await api.job(source.recordingId).then((j) => j.transcriptionId, () => undefined));
267
+ const trial = await api.speakerFromAppearance({ draft: true, name: nameOf(req, doc), recordingId: source.recordingId, spans, speaker: body.speaker, transcriptionId }, `payload:${collection}:${id}:trial:${randomUUID()}`);
231
268
  // The trial it replaces (other samples picked) is not wanted any more.
232
- if (typeof body.replace === 'string' && body.replace !== voice.id)
269
+ if (typeof body.replace === 'string' && body.replace !== trial.id)
233
270
  await dropTrial(api, body.replace);
234
- return json({ voice: trialOf(voice) }, 201);
271
+ return json({ voice: trialOf(trial) }, 201);
235
272
  }
236
273
  catch (err) {
237
274
  return apiError(err);
@@ -240,16 +277,16 @@ export function voiceEndpoints(config, options) {
240
277
  },
241
278
  {
242
279
  method: 'get',
243
- path: '/:id/vocalstack/voice/trial',
280
+ path: '/:id/vocalstack/speaker/trial',
244
281
  handler: async (req) => {
245
282
  const found = await open(req, 'create');
246
283
  if (found instanceof Response)
247
284
  return found;
248
285
  try {
249
- const voice = await found.api.voice(req.searchParams.get('voice') ?? '');
250
- if (!voice.draft)
286
+ const trial = await found.api.savedSpeaker(req.searchParams.get('voice') ?? '');
287
+ if (!trial.draft)
251
288
  return json({ error: 'Not a trial voice.' }, 404);
252
- return json({ voice: trialOf(voice) });
289
+ return json({ voice: trialOf(trial) });
253
290
  }
254
291
  catch (err) {
255
292
  return apiError(err);
@@ -258,17 +295,17 @@ export function voiceEndpoints(config, options) {
258
295
  },
259
296
  {
260
297
  method: 'get',
261
- path: '/:id/vocalstack/voice/trial/preview',
298
+ path: '/:id/vocalstack/speaker/trial/preview',
262
299
  handler: async (req) => {
263
300
  const found = await open(req, 'hear');
264
301
  if (found instanceof Response)
265
302
  return found;
266
303
  const format = req.searchParams.get('format') === 'caf' ? 'caf' : 'ogg';
267
304
  try {
268
- const voice = await found.api.voice(req.searchParams.get('voice') ?? '');
269
- if (!voice.draft)
305
+ const trial = await found.api.savedSpeaker(req.searchParams.get('voice') ?? '');
306
+ if (!trial.draft)
270
307
  return json({ error: 'Not a trial voice.' }, 404);
271
- const res = await found.api.voicePreview(voice.id, req.searchParams.get('lang') ?? undefined, format);
308
+ const res = await found.api.speakerVoicePreview(trial.id, req.searchParams.get('lang') ?? undefined, format);
272
309
  if (res.status === 202)
273
310
  return json({ pending: true }, 202);
274
311
  if (!res.ok)
@@ -281,9 +318,9 @@ export function voiceEndpoints(config, options) {
281
318
  },
282
319
  },
283
320
  {
284
- // Keep the trial as their voice (with their permission); the voice they had before goes.
321
+ // Keep the trial as their saved speaker (with their permission); the one they had before goes.
285
322
  method: 'post',
286
- path: '/:id/vocalstack/voice/trial/keep',
323
+ path: '/:id/vocalstack/speaker/trial/keep',
287
324
  handler: async (req) => {
288
325
  const found = await open(req, 'create');
289
326
  if (found instanceof Response)
@@ -296,15 +333,15 @@ export function voiceEndpoints(config, options) {
296
333
  return json({ error: 'Which voice?' }, 400);
297
334
  const name = (typeof body.name === 'string' && body.name.trim() ? body.name.trim() : nameOf(req, doc)).slice(0, 60);
298
335
  try {
299
- const trial = await api.voice(body.voice);
336
+ const trial = await api.savedSpeaker(body.voice);
300
337
  if (!trial.draft)
301
338
  return json({ error: 'Not a trial voice.' }, 404);
302
- const voice = await api.keepVoice(trial.id, name);
303
- const previous = doc.vocalstackVoice?.voiceId;
304
- const data = await save(req, id, { ...fieldData(voice), consentAt: new Date().toISOString() });
305
- if (previous && previous !== voice.id)
306
- await api.deleteVoice(previous).catch(() => undefined);
307
- return json({ name: nameOf(req, doc), vocalstackVoice: data });
339
+ const speaker = await api.keepSpeaker(trial.id, name);
340
+ const previous = speakerData(doc).speakerId;
341
+ const data = await save(req, id, { ...fieldData(speaker), consentAt: new Date().toISOString() });
342
+ if (previous && previous !== speaker.id)
343
+ await api.deleteSpeaker(previous).catch(() => undefined);
344
+ return answer(nameOf(req, doc), data);
308
345
  }
309
346
  catch (err) {
310
347
  return apiError(err);
@@ -313,7 +350,7 @@ export function voiceEndpoints(config, options) {
313
350
  },
314
351
  {
315
352
  method: 'delete',
316
- path: '/:id/vocalstack/voice/trial',
353
+ path: '/:id/vocalstack/speaker/trial',
317
354
  handler: async (req) => {
318
355
  const found = await open(req, 'create');
319
356
  if (found instanceof Response)
@@ -324,17 +361,17 @@ export function voiceEndpoints(config, options) {
324
361
  },
325
362
  {
326
363
  method: 'get',
327
- path: '/:id/vocalstack/voice/preview',
364
+ path: '/:id/vocalstack/speaker/preview',
328
365
  handler: async (req) => {
329
366
  const found = await open(req, 'hear');
330
367
  if (found instanceof Response)
331
368
  return found;
332
- const voiceId = found.doc.vocalstackVoice?.voiceId;
333
- if (!voiceId)
369
+ const { cloneId, speakerId } = speakerData(found.doc);
370
+ if (!speakerId || !cloneId)
334
371
  return json({ error: 'There is no voice yet.' }, 404);
335
372
  const format = req.searchParams.get('format') === 'caf' ? 'caf' : 'ogg';
336
373
  try {
337
- const res = await found.api.voicePreview(voiceId, req.searchParams.get('lang') ?? undefined, format);
374
+ const res = await found.api.speakerVoicePreview(speakerId, req.searchParams.get('lang') ?? undefined, format);
338
375
  // 202: being rendered; the client asks again.
339
376
  if (res.status === 202)
340
377
  return json({ pending: true }, 202);
@@ -348,6 +385,7 @@ export function voiceEndpoints(config, options) {
348
385
  },
349
386
  },
350
387
  ];
388
+ return [...endpoints, ...endpoints.map((e) => ({ ...e, path: e.path.replace('/vocalstack/speaker', '/vocalstack/voice') }))];
351
389
  }
352
390
  /**
353
391
  * Shared lookups:
@@ -1,5 +1,5 @@
1
1
  export { ConnectionPanel } from '../components/ConnectionPanel.js';
2
+ export { SpeakerField } from '../components/SpeakerField.js';
2
3
  export { SpeechField } from '../components/SpeechField.js';
3
4
  export { TranscribeButton } from '../components/TranscribeButton.js';
4
5
  export { TranscriptField } from '../components/TranscriptField.js';
5
- export { VoiceField } from '../components/VoiceField.js';
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  export { ConnectionPanel } from '../components/ConnectionPanel.js';
3
+ export { SpeakerField } from '../components/SpeakerField.js';
3
4
  export { SpeechField } from '../components/SpeechField.js';
4
5
  export { TranscribeButton } from '../components/TranscribeButton.js';
5
6
  export { TranscriptField } from '../components/TranscriptField.js';
6
- export { VoiceField } from '../components/VoiceField.js';
package/dist/index.d.ts CHANGED
@@ -2,4 +2,5 @@ import type { Plugin } from 'payload';
2
2
  import type { VocalStackPluginOptions } from './types.js';
3
3
  export type * from './types.js';
4
4
  export { spokenSentences, timedTokens, transcriptText } from './text.js';
5
+ export { migrateSpeakerFields, speakerData } from './endpoints/voices.js';
5
6
  export declare const vocalstackPlugin: (options?: VocalStackPluginOptions) => Plugin;
package/dist/index.js CHANGED
@@ -2,10 +2,11 @@ import { connectionEndpoints } from './endpoints/connection.js';
2
2
  import { refreshAfterRead, speechEndpoints } from './endpoints/speech.js';
3
3
  import { streamEndpoint } from './endpoints/stream.js';
4
4
  import { transcribeEndpoints } from './endpoints/transcribe.js';
5
- import { lookupEndpoints, voiceEndpoints } from './endpoints/voices.js';
5
+ import { lookupEndpoints, speakerEndpoints } from './endpoints/voices.js';
6
6
  import { readingsCollection, readingsSlug } from './readings.js';
7
7
  import { settingsGlobal } from './settings.js';
8
8
  export { spokenSentences, timedTokens, transcriptText } from './text.js';
9
+ export { migrateSpeakerFields, speakerData } from './endpoints/voices.js';
9
10
  const isAudioDoc = (data) => typeof data?.mimeType === 'string' && data.mimeType.startsWith('audio/');
10
11
  /** An upload collection that can hold audio: `audio/*`, a wildcard, or no restriction at all. */
11
12
  function acceptsAudio(collection) {
@@ -84,22 +85,38 @@ function transcriptionFields(enabled, options, target) {
84
85
  },
85
86
  ];
86
87
  }
87
- /** A person's cloned voice: the panel, and what VocalStack says about the voice. */
88
- function voiceFields(enabled) {
88
+ /** A person saved as a VocalStack speaker: the panel, and what VocalStack says about the speaker and their cloned voice. */
89
+ function speakerFields(enabled) {
89
90
  return [
90
91
  ...(enabled
91
92
  ? [
92
93
  {
93
- name: 'vocalstackVoicePanel',
94
+ name: 'vocalstackSpeakerPanel',
94
95
  type: 'ui',
95
- admin: { components: { Field: '@vocalstack/payload/client#VoiceField' }, position: 'sidebar' },
96
+ admin: { components: { Field: '@vocalstack/payload/client#SpeakerField' }, position: 'sidebar' },
96
97
  },
97
98
  ]
98
99
  : []),
100
+ {
101
+ name: 'vocalstackSpeaker',
102
+ type: 'group',
103
+ label: 'Speaker',
104
+ admin: { hidden: true },
105
+ fields: [
106
+ { name: 'speakerId', type: 'text', ...hidden },
107
+ { name: 'cloneId', type: 'text', ...hidden },
108
+ { name: 'state', type: 'select', defaultValue: 'none', options: ['none', 'training', 'ready', 'failed'], ...hidden },
109
+ { name: 'progress', type: 'number', ...hidden },
110
+ { name: 'error', type: 'text', ...hidden },
111
+ { name: 'sampleS', type: 'number', ...hidden },
112
+ { name: 'consentAt', type: 'date', ...hidden },
113
+ { name: 'createdAt', type: 'date', ...hidden },
114
+ ],
115
+ },
99
116
  {
100
117
  name: 'vocalstackVoice',
101
118
  type: 'group',
102
- label: 'Voice',
119
+ label: 'Voice (0.5)',
103
120
  admin: { hidden: true },
104
121
  fields: [
105
122
  { name: 'voiceId', type: 'text', ...hidden },
@@ -151,20 +168,20 @@ export const vocalstackPlugin = (options = {}) => (config) => {
151
168
  const readings = readingsSlug(options);
152
169
  const uploads = new Set(options.collections ?? collections.filter((c) => c.slug !== readings && acceptsAudio(c)).map((c) => c.slug));
153
170
  const audioFields = options.audioFields ?? [];
154
- const voices = options.voices ?? [];
155
- for (const v of voices) {
171
+ const speakers = options.speakers ?? options.voices ?? [];
172
+ for (const v of speakers) {
156
173
  if (!collections.some((c) => c.slug === v.collection))
157
- throw new Error(`vocalstackPlugin: no collection "${v.collection}" for voices`);
174
+ throw new Error(`vocalstackPlugin: no collection "${v.collection}" for speakers`);
158
175
  }
159
176
  return {
160
177
  ...config,
161
178
  collections: [...collections, ...(readings && !collections.some((c) => c.slug === readings) ? [(options.readings && options.readings.overrides ? options.readings.overrides : (c) => c)(readingsCollection(readings))] : [])].map((original) => {
162
- const voice = voices.find((v) => v.collection === original.slug);
163
- const collection = voice
179
+ const speaker = speakers.find((v) => v.collection === original.slug);
180
+ const collection = speaker
164
181
  ? {
165
182
  ...original,
166
- endpoints: enabled ? [...(original.endpoints || []), ...voiceEndpoints(voice, options)] : original.endpoints,
167
- fields: [...original.fields, ...voiceFields(enabled)],
183
+ endpoints: enabled ? [...(original.endpoints || []), ...speakerEndpoints(speaker, options)] : original.endpoints,
184
+ fields: [...original.fields, ...speakerFields(enabled)],
168
185
  }
169
186
  : original;
170
187
  const rowFields = audioFields.filter((f) => f.collection === collection.slug);
package/dist/types.d.ts CHANGED
@@ -62,10 +62,13 @@ export type VocalStackPluginOptions = {
62
62
  req: PayloadRequest;
63
63
  }) => boolean | Promise<boolean>;
64
64
  /**
65
- * Collections of people (speakers, presenters) that each get a cloned VocalStack voice:
66
- * made from a stretch of a recording they speak in, or from a sample, with their permission.
65
+ * Collections of people (speakers, presenters) that are each saved as a VocalStack speaker,
66
+ * with a cloned voice made from a stretch of a recording they speak in, or from a sample,
67
+ * with their permission.
67
68
  */
68
- voices?: VoiceCollectionConfig[];
69
+ speakers?: SpeakerCollectionConfig[];
70
+ /** @deprecated Renamed to `speakers`; still read when `speakers` is not set. */
71
+ voices?: SpeakerCollectionConfig[];
69
72
  /**
70
73
  * Let the site's visitors ask for a transcript in their own language: it is translated,
71
74
  * read aloud where VocalStack has a voice for it, and kept on the document (and the
@@ -99,9 +102,9 @@ export type ListenerOptions = {
99
102
  /** New languages one visitor (by IP address) may ask for in an hour, on this server. Default 10. */
100
103
  perHour?: number;
101
104
  };
102
- export type VoiceCollectionConfig = {
105
+ export type SpeakerCollectionConfig = {
103
106
  collection: CollectionSlug;
104
- /** The voice's name in VocalStack. Default: the collection's `useAsTitle` field, else `name`. */
107
+ /** The speaker's name in VocalStack. Default: the collection's `useAsTitle` field, else `name`. */
105
108
  name?: (args: {
106
109
  doc: Record<string, unknown>;
107
110
  }) => string;
@@ -109,25 +112,48 @@ export type VoiceCollectionConfig = {
109
112
  recordings?: (args: {
110
113
  doc: Record<string, unknown>;
111
114
  req: PayloadRequest;
112
- }) => Promise<VoiceSource[]> | VoiceSource[];
115
+ }) => Promise<SpeakerSource[]> | SpeakerSource[];
113
116
  };
114
117
  /** A transcribed recording to take a voice sample from. */
115
- export type VoiceSource = {
118
+ export type SpeakerSource = {
116
119
  label: string;
117
120
  recordingId: string;
118
121
  sentences?: TranscriptSentence[];
122
+ transcriptionId?: string;
119
123
  };
120
- export type VoiceState = 'failed' | 'none' | 'ready' | 'training';
121
- /** The `vocalstackVoice` group on a voice collection's documents. */
124
+ export type CloneState = 'failed' | 'none' | 'ready' | 'training';
125
+ /** The `vocalstackSpeaker` group on a speaker collection's documents. */
126
+ export type SpeakerFieldData = {
127
+ cloneId?: null | string;
128
+ consentAt?: null | string;
129
+ createdAt?: null | string;
130
+ error?: null | string;
131
+ progress?: null | number;
132
+ sampleS?: null | number;
133
+ speakerId?: null | string;
134
+ state?: null | CloneState;
135
+ };
136
+ /** @deprecated The `vocalstackVoice` group of 0.5 and earlier, kept in step for a release; read `vocalstackSpeaker`. */
122
137
  export type VoiceFieldData = {
123
138
  consentAt?: null | string;
124
139
  createdAt?: null | string;
125
140
  error?: null | string;
126
141
  progress?: null | number;
127
142
  sampleS?: null | number;
128
- state?: null | VoiceState;
143
+ state?: null | CloneState;
129
144
  voiceId?: null | string;
130
145
  };
146
+ export type SpeakerAnswer = {
147
+ name?: string;
148
+ vocalstackSpeaker: SpeakerFieldData;
149
+ vocalstackVoice?: VoiceFieldData;
150
+ };
151
+ /** @deprecated Renamed to `SpeakerCollectionConfig`. */
152
+ export type VoiceCollectionConfig = SpeakerCollectionConfig;
153
+ /** @deprecated Renamed to `SpeakerSource`. */
154
+ export type VoiceSource = SpeakerSource;
155
+ /** @deprecated Renamed to `CloneState`. */
156
+ export type VoiceState = CloneState;
131
157
  export type Translation = {
132
158
  /** The transcript's sentences (same ids and times), their text translated. */
133
159
  sentences: TranscriptSentence[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vocalstack/payload",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "VocalStack for Payload CMS: transcribe audio, translate it into other languages and read it aloud, kept in your own database and storage.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1 +0,0 @@
1
- export declare const VoiceField: React.FC;