@vocalstack/payload 0.4.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.
@@ -132,9 +132,9 @@ const readingName = (target, lang, voice) => `${(target.name || target.fileName.
132
132
  async function keepReading(req, api, slug, target, lang, speech) {
133
133
  if (speech.audio || speech.state !== 'sealed')
134
134
  return speech;
135
- // The reading's key as VocalStack knows it: its mode (`synthetic` | `cloned`) on newer APIs,
136
- // its cast key on older ones. A key the API does not take (400) is followed by the next.
137
- const keys = [...new Set([speech.voice ?? undefined, speech.cast ?? undefined, undefined])];
135
+ // The reading's track by its key (`cast:…`), or the default voice for older (`''`) tracks.
136
+ // A key the API does not take (400) is followed by the default.
137
+ const keys = [...new Set([speech.voice || undefined, undefined])];
138
138
  let res;
139
139
  for (const voice of keys) {
140
140
  const src = await api.audioURL(target.data.recordingId, { kind: 'voice', lang, voice });
@@ -192,8 +192,8 @@ function trackFor(tracks, lang, speech) {
192
192
  return mine.find((t) => keyOf(t) === speech.voice);
193
193
  return mine.find((t) => keyOf(t) && t.state !== 'clips') ?? mine.find((t) => t.voiceKey === '');
194
194
  }
195
- /** A track's key: its mode (`synthetic` | `cloned`) where the API names one, else its cast key. */
196
- const keyOf = (t) => (t.voice === 'synthetic' || t.voice === 'cloned' ? t.voice : t.voiceKey);
195
+ /** A track's key, which `/audio?voice=` takes: its cast (`cast:0=M1;1=F1`), or `''` on older tracks. */
196
+ const keyOf = (t) => t.voiceKey;
197
197
  /** The key VocalStack gave the reading it just took on for `lang`. */
198
198
  const askedKey = (tracks, lang) => {
199
199
  const mine = (Array.isArray(tracks) ? tracks : []).filter((t) => t.lang === lang);
@@ -204,8 +204,9 @@ const askedKey = (tracks, lang) => {
204
204
  async function voiceModeOf(req, collection, options, target) {
205
205
  const decided = await options.voiceMode?.({ collection, doc: target.doc, req, row: target.row });
206
206
  if (decided === 'cloned' || decided === 'synthetic')
207
- return { fixed: true, mode: decided };
208
- return { fixed: false, mode: target.data.voices === 'cloned' ? 'cloned' : 'synthetic' };
207
+ return { as: { cloned: decided === 'cloned' }, fixed: true, mode: decided };
208
+ const mode = target.data.voices === 'cloned' ? 'cloned' : 'synthetic';
209
+ return { as: { cloned: mode === 'cloned' }, fixed: false, mode };
209
210
  }
210
211
  /** A spoken translation brought up to date from VocalStack's track. */
211
212
  function settle(speech, track, translation) {
@@ -216,10 +217,12 @@ function settle(speech, track, translation) {
216
217
  }
217
218
  if (track.state === 'failed')
218
219
  return { ...speech, error: track.error ?? 'The reading failed.', state: 'failed' };
220
+ const readIn = track.voices ?? speech.readIn ?? null;
219
221
  if (track.state !== 'sealed')
220
- return { ...speech, done: track.clips?.length ?? 0, error: null, state: track.state === 'queued' ? 'queued' : 'running', voice: keyOf(track) || speech.voice };
222
+ return { ...speech, done: track.clips?.length ?? 0, error: null, readIn, state: track.state === 'queued' ? 'queued' : 'running', voice: keyOf(track) || speech.voice };
221
223
  return {
222
224
  ...speech,
225
+ readIn,
223
226
  voice: keyOf(track) || speech.voice,
224
227
  done: null,
225
228
  durationS: track.durationS ?? null,
@@ -315,7 +318,7 @@ async function refresh(req, api, readings, target, key) {
315
318
  * is asked for, step by step (each step saved), ask VocalStack to read each one aloud once its
316
319
  * translation is done, then bring readings up to date and keep their files. The field as saved.
317
320
  */
318
- async function advance(req, api, readings, target, key, budgetMs, cloned) {
321
+ async function advance(req, api, readings, target, key, budgetMs, speakAs) {
319
322
  const deadline = Date.now() + budgetMs;
320
323
  let data = target.data;
321
324
  const at = () => ({ ...target, data });
@@ -348,12 +351,12 @@ async function advance(req, api, readings, target, key, budgetMs, cloned) {
348
351
  if (s.state !== 'translating' || !isTranslated(data.translations?.[lang]) || Date.now() > deadline + 30_000)
349
352
  continue;
350
353
  try {
351
- const inClones = await cloned();
352
- const tracks = await api.speak(data.recordingId, [lang], { cloned: inClones });
354
+ const as = await speakAs();
355
+ const tracks = await api.speak(data.recordingId, [lang], as);
353
356
  const requestedAt = new Date().toISOString();
354
357
  const voice = askedKey(tracks, lang);
355
358
  data = await target.save((current) => ({
356
- speech: { ...current.speech, [lang]: { ...current.speech?.[lang], cast: inClones ? 'cloned' : 'synthetic', error: null, requestedAt, state: 'queued', voice } },
359
+ speech: { ...current.speech, [lang]: { ...current.speech?.[lang], cast: as.cloned ? 'cloned' : 'synthetic', error: null, requestedAt, state: 'queued', voice } },
357
360
  }));
358
361
  }
359
362
  catch (err) {
@@ -447,7 +450,7 @@ function background(payload, collection, options, rowFields, id, where, force =
447
450
  return;
448
451
  await advance(req, new VocalStackAPI(apiKey, options.apiURL ?? DEFAULT_API_URL), readingsSlug(options), target, key, BACKGROUND_MS, async () => {
449
452
  const fresh = await locate(req, collection, options, rowFields, 'admin');
450
- return (await voiceModeOf(req, collection, options, fresh instanceof Response ? target : fresh)).mode === 'cloned';
453
+ return (await voiceModeOf(req, collection, options, fresh instanceof Response ? target : fresh)).as;
451
454
  });
452
455
  };
453
456
  const run = () => work()
@@ -626,12 +629,12 @@ export function speechEndpoints(collection, options, rowFields) {
626
629
  const later = asked.langs.filter((l) => !ready.includes(l));
627
630
  let data = target.data;
628
631
  if (ready.length) {
629
- const cloned = (await voiceModeOf(req, collection, options, target)).mode === 'cloned';
630
- const tracks = await api.speak(target.data.recordingId, ready, { cloned });
632
+ const { as } = await voiceModeOf(req, collection, options, target);
633
+ const tracks = await api.speak(target.data.recordingId, ready, as);
631
634
  for (const lang of ready)
632
635
  await dropReading(req, readings, data.speech?.[lang]);
633
636
  const requestedAt = new Date().toISOString();
634
- const cast = cloned ? 'cloned' : 'synthetic';
637
+ const cast = as.cloned ? 'cloned' : 'synthetic';
635
638
  data = await target.save((current) => ({
636
639
  speech: {
637
640
  ...current.speech,
@@ -659,7 +662,8 @@ export function speechEndpoints(collection, options, rowFields) {
659
662
  const target = await locate(req, collection, options, rowFields, 'user');
660
663
  if (target instanceof Response)
661
664
  return target;
662
- const voiceMode = await voiceModeOf(req, collection, options, target);
665
+ const { fixed, mode } = await voiceModeOf(req, collection, options, target);
666
+ const voiceMode = { fixed, mode };
663
667
  const answer = (vocalstack) => json({ vocalstack, voiceMode });
664
668
  if (!target.data.recordingId || !hasWork(target.data, readings))
665
669
  return answer(target.data);
@@ -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;