@vocalstack/payload 0.8.1 → 0.9.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
@@ -33,12 +33,12 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
33
33
  - a `vocalstack` group:
34
34
  - `transcript`: text you can edit; paragraphs break on a speaker change or a pause.
35
35
  - `sentences`: `[{ start, end, speaker, text }]` in seconds.
36
- - `status`, `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
36
+ - `status`, `language`, `error`, `transcriptionId` and `transcribedAt` (and `recordingId`, which documents transcribed before 0.9.0 keep; everything is read by `transcriptionId`).
37
37
  - `POST /api/{collection}/:id/vocalstack/transcribe`, `POST …/vocalstack/stop`, `GET …/vocalstack/status` and `GET …/vocalstack/stream` (live progress as Server-Sent Events).
38
- - **Translations and readings**, under every finished transcript: translate it into up to 10 of VocalStack's 100 languages (VocalStack's limit per recording), and have each translation read aloud where VocalStack has a voice for it. VocalStack picks the voices; a toggle on each transcript chooses between **synthetic** voices and the speakers' own **cloned** voices (where they have one, made with their permission), saved as `voices`. One click in the admin does both; the server carries on until it is done, with no one watching. Saved in the `vocalstack` group as:
38
+ - **Translations and readings**, under every finished transcript: translate it into up to 10 of VocalStack's 100 languages (VocalStack's limit per transcription), and have each translation read aloud where VocalStack has a voice for it. VocalStack picks the voices; a toggle on each transcript chooses between **synthetic** voices and the speakers' own **cloned** voices (where they have one, made with their permission), saved as `voices`. One click in the admin does both; the server carries on until it is done, with no one watching. Saved in the `vocalstack` group as:
39
39
  - `translations`: `{ [lang]: { translatedAt, sentences, pending?, error?, requestedAt? } }`, the transcript's sentences (same ids and times) translated. `pending` while the server is still translating it.
40
40
  - `speech`: `{ [lang]: { voice, cast, readIn, state, error, durationS, requestedAt, renderedAt, sentences, audio } }`. `state` is `translating` (waiting for its translation), `queued`, `running`, `failed` or `sealed`; once sealed, `sentences` are the translation in the reading's own timing, with words, for a read-along player, and `audio` is the MP3 kept in your storage.
41
- - `POST …/vocalstack/voices { voices: 'synthetic' | 'cloned' }`, `POST …/vocalstack/request { langs, speak? }` (translate, and read aloud unless `speak: false`; carried on by the server), `POST …/vocalstack/translate { langs }` (one step; answers `more: true` when it stopped for time), `DELETE …/vocalstack/translate?lang=`, `POST …/vocalstack/speak { langs }`, `GET …/vocalstack/speak`, and the public `GET …/vocalstack/audio?lang=`, which redirects to the reading's MP3 (or, with no `lang` or the spoken one, the recording's audio) for anyone who may read the document.
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 transcribed 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
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 a VocalStack workspace. It shows the workspace the site works in, with its name and icon, and **Change** picks another. The key is stored server-side and is unreadable over the REST and GraphQL APIs.
@@ -103,17 +103,17 @@ vocalstackPlugin({
103
103
  speakers: [
104
104
  {
105
105
  collection: 'speakers',
106
- // Recordings this speaker is in, offered as the sample to clone from.
107
- recordings: async ({ doc, req }) => {
106
+ // Transcriptions this speaker is in, offered as the sample to clone from.
107
+ transcriptions: async ({ doc, req }) => {
108
108
  const { docs } = await req.payload.find({ collection: 'episodes', where: { speaker: { equals: doc.id } }, req })
109
- return docs.flatMap((e) => (e.vocalstack?.recordingId ? [{ label: e.title, recordingId: e.vocalstack.recordingId, sentences: e.vocalstack.sentences, transcriptionId: e.vocalstack.transcriptionId }] : []))
109
+ return docs.flatMap((e) => (e.vocalstack?.transcriptionId ? [{ label: e.title, sentences: e.vocalstack.sentences, transcriptionId: e.vocalstack.transcriptionId }] : []))
110
110
  },
111
111
  },
112
112
  ],
113
113
  })
114
114
  ```
115
115
 
116
- 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.
116
+ A sample from a transcription can only come from the ones `transcriptions` returns for that document: cloning, and hearing a stretch first (`GET /:id/vocalstack/speaker/clip?transcription=`), refuse any other. Each source needs its `transcriptionId`. Before 0.9.0 this option was called `recordings` and keyed by `recordingId`; `recordings` still works, but sources that carry only a `recordingId` are left out, because VocalStack no longer looks transcripts up by recording.
117
117
 
118
118
  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.
119
119
 
@@ -151,11 +151,11 @@ export async function up({ payload, req }: MigrateUpArgs) {
151
151
 
152
152
  ### Translations and readings
153
153
 
154
- 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).
154
+ 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 transcription 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 transcription) 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).
155
155
 
156
156
  **Everything is asked for once and kept.** The transcript (text, sentences, word times) and each translation are saved on the document. Translating again only asks for sentences that have none, and reads ones VocalStack already translated back from `/transcript?lang=` rather than translating them again. A finished reading's MP3 is downloaded once and saved as an upload in the `vocalstack-readings` collection (option `readings`), so listeners are served from your storage: `GET …/vocalstack/audio` redirects to that file, or for the spoken language to your own audio file, and only falls back to VocalStack while a reading isn't kept yet. Point your storage adapter at the readings collection, e.g. `s3Storage({ collections: { 'vocalstack-readings': { prefix: 'readings', disablePayloadAccessControl: true } } })` for direct public URLs.
157
157
 
158
- **The readings collection.** By default the plugin adds `vocalstack-readings`: public read, and create, update and delete for signed-in users. Change it with `readings: { overrides: (collection) => ({ ...collection, access: { ... } }) }`, or define an upload collection with that slug (or `readings.slug`) yourself; the plugin then uses yours as it is. It needs to accept `audio/mpeg` and to have text fields `lang`, `recordingId` and `voice`.
158
+ **The readings collection.** By default the plugin adds `vocalstack-readings`: public read, and create, update and delete for signed-in users. Change it with `readings: { overrides: (collection) => ({ ...collection, access: { ... } }) }`, or define an upload collection with that slug (or `readings.slug`) yourself; the plugin then uses yours as it is. It needs to accept `audio/mpeg` and to have text fields `lang`, `transcriptionId` and `voice` (readings kept before 0.9.0 are found by a `recordingId` field, where the collection has one).
159
159
 
160
160
  ### Languages for listeners
161
161
 
package/dist/api.d.ts CHANGED
@@ -19,7 +19,6 @@ export type Job = {
19
19
  processedS?: number;
20
20
  totalS?: null | number;
21
21
  };
22
- recordingId: string;
23
22
  state: JobState;
24
23
  transcriptionId: string;
25
24
  };
@@ -71,7 +70,7 @@ export type VoiceOption = {
71
70
  quality: number;
72
71
  ready?: boolean;
73
72
  };
74
- /** A recording's spoken translation in one language, in one cast of voices. */
73
+ /** A transcription's spoken translation in one language, in one cast of voices. */
75
74
  export type VoiceTrack = {
76
75
  /** Seconds each sentence's clip lasts, by sentence id. */
77
76
  clipDur?: Record<string, number>;
@@ -107,7 +106,7 @@ export type Languages = {
107
106
  voice: string[];
108
107
  };
109
108
  export declare const UNAVAILABLE = "VocalStack is unavailable, try again shortly.";
110
- /** A stored recording the connected key cannot see: made in another workspace (the workspace was changed), or deleted. */
109
+ /** A stored transcription the connected key cannot see: made in another workspace (the workspace was changed), or deleted. */
111
110
  export declare const NOT_IN_WORKSPACE = "This transcript is not in the connected VocalStack workspace: it was made in another workspace, or deleted in VocalStack. Transcribe the file again to work with it here.";
112
111
  export declare class VocalStackAPIError extends Error {
113
112
  code: string;
@@ -129,18 +128,18 @@ export declare class VocalStackAPI {
129
128
  name: string;
130
129
  spokenLanguage?: string;
131
130
  }): Promise<Transcription>;
132
- job(recordingId: string): Promise<Job>;
131
+ job(transcriptionId: string): Promise<Job>;
133
132
  /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
134
- stop(recordingId: string, reason?: string): Promise<unknown>;
135
- transcript(recordingId: string): Promise<Transcript>;
133
+ stop(transcriptionId: string, reason?: string): Promise<unknown>;
134
+ transcript(transcriptionId: string): Promise<Transcript>;
136
135
  /**
137
136
  * The translations VocalStack already holds for `lang`, by sentence id. `/translation`
138
137
  * answers only the sentences it translates in that call, so stored ones are read here.
139
138
  */
140
- storedTranslations(recordingId: string, lang: string): Promise<Record<string, string>>;
139
+ storedTranslations(transcriptionId: string, lang: string): Promise<Record<string, string>>;
141
140
  languages(): Promise<Languages>;
142
141
  /** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
143
- translation(recordingId: string, lang: string, sentenceIds: number[]): Promise<{
142
+ translation(transcriptionId: string, lang: string, sentenceIds: number[]): Promise<{
144
143
  lang: string;
145
144
  translations: Record<string, string>;
146
145
  }>;
@@ -151,17 +150,17 @@ export declare class VocalStackAPI {
151
150
  * everyone in stock voices. Each track says which it got (`voices`: cloned, synthetic or mixed).
152
151
  * A clone only ever reads words its own speaker said.
153
152
  */
154
- speak(recordingId: string, langs: string[], as?: SpeakAs): Promise<VoiceTrack[]>;
155
- voiceTracks(recordingId: string, lang?: string): Promise<VoiceTrack[]>;
156
- /** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
157
- audioURL(recordingId: string, opts: {
153
+ speak(transcriptionId: string, langs: string[], as?: SpeakAs): Promise<VoiceTrack[]>;
154
+ voiceTracks(transcriptionId: string, lang?: string): Promise<VoiceTrack[]>;
155
+ /** An address of the transcription's audio, or of a spoken translation's, that works for an hour or so. */
156
+ audioURL(transcriptionId: string, opts: {
158
157
  format?: 'caf' | 'mp3' | 'ogg';
159
158
  kind: 'delivery' | 'voice';
160
159
  lang?: string;
161
160
  voice?: string;
162
161
  }): Promise<string>;
163
- /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
164
- clip(recordingId: string, startS: number, endS: number): Promise<Response>;
162
+ /** A stretch of the transcription's audio as WAV (16 kHz mono), at most 120 s. */
163
+ clip(transcriptionId: string, startS: number, endS: number): Promise<Response>;
165
164
  savedSpeaker(id: string): Promise<SavedSpeaker>;
166
165
  /** Save a speaker from a recorded sample (30 s or more), cloning their voice. Needs the speaker's permission. */
167
166
  createSpeaker(sample: Blob, fileName: string, meta: {
@@ -169,27 +168,26 @@ export declare class VocalStackAPI {
169
168
  name: string;
170
169
  }, idempotencyKey: string): Promise<SavedSpeaker>;
171
170
  /**
172
- * Save a speaker from stretches of a transcribed recording (5–60 s in all), cloning their voice.
171
+ * Save a speaker from stretches of a transcription (5–60 s in all), cloning their voice.
173
172
  * `draft` makes a trial to hear first; keep it with `keepSpeaker`, or delete it. Saved speakers
174
- * are the ones VocalStack looks for first when it works out who speaks in a new recording.
173
+ * are the ones VocalStack looks for first when it works out who speaks in a new transcription.
175
174
  */
176
175
  speakerFromAppearance(opts: {
177
176
  draft: boolean;
178
177
  name: string;
179
- recordingId: string;
180
178
  spans: {
181
179
  end: number;
182
180
  start: number;
183
181
  }[];
184
182
  speaker: number;
185
- transcriptionId?: string;
183
+ transcriptionId: string;
186
184
  }, idempotencyKey: string): Promise<SavedSpeaker>;
187
185
  /** Keep a trial speaker, as `name`, with the speaker's permission. */
188
186
  keepSpeaker(id: string, name: string): Promise<SavedSpeaker>;
189
187
  deleteSpeaker(id: string): Promise<void>;
190
188
  /** The saved speaker's cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
191
189
  speakerVoicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
192
- availableVoices(lang: string, recordingId?: string): Promise<{
190
+ availableVoices(lang: string, transcriptionId?: string): Promise<{
193
191
  lang: string;
194
192
  voices: VoiceOption[];
195
193
  }>;
package/dist/api.js CHANGED
@@ -24,9 +24,9 @@ function savedSpeakerOf(raw) {
24
24
  const speakerRoutes = new Map();
25
25
  const both = (rest) => ({ speakers: `/v1/speakers${rest}`, voices: `/v1/voices${rest}` });
26
26
  export const UNAVAILABLE = 'VocalStack is unavailable, try again shortly.';
27
- /** A stored recording the connected key cannot see: made in another workspace (the workspace was changed), or deleted. */
27
+ /** A stored transcription the connected key cannot see: made in another workspace (the workspace was changed), or deleted. */
28
28
  export const NOT_IN_WORKSPACE = 'This transcript is not in the connected VocalStack workspace: it was made in another workspace, or deleted in VocalStack. Transcribe the file again to work with it here.';
29
- const isGone = (status, message) => status === 404 && /^no such (recording|transcription|job)\b/i.test(message.trim());
29
+ const isGone = (status, message) => status === 404 && /^no such (transcription|job)\b/i.test(message.trim());
30
30
  export class VocalStackAPIError extends Error {
31
31
  code;
32
32
  status;
@@ -95,9 +95,9 @@ export class VocalStackAPI {
95
95
  transcribeFile(file, fileName, opts) {
96
96
  return call(() => this.sdk.transcriptions.create({ file, fileName, name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }, { idempotencyKey: opts.idempotencyKey }));
97
97
  }
98
- async job(recordingId) {
98
+ async job(transcriptionId) {
99
99
  try {
100
- return await call(() => this.sdk.jobs.get(recordingId));
100
+ return await call(() => this.sdk.transcriptions.job(transcriptionId));
101
101
  }
102
102
  catch (err) {
103
103
  // Any "not found" for a job that was started here means this key cannot see it (a wrong address says "no route").
@@ -107,18 +107,18 @@ export class VocalStackAPI {
107
107
  }
108
108
  }
109
109
  /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
110
- stop(recordingId, reason) {
111
- return call(() => this.sdk.recordings.stop(recordingId, reason));
110
+ stop(transcriptionId, reason) {
111
+ return call(() => this.sdk.transcriptions.stop(transcriptionId, reason));
112
112
  }
113
- transcript(recordingId) {
114
- return call(() => this.sdk.recordings.transcript(recordingId));
113
+ transcript(transcriptionId) {
114
+ return call(() => this.sdk.transcriptions.transcript(transcriptionId));
115
115
  }
116
116
  /**
117
117
  * The translations VocalStack already holds for `lang`, by sentence id. `/translation`
118
118
  * answers only the sentences it translates in that call, so stored ones are read here.
119
119
  */
120
- async storedTranslations(recordingId, lang) {
121
- const t = (await call(() => this.sdk.recordings.transcript(recordingId, { lang })));
120
+ async storedTranslations(transcriptionId, lang) {
121
+ const t = (await call(() => this.sdk.transcriptions.transcript(transcriptionId, { lang })));
122
122
  const out = {};
123
123
  for (const s of t.sentences ?? []) {
124
124
  const text = s.translations?.[lang];
@@ -131,8 +131,8 @@ export class VocalStackAPI {
131
131
  return call(() => this.sdk.languages.list());
132
132
  }
133
133
  /** Sentences translated into `lang`, by sentence id. Untranslated ones are translated now, which takes a while. */
134
- translation(recordingId, lang, sentenceIds) {
135
- return call(() => this.sdk.recordings.translation(recordingId, lang, sentenceIds));
134
+ translation(transcriptionId, lang, sentenceIds) {
135
+ return call(() => this.sdk.transcriptions.translation(transcriptionId, lang, sentenceIds));
136
136
  }
137
137
  /**
138
138
  * Read translations aloud, one job per language. `cloned` reads each speaker in their own cloned
@@ -141,39 +141,24 @@ export class VocalStackAPI {
141
141
  * everyone in stock voices. Each track says which it got (`voices`: cloned, synthetic or mixed).
142
142
  * A clone only ever reads words its own speaker said.
143
143
  */
144
- async speak(recordingId, langs, as = { cloned: false }) {
145
- const ask = { langs, voices: as.cloned ? 'cloned' : 'synthetic' };
146
- // Straight to the API: the SDK on npm (2.0.0-alpha.1) leaves `voices` out of the body.
147
- const res = await call(() => fetch(`${this.#baseURL}/v1/recordings/${encodeURIComponent(recordingId)}/voice`, {
148
- body: JSON.stringify(ask),
149
- headers: { authorization: `Bearer ${this.#apiKey}`, 'content-type': 'application/json' },
150
- method: 'POST',
151
- signal: AbortSignal.timeout(30_000),
152
- }));
153
- const body = (await res.json().catch(() => null));
154
- if (res.ok)
155
- return body;
156
- if (res.status === 502 || res.status === 503 || res.status === 504)
157
- throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
158
- if (isGone(res.status, body?.message ?? ''))
159
- throw new VocalStackAPIError(404, 'not_found', NOT_IN_WORKSPACE);
160
- throw new VocalStackAPIError(res.status, body?.code ?? 'http_error', body?.message ?? `VocalStack answered ${res.status}`);
144
+ speak(transcriptionId, langs, as = { cloned: false }) {
145
+ return call(() => this.sdk.transcriptions.requestVoice(transcriptionId, { langs, voices: as.cloned ? 'cloned' : 'synthetic' }));
161
146
  }
162
- voiceTracks(recordingId, lang) {
163
- return call(() => this.sdk.recordings.voice(recordingId, lang));
147
+ voiceTracks(transcriptionId, lang) {
148
+ return call(() => this.sdk.transcriptions.voice(transcriptionId, lang));
164
149
  }
165
- /** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
166
- async audioURL(recordingId, opts) {
150
+ /** An address of the transcription's audio, or of a spoken translation's, that works for an hour or so. */
151
+ async audioURL(transcriptionId, opts) {
167
152
  const format = opts.format ?? 'mp3';
168
153
  if (opts.kind === 'delivery')
169
- return call(() => this.sdk.recordings.audioUrl(recordingId, { format, kind: 'delivery' }));
154
+ return call(() => this.sdk.transcriptions.audio(transcriptionId, { format, kind: 'delivery' }));
170
155
  // A reading in a named voice: a short-lived media token carries the voice in the address.
171
- const { token } = await call(() => this.sdk.recordings.mediaToken(recordingId));
172
- return this.sdk.recordings.audioSrc(recordingId, { format, kind: 'voice', lang: opts.lang, media: token, voice: opts.voice });
156
+ const { token } = await call(() => this.sdk.transcriptions.mediaToken(transcriptionId));
157
+ return this.sdk.transcriptions.audioSrc(transcriptionId, { format, kind: 'voice', lang: opts.lang, media: token, voice: opts.voice });
173
158
  }
174
- /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
175
- clip(recordingId, startS, endS) {
176
- return call(() => this.sdk.recordings.clip(recordingId, startS, endS));
159
+ /** A stretch of the transcription's audio as WAV (16 kHz mono), at most 120 s. */
160
+ clip(transcriptionId, startS, endS) {
161
+ return call(() => this.sdk.transcriptions.audioClip(transcriptionId, startS, endS));
177
162
  }
178
163
  async #speakerRequest(method, paths, init = {}) {
179
164
  const first = speakerRoutes.get(this.#baseURL) ?? 'speakers';
@@ -226,16 +211,14 @@ export class VocalStackAPI {
226
211
  return this.#speaker('POST', both(''), { form, idempotencyKey });
227
212
  }
228
213
  /**
229
- * Save a speaker from stretches of a transcribed recording (5–60 s in all), cloning their voice.
214
+ * Save a speaker from stretches of a transcription (5–60 s in all), cloning their voice.
230
215
  * `draft` makes a trial to hear first; keep it with `keepSpeaker`, or delete it. Saved speakers
231
- * are the ones VocalStack looks for first when it works out who speaks in a new recording.
216
+ * are the ones VocalStack looks for first when it works out who speaks in a new transcription.
232
217
  */
233
218
  speakerFromAppearance(opts, idempotencyKey) {
234
- const { recordingId, speaker, transcriptionId, ...rest } = opts;
235
- const common = { ...rest, consent: true, library: true };
236
- return this.#speaker('POST', { speakers: transcriptionId ? '/v1/speakers/from-appearance' : undefined, voices: '/v1/voices/from-speaker' }, {
237
- // The spans are times in this recording: name it, or the server takes the latest one the speaker is heard in.
238
- body: (route) => (route === 'speakers' ? { ...common, appearance: speaker, recordingId, transcriptionId } : { ...common, recordingId, speaker }),
219
+ const { speaker, ...rest } = opts;
220
+ return this.#speaker('POST', { speakers: '/v1/speakers/from-appearance' }, {
221
+ body: () => ({ ...rest, appearance: speaker, consent: true, library: true }),
239
222
  idempotencyKey,
240
223
  });
241
224
  }
@@ -256,8 +239,8 @@ export class VocalStackAPI {
256
239
  speakerVoicePreview(id, lang, format = 'ogg') {
257
240
  return this.#speakerRequest('GET', both(`/${encodeURIComponent(id)}/preview`), { audio: true, query: { format, lang } });
258
241
  }
259
- availableVoices(lang, recordingId) {
260
- return call(() => this.sdk.voices.available(lang, { recording: recordingId }));
242
+ availableVoices(lang, transcriptionId) {
243
+ return call(() => this.sdk.voices.available(lang, { transcription: transcriptionId }));
261
244
  }
262
245
  }
263
246
  /** A short label for the connected account, from whatever `/v1/me` carries. */
@@ -199,7 +199,7 @@ export const VoiceFromRecording = ({ base, name, onCreated, sources }) => {
199
199
  setError(undefined);
200
200
  try {
201
201
  const r = await call(`${base}/trial`, {
202
- body: JSON.stringify({ recordingId: source.recordingId, replace: trial?.id, spans: spansOf(clips, picked), speaker }),
202
+ body: JSON.stringify({ replace: trial?.id, spans: spansOf(clips, picked), speaker, transcriptionId: source.transcriptionId }),
203
203
  method: 'POST',
204
204
  });
205
205
  setTrial({ ...r.voice, key: pickKey });
@@ -240,7 +240,7 @@ export const VoiceFromRecording = ({ base, name, onCreated, sources }) => {
240
240
  setSourceIdx(Number(e.target.value));
241
241
  setIdx(0);
242
242
  setPicked(new Set());
243
- }, value: sourceIdx, children: sources.map((s, i) => (_jsx("option", { value: i, children: s.label }, s.recordingId))) })), _jsxs("div", { style: { alignItems: 'baseline', display: 'flex', gap: 8, justifyContent: 'space-between' }, children: [_jsxs("p", { style: muted, children: ["Pick about ", PICK_TARGET_S, "s of clear speech, with no music or other voices."] }), _jsxs("strong", { style: { fontSize: 13, whiteSpace: 'nowrap' }, children: [Math.round(total), "s ", _jsxs("span", { style: { color: 'var(--theme-elevation-500)', fontWeight: 400 }, children: ["/ ", PICK_TARGET_S, "s"] })] })] }), _jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", disabled: chosen || !clips.length, margin: false, onClick: () => setPicked(new Set(best)), size: "small", children: "\u2728 Choose for me" }) }), clip ? (_jsxs("div", { className: "vs-sample", children: [_jsxs("div", { className: "vs-sample-body", children: [_jsxs("div", { className: "vs-sample-head", children: [_jsxs("span", { children: ["Sample ", idx + 1, " of ", clips.length] }), _jsxs("span", { className: "vs-pager", children: [_jsx("button", { "aria-label": "Previous sample", disabled: idx === 0, onClick: () => setIdx((i) => Math.max(0, i - 1)), type: "button", children: "\u2039" }), _jsx("button", { "aria-label": "Next sample", disabled: idx >= clips.length - 1, onClick: () => setIdx((i) => Math.min(clips.length - 1, i + 1)), type: "button", children: "\u203A" })] })] }), _jsx("div", { className: "vs-sample-text", children: clip.text }), _jsx(SampleAudio, { src: `${apiBase}${base}/clip?${new URLSearchParams({ endS: clip.end.toFixed(2), recording: source.recordingId, startS: clip.start.toFixed(2) })}` })] }), _jsxs("label", { className: "vs-sample-use", style: { opacity: room ? 1 : 0.5 }, children: [_jsx("input", { checked: here, disabled: !room, onChange: () => toggle(idx), type: "checkbox" }), room ? 'Use this sample' : `Full: ${PICK_MAX_S}s at most`] })] })) : (_jsx("p", { style: muted, children: "No sentences of theirs in this recording." })), _jsxs("div", { children: [_jsx("div", { className: "vs-meter", children: _jsx("span", { style: { width: meterAt(total) } }) }), _jsx("div", { className: "vs-meter-marks", children: [PICK_MIN_S, PICK_GOOD_S, PICK_TARGET_S].map((s) => (_jsxs("span", { style: { fontWeight: total + 0.05 >= s ? 600 : 400, left: meterAt(s) }, children: [s, "s"] }, s))) })] }), _jsx("p", { style: muted, children: !picked.size
243
+ }, value: sourceIdx, children: sources.map((s, i) => (_jsx("option", { value: i, children: s.label }, s.transcriptionId))) })), _jsxs("div", { style: { alignItems: 'baseline', display: 'flex', gap: 8, justifyContent: 'space-between' }, children: [_jsxs("p", { style: muted, children: ["Pick about ", PICK_TARGET_S, "s of clear speech, with no music or other voices."] }), _jsxs("strong", { style: { fontSize: 13, whiteSpace: 'nowrap' }, children: [Math.round(total), "s ", _jsxs("span", { style: { color: 'var(--theme-elevation-500)', fontWeight: 400 }, children: ["/ ", PICK_TARGET_S, "s"] })] })] }), _jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", disabled: chosen || !clips.length, margin: false, onClick: () => setPicked(new Set(best)), size: "small", children: "\u2728 Choose for me" }) }), clip ? (_jsxs("div", { className: "vs-sample", children: [_jsxs("div", { className: "vs-sample-body", children: [_jsxs("div", { className: "vs-sample-head", children: [_jsxs("span", { children: ["Sample ", idx + 1, " of ", clips.length] }), _jsxs("span", { className: "vs-pager", children: [_jsx("button", { "aria-label": "Previous sample", disabled: idx === 0, onClick: () => setIdx((i) => Math.max(0, i - 1)), type: "button", children: "\u2039" }), _jsx("button", { "aria-label": "Next sample", disabled: idx >= clips.length - 1, onClick: () => setIdx((i) => Math.min(clips.length - 1, i + 1)), type: "button", children: "\u203A" })] })] }), _jsx("div", { className: "vs-sample-text", children: clip.text }), _jsx(SampleAudio, { src: `${apiBase}${base}/clip?${new URLSearchParams({ endS: clip.end.toFixed(2), startS: clip.start.toFixed(2), transcription: source.transcriptionId })}` })] }), _jsxs("label", { className: "vs-sample-use", style: { opacity: room ? 1 : 0.5 }, children: [_jsx("input", { checked: here, disabled: !room, onChange: () => toggle(idx), type: "checkbox" }), room ? 'Use this sample' : `Full: ${PICK_MAX_S}s at most`] })] })) : (_jsx("p", { style: muted, children: "No sentences of theirs in this recording." })), _jsxs("div", { children: [_jsx("div", { className: "vs-meter", children: _jsx("span", { style: { width: meterAt(total) } }) }), _jsx("div", { className: "vs-meter-marks", children: [PICK_MIN_S, PICK_GOOD_S, PICK_TARGET_S].map((s) => (_jsxs("span", { style: { fontWeight: total + 0.05 >= s ? 600 : 400, left: meterAt(s) }, children: [s, "s"] }, s))) })] }), _jsx("p", { style: muted, children: !picked.size
244
244
  ? `At least ${PICK_MIN_S}s makes a voice.`
245
245
  : total + 0.05 < PICK_MIN_S
246
246
  ? `${Math.ceil(PICK_MIN_S - total)}s more to make a voice.`
@@ -53,7 +53,7 @@ async function translate(api, target, lang, deadline) {
53
53
  // What VocalStack translated before (for anyone) costs nothing to read back; only the rest is translated.
54
54
  if (missing.length) {
55
55
  try {
56
- const stored = await api.storedTranslations(target.data.recordingId, lang);
56
+ const stored = await api.storedTranslations(target.data.transcriptionId, lang);
57
57
  for (const id of missing)
58
58
  if (stored[String(id)]?.trim())
59
59
  got.set(id, stored[String(id)].trim());
@@ -90,7 +90,7 @@ async function translate(api, target, lang, deadline) {
90
90
  return;
91
91
  }
92
92
  try {
93
- const { translations } = await api.translation(target.data.recordingId, lang, batch);
93
+ const { translations } = await api.translation(target.data.transcriptionId, lang, batch);
94
94
  for (const [id, text] of Object.entries(translations))
95
95
  if (text?.trim())
96
96
  got.set(Number(id), text.trim());
@@ -137,7 +137,7 @@ async function keepReading(req, api, slug, target, lang, speech) {
137
137
  const keys = [...new Set([speech.voice || undefined, undefined])];
138
138
  let res;
139
139
  for (const voice of keys) {
140
- const src = await api.audioURL(target.data.recordingId, { kind: 'voice', lang, voice });
140
+ const src = await api.audioURL(target.data.transcriptionId, { kind: 'voice', lang, voice });
141
141
  // The first ask makes the MP3 (a long reading takes a while); VocalStack finishes it even
142
142
  // when this gives up, and a later look finds it ready.
143
143
  res = await fetch(src, { signal: AbortSignal.timeout(90_000) });
@@ -154,7 +154,7 @@ async function keepReading(req, api, slug, target, lang, speech) {
154
154
  const data = Buffer.from(await res.arrayBuffer());
155
155
  const doc = (await req.payload.create({
156
156
  collection: slug,
157
- data: { lang, recordingId: target.data.recordingId, voice: speech.voice ?? '' },
157
+ data: { lang, transcriptionId: target.data.transcriptionId, voice: speech.voice ?? '' },
158
158
  file: { data, mimetype: 'audio/mpeg', name: readingName(target, lang, speech.voice), size: data.length },
159
159
  overrideAccess: true,
160
160
  req,
@@ -169,19 +169,19 @@ async function dropReading(req, slug, speech) {
169
169
  return;
170
170
  await req.payload.delete({ collection: slug, id: speech.audio.id, overrideAccess: true, req }).catch(() => { });
171
171
  }
172
- /** Delete kept readings of this recording, in these languages, that the field does not point to. */
172
+ /** Delete kept readings of this transcription, in these languages, that the field does not point to. */
173
173
  async function sweepReadings(req, slug, data, langs) {
174
- if (!data.recordingId || !langs.length)
174
+ if (!data.transcriptionId || !langs.length)
175
175
  return;
176
- const found = await req.payload.find({
177
- collection: slug,
178
- depth: 0,
179
- limit: 50,
180
- overrideAccess: true,
181
- pagination: false,
182
- req,
183
- where: { and: [{ recordingId: { equals: data.recordingId } }, { lang: { in: langs } }] },
184
- });
176
+ // Readings saved before 0.9.0 carry the old `recordingId` of the same transcript instead; a host's own collection may have no such field.
177
+ const keys = [{ transcriptionId: { equals: data.transcriptionId } }, ...(data.recordingId ? [{ recordingId: { equals: data.recordingId } }] : [])];
178
+ const found = { docs: [] };
179
+ for (const key of keys) {
180
+ const page = await req.payload
181
+ .find({ collection: slug, depth: 0, limit: 50, overrideAccess: true, pagination: false, req, where: { and: [key, { lang: { in: langs } }] } })
182
+ .catch(() => undefined);
183
+ found.docs.push(...(page?.docs ?? []));
184
+ }
185
185
  const keep = new Set(langs.map((l) => data.speech?.[l]?.audio?.id).filter((id) => id !== undefined).map(String));
186
186
  for (const doc of found.docs)
187
187
  if (!keep.has(String(doc.id)))
@@ -266,11 +266,11 @@ const hasWork = (data, readings) => {
266
266
  */
267
267
  async function refresh(req, api, readings, target, key) {
268
268
  const { pending, unkept } = waiting(target.data, readings);
269
- if ((!pending.length && !unkept.length) || !target.data.recordingId)
269
+ if ((!pending.length && !unkept.length) || !target.data.transcriptionId)
270
270
  return target.data;
271
271
  const next = {};
272
272
  if (pending.length) {
273
- const tracks = await api.voiceTracks(target.data.recordingId);
273
+ const tracks = await api.voiceTracks(target.data.transcriptionId);
274
274
  for (const [lang, speech] of pending) {
275
275
  const settled = settle(speech, trackFor(tracks, lang, speech), target.data.translations?.[lang]);
276
276
  if (settled.state !== speech.state || settled.error !== speech.error || settled.done !== speech.done)
@@ -357,7 +357,7 @@ async function advance(req, api, readings, target, key, budgetMs, speakAs) {
357
357
  continue;
358
358
  try {
359
359
  const as = await speakAs();
360
- const tracks = await api.speak(data.recordingId, [lang], as);
360
+ const tracks = await api.speak(data.transcriptionId, [lang], as);
361
361
  const requestedAt = new Date().toISOString();
362
362
  const voice = askedKey(tracks, lang);
363
363
  data = await target.save((current) => ({
@@ -480,7 +480,7 @@ const rowOf = (req) => {
480
480
  * response, so a translation or reading is ready for listeners without an editor watching.
481
481
  */
482
482
  export function refreshAfterRead(payload, collection, options, rowFields, id, data, where) {
483
- if (!data?.recordingId || !hasWork(data, readingsSlug(options)))
483
+ if (!data?.transcriptionId || !hasWork(data, readingsSlug(options)))
484
484
  return;
485
485
  background(payload, collection, options, rowFields, id, where);
486
486
  }
@@ -517,7 +517,7 @@ export function speechEndpoints(collection, options, rowFields) {
517
517
  const target = await locate(req, collection, options, rowFields, 'admin');
518
518
  if (target instanceof Response)
519
519
  return target;
520
- if (target.data.status !== 'done' || !target.data.recordingId)
520
+ if (target.data.status !== 'done' || !target.data.transcriptionId)
521
521
  return json({ error: 'Transcribe the audio first.' }, 409);
522
522
  return { api: new VocalStackAPI(apiKey, apiURL), target };
523
523
  };
@@ -635,7 +635,7 @@ export function speechEndpoints(collection, options, rowFields) {
635
635
  let data = target.data;
636
636
  if (ready.length) {
637
637
  const { as } = await voiceModeOf(req, collection, options, target);
638
- const tracks = await api.speak(target.data.recordingId, ready, as);
638
+ const tracks = await api.speak(target.data.transcriptionId, ready, as);
639
639
  for (const lang of ready)
640
640
  await dropReading(req, readings, data.speech?.[lang]);
641
641
  const requestedAt = new Date().toISOString();
@@ -670,7 +670,7 @@ export function speechEndpoints(collection, options, rowFields) {
670
670
  const { fixed, mode } = await voiceModeOf(req, collection, options, target);
671
671
  const voiceMode = { fixed, mode };
672
672
  const answer = (vocalstack) => json({ vocalstack, voiceMode });
673
- if (!target.data.recordingId || !hasWork(target.data, readings))
673
+ if (!target.data.transcriptionId || !hasWork(target.data, readings))
674
674
  return answer(target.data);
675
675
  // Translating goes on in the background; readings are looked at now.
676
676
  if (waiting(target.data, readings).translating.length)
@@ -696,8 +696,8 @@ export function speechEndpoints(collection, options, rowFields) {
696
696
  const target = await locate(req, collection, options, rowFields, 'user');
697
697
  if (target instanceof Response)
698
698
  return target;
699
- const { language, recordingId, speech } = target.data;
700
- if (!recordingId)
699
+ const { language, transcriptionId, speech } = target.data;
700
+ if (!transcriptionId)
701
701
  return json({ error: 'No audio.' }, 404);
702
702
  const lang = req.searchParams.get('lang')?.toLowerCase();
703
703
  const spoken = !lang || lang === language;
@@ -713,7 +713,7 @@ export function speechEndpoints(collection, options, rowFields) {
713
713
  if (!apiKey)
714
714
  return json({ error: 'Not available.' }, 404);
715
715
  try {
716
- const url = await new VocalStackAPI(apiKey, apiURL).audioURL(recordingId, spoken ? { kind: 'delivery' } : { kind: 'voice', lang, voice: reading?.voice ?? undefined });
716
+ const url = await new VocalStackAPI(apiKey, apiURL).audioURL(transcriptionId, spoken ? { kind: 'delivery' } : { kind: 'voice', lang, voice: reading?.voice ?? undefined });
717
717
  // The signed address lasts a while; hand out the same one for a few minutes.
718
718
  return new Response(null, { headers: { 'cache-control': 'public, max-age=300, s-maxage=300', location: url }, status: 302 });
719
719
  }
@@ -730,7 +730,7 @@ export function speechEndpoints(collection, options, rowFields) {
730
730
  const target = await locate(req, collection, options, rowFields, 'user');
731
731
  if (target instanceof Response)
732
732
  return target;
733
- if (target.data.status !== 'done' || !target.data.recordingId)
733
+ if (target.data.status !== 'done' || !target.data.transcriptionId)
734
734
  return json({ error: 'There is no transcript to translate yet.' }, 409);
735
735
  return target;
736
736
  };
@@ -25,8 +25,8 @@ export function streamEndpoint(collection, options, rowFields) {
25
25
  const target = await locate(req, collection, options, rowFields, 'user');
26
26
  if (target instanceof Response)
27
27
  return target;
28
- const recordingId = target.data.recordingId;
29
- if (target.data.status !== 'processing' || !recordingId)
28
+ const transcriptionId = target.data.transcriptionId;
29
+ if (target.data.status !== 'processing' || !transcriptionId)
30
30
  return Response.json({ status: target.data.status ?? 'idle', vocalstack: target.data });
31
31
  const apiKey = await resolveAPIKey(req, options);
32
32
  if (!apiKey)
@@ -57,7 +57,7 @@ export function streamEndpoint(collection, options, rowFields) {
57
57
  };
58
58
  // VocalStack signals the end several ways (progress, state, socket close); check once at a time.
59
59
  let settling;
60
- const settle = () => (settling ??= checkJob(api, target, recordingId)
60
+ const settle = () => (settling ??= checkJob(api, target, transcriptionId)
61
61
  .then((r) => (r.status === 'processing' ? undefined : finish(r)), (err) => finish({ error: err.message, status: 'failed' }))
62
62
  .finally(() => (settling = undefined)));
63
63
  // What the page has been told: settled sentences by id, the words of committed
@@ -83,7 +83,7 @@ export function streamEndpoint(collection, options, rowFields) {
83
83
  };
84
84
  controller.enqueue(encoder.encode('retry: 2000\n\n'));
85
85
  heartbeat = setInterval(() => !closed && controller.enqueue(encoder.encode(': ping\n\n')), 15000);
86
- const wsURL = `${apiURL.replace(/^http/, 'ws')}/v1/recordings/${encodeURIComponent(recordingId)}/subscribe`;
86
+ const wsURL = `${apiURL.replace(/^http/, 'ws')}/v1/transcriptions/${encodeURIComponent(transcriptionId)}/subscribe`;
87
87
  // Node's WebSocket (undici) takes headers, which the DOM type does not know about.
88
88
  socket = new WebSocket(wsURL, { headers: { authorization: `Bearer ${apiKey}` } });
89
89
  socket.onmessage = (message) => {
@@ -115,7 +115,7 @@ export function streamEndpoint(collection, options, rowFields) {
115
115
  if (frame.type === 'subscribe.ready') {
116
116
  // Catch up on everything said before the socket opened. Live frames that
117
117
  // arrive meanwhile update the same maps by id, so the overlap is harmless.
118
- void api.transcript(recordingId).then((t) => {
118
+ void api.transcript(transcriptionId).then((t) => {
119
119
  for (const g of t.segments ?? [])
120
120
  if (!g.suppressed && g.words)
121
121
  segmentWords.set(g.seq, g.words);
@@ -24,7 +24,7 @@ export declare function apiError(err: unknown): Response;
24
24
  * Where a job stands, saving the outcome on the document once it is over: the
25
25
  * whole transcript when done, the reason when it failed.
26
26
  */
27
- export declare function checkJob(api: VocalStackAPI, target: Target, recordingId: string): Promise<StatusResponse>;
27
+ export declare function checkJob(api: VocalStackAPI, target: Target, transcriptionId: string): Promise<StatusResponse>;
28
28
  /**
29
29
  * POST /:id/vocalstack/transcribe and GET /:id/vocalstack/status. With no query
30
30
  * they act on the upload document itself; with `?field=<array>&row=<row id>` on one row.
@@ -117,10 +117,10 @@ export function apiError(err) {
117
117
  * Where a job stands, saving the outcome on the document once it is over: the
118
118
  * whole transcript when done, the reason when it failed.
119
119
  */
120
- export async function checkJob(api, target, recordingId) {
120
+ export async function checkJob(api, target, transcriptionId) {
121
121
  let job;
122
122
  try {
123
- job = await api.job(recordingId);
123
+ job = await api.job(transcriptionId);
124
124
  }
125
125
  catch (err) {
126
126
  if (!(err instanceof VocalStackAPIError && err.message === NOT_IN_WORKSPACE))
@@ -140,14 +140,14 @@ export async function checkJob(api, target, recordingId) {
140
140
  if (job.state !== 'transcribing')
141
141
  return { phase: job.progress.phase ?? job.state, progress, status: 'processing' };
142
142
  // Sentences are readable while the job runs; send what is there so far.
143
- const partial = await api.transcript(recordingId).then(toSentences, () => undefined);
143
+ const partial = await api.transcript(transcriptionId).then(toSentences, () => undefined);
144
144
  return { audio: { processedS: job.progress.processedS ?? 0, totalS: job.progress.totalS ?? undefined }, partial, phase: 'transcribing', progress, status: 'processing' };
145
145
  }
146
- let saving = finishing.get(recordingId);
146
+ let saving = finishing.get(transcriptionId);
147
147
  if (!saving) {
148
- saving = saveTranscript(api, target, recordingId);
149
- finishing.set(recordingId, saving);
150
- void saving.catch(() => undefined).then(() => finishing.delete(recordingId));
148
+ saving = saveTranscript(api, target, transcriptionId);
149
+ finishing.set(transcriptionId, saving);
150
+ void saving.catch(() => undefined).then(() => finishing.delete(transcriptionId));
151
151
  }
152
152
  return saving;
153
153
  }
@@ -160,14 +160,14 @@ async function restore(target) {
160
160
  const status = target.data.transcript ? 'done' : 'idle';
161
161
  return { status, stopped: true, vocalstack: await target.save({ error: null, status }) };
162
162
  }
163
- async function saveTranscript(api, target, recordingId) {
164
- const transcript = await api.transcript(recordingId);
163
+ async function saveTranscript(api, target, transcriptionId) {
164
+ const transcript = await api.transcript(transcriptionId);
165
165
  const sentences = toSentences(transcript);
166
166
  const vocalstack = await target.save({
167
167
  error: null,
168
168
  language: transcript.lang ?? transcript.sentences.find((s) => s.language)?.language ?? null,
169
169
  sentences,
170
- // A new recording: translations and readings of the old one no longer match it.
170
+ // A new transcript: translations and readings of the old one no longer match it.
171
171
  speech: null,
172
172
  status: 'done',
173
173
  transcribedAt: new Date().toISOString(),
@@ -211,7 +211,7 @@ export function transcribeEndpoints(collection, options, rowFields) {
211
211
  : await api.transcribeFile(await fetchFile(req, url), decodeURIComponent(new URL(url).pathname.split('/').pop() || target.fileName), call);
212
212
  if (!tx.job)
213
213
  throw new Error('VocalStack did not start a job for this file.');
214
- const vocalstack = await target.save({ error: null, recordingId: tx.job.recordingId, status: 'processing', transcriptionId: tx.id });
214
+ const vocalstack = await target.save({ error: null, recordingId: null, status: 'processing', transcriptionId: tx.id });
215
215
  return json({ phase: tx.job.state, progress: 0, status: 'processing', vocalstack }, 202);
216
216
  }
217
217
  catch (err) {
@@ -230,13 +230,13 @@ export function transcribeEndpoints(collection, options, rowFields) {
230
230
  if (target instanceof Response)
231
231
  return target;
232
232
  const field = target.data;
233
- if (field.status !== 'processing' || !field.recordingId)
233
+ if (field.status !== 'processing' || !field.transcriptionId)
234
234
  return json({ status: field.status ?? 'idle', vocalstack: field });
235
235
  const apiKey = await resolveAPIKey(req, options);
236
236
  if (!apiKey)
237
237
  return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
238
238
  try {
239
- return json(await checkJob(new VocalStackAPI(apiKey, apiURL), target, field.recordingId));
239
+ return json(await checkJob(new VocalStackAPI(apiKey, apiURL), target, field.transcriptionId));
240
240
  }
241
241
  catch (err) {
242
242
  return apiError(err);
@@ -258,18 +258,18 @@ export function transcribeEndpoints(collection, options, rowFields) {
258
258
  const target = await locate(req, collection, options, rowFields, 'admin');
259
259
  if (target instanceof Response)
260
260
  return target;
261
- const { recordingId, status } = target.data;
262
- if (status !== 'processing' || !recordingId)
261
+ const { transcriptionId, status } = target.data;
262
+ if (status !== 'processing' || !transcriptionId)
263
263
  return json({ status: status ?? 'idle', vocalstack: target.data });
264
264
  const api = new VocalStackAPI(apiKey, apiURL);
265
265
  try {
266
- await api.stop(recordingId, 'Stopped from Payload');
266
+ await api.stop(transcriptionId, 'Stopped from Payload');
267
267
  return json(await restore(target));
268
268
  }
269
269
  catch (err) {
270
270
  // Too late to stop: the job ended meanwhile, so take its outcome instead.
271
271
  if (err instanceof VocalStackAPIError && err.status === 409)
272
- return json(await checkJob(api, target, recordingId).catch(() => restore(target)));
272
+ return json(await checkJob(api, target, transcriptionId).catch(() => restore(target)));
273
273
  return apiError(err);
274
274
  }
275
275
  },
@@ -14,17 +14,17 @@ export declare const legacyVoiceData: ({ cloneId, speakerId, ...rest }: SpeakerF
14
14
  /**
15
15
  * A person saved as a VocalStack speaker, with their cloned voice, kept in the `vocalstackSpeaker` group of their document:
16
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 },
17
+ * POST /:id/vocalstack/speaker save and clone them: JSON { transcriptionId, startS, endS, consent },
18
18
  * or multipart with a `file` sample and `_payload` { consent }
19
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=)
20
+ * GET /:id/vocalstack/speaker/sources transcriptions to take the sample from
21
+ * GET /:id/vocalstack/speaker/clip a stretch of one of them, to hear before cloning (?transcription=&startS=&endS=)
22
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? }
23
+ * POST /:id/vocalstack/speaker/trial a trial from picked sentences { transcriptionId, speaker, spans, replace? }
24
24
  * GET /:id/vocalstack/speaker/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
25
25
  * POST /:id/vocalstack/speaker/trial/keep { voice, name, consent } keep it as their speaker; DELETE …/trial?voice= drop it
26
26
  * Each also answers under /:id/vocalstack/voice…, its path in 0.5.
27
- * A sample is only ever taken from the recordings `config.recordings` offers for that document.
27
+ * A sample is only ever taken from the transcriptions `config.transcriptions` offers for that document.
28
28
  */
29
29
  export declare function speakerEndpoints(config: SpeakerCollectionConfig, options: VocalStackPluginOptions): Endpoint[];
30
30
  /**
@@ -67,17 +67,17 @@ export const legacyVoiceData = ({ cloneId, speakerId, ...rest }) => ({ ...rest,
67
67
  /**
68
68
  * A person saved as a VocalStack speaker, with their cloned voice, kept in the `vocalstackSpeaker` group of their document:
69
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 },
70
+ * POST /:id/vocalstack/speaker save and clone them: JSON { transcriptionId, startS, endS, consent },
71
71
  * or multipart with a `file` sample and `_payload` { consent }
72
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=)
73
+ * GET /:id/vocalstack/speaker/sources transcriptions to take the sample from
74
+ * GET /:id/vocalstack/speaker/clip a stretch of one of them, to hear before cloning (?transcription=&startS=&endS=)
75
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? }
76
+ * POST /:id/vocalstack/speaker/trial a trial from picked sentences { transcriptionId, speaker, spans, replace? }
77
77
  * GET /:id/vocalstack/speaker/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
78
78
  * POST /:id/vocalstack/speaker/trial/keep { voice, name, consent } keep it as their speaker; DELETE …/trial?voice= drop it
79
79
  * Each also answers under /:id/vocalstack/voice…, its path in 0.5.
80
- * A sample is only ever taken from the recordings `config.recordings` offers for that document.
80
+ * A sample is only ever taken from the transcriptions `config.transcriptions` offers for that document.
81
81
  */
82
82
  export function speakerEndpoints(config, options) {
83
83
  const { collection } = config;
@@ -96,8 +96,10 @@ export function speakerEndpoints(config, options) {
96
96
  return json({ error: 'Not found.' }, 404);
97
97
  return { api: new VocalStackAPI(apiKey, apiURL), doc, id };
98
98
  };
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);
99
+ /** The transcriptions the host offers for this person. A source with only a recording id (before 0.9.0) cannot be read any more and is left out. */
100
+ const sourcesOf = async (req, doc) => ((await (config.transcriptions ?? config.recordings)?.({ doc, req })) ?? []).filter((s) => typeof s?.transcriptionId === 'string' && s.transcriptionId !== '');
101
+ /** The transcription, when the host offers it for this person. */
102
+ const ownSource = async (req, doc, transcriptionId) => (await sourcesOf(req, doc)).find((s) => s.transcriptionId === transcriptionId);
101
103
  const save = async (req, id, data) => {
102
104
  await req.payload.update({ id, collection, data: { vocalstackSpeaker: data, vocalstackVoice: legacyVoiceData(data) }, depth: 0, overrideAccess: true, req });
103
105
  return data;
@@ -158,14 +160,14 @@ export function speakerEndpoints(config, options) {
158
160
  const body = (await req.json?.().catch(() => ({})));
159
161
  consent = body.consent === true;
160
162
  const [startS, endS] = [Number(body.startS), Number(body.endS)];
161
- if (typeof body.recordingId !== 'string' || !(endS - startS >= MIN_SAMPLE_S - 1.5 && endS - startS <= MAX_SAMPLE_S)) {
162
- return json({ error: `Pick ${MIN_SAMPLE_S} to ${MAX_SAMPLE_S} seconds of a recording.` }, 400);
163
+ if (typeof body.transcriptionId !== 'string' || !(endS - startS >= MIN_SAMPLE_S - 1.5 && endS - startS <= MAX_SAMPLE_S)) {
164
+ return json({ error: `Pick ${MIN_SAMPLE_S} to ${MAX_SAMPLE_S} seconds of a transcription.` }, 400);
163
165
  }
164
166
  if (!consent)
165
167
  return json({ error: 'Confirm you have their permission to clone their voice.' }, 400);
166
- if (!(await ownRecording(req, doc, body.recordingId)))
167
- return json({ error: 'That recording is not one of theirs.' }, 403);
168
- const clip = await api.clip(body.recordingId, startS, endS);
168
+ if (!(await ownSource(req, doc, body.transcriptionId)))
169
+ return json({ error: 'That transcription is not one of theirs.' }, 403);
170
+ const clip = await api.clip(body.transcriptionId, startS, endS);
169
171
  sample = { blob: await clip.blob(), name: 'sample.wav' };
170
172
  }
171
173
  if (!consent)
@@ -210,11 +212,11 @@ export function speakerEndpoints(config, options) {
210
212
  const found = await open(req, 'create');
211
213
  if (found instanceof Response)
212
214
  return found;
213
- const sources = (await config.recordings?.({ doc: found.doc, req })) ?? [];
215
+ const sources = await sourcesOf(req, found.doc);
214
216
  return json({
215
- sources: sources.map(({ label, recordingId, sentences }) => ({
217
+ sources: sources.map(({ label, sentences, transcriptionId }) => ({
216
218
  label,
217
- recordingId,
219
+ transcriptionId,
218
220
  sentences: (sentences ?? []).filter((s) => !s.draft).map(({ end, id, speaker, start, text }) => ({ end, id, speaker, start, text })),
219
221
  })),
220
222
  });
@@ -227,14 +229,14 @@ export function speakerEndpoints(config, options) {
227
229
  const found = await open(req, 'create');
228
230
  if (found instanceof Response)
229
231
  return found;
230
- const recording = req.searchParams.get('recording');
232
+ const transcription = req.searchParams.get('transcription');
231
233
  const [startS, endS] = [Number(req.searchParams.get('startS')), Number(req.searchParams.get('endS'))];
232
- if (!recording || !(endS > startS) || endS - startS > MAX_SAMPLE_S)
234
+ if (!transcription || !(endS > startS) || endS - startS > MAX_SAMPLE_S)
233
235
  return json({ error: `At most ${MAX_SAMPLE_S} seconds.` }, 400);
234
- if (!(await ownRecording(req, found.doc, recording)))
235
- return json({ error: 'That recording is not one of theirs.' }, 403);
236
+ if (!(await ownSource(req, found.doc, transcription)))
237
+ return json({ error: 'That transcription is not one of theirs.' }, 403);
236
238
  try {
237
- const res = await found.api.clip(recording, startS, endS);
239
+ const res = await found.api.clip(transcription, startS, endS);
238
240
  return new Response(res.body, { headers: { 'cache-control': 'private, max-age=3600', 'content-type': 'audio/wav' } });
239
241
  }
240
242
  catch (err) {
@@ -243,7 +245,7 @@ export function speakerEndpoints(config, options) {
243
245
  },
244
246
  },
245
247
  {
246
- // A trial voice from sentences of one of their recordings, to hear before keeping it.
248
+ // A trial voice from sentences of one of their transcriptions, to hear before keeping it.
247
249
  method: 'post',
248
250
  path: '/:id/vocalstack/speaker/trial',
249
251
  handler: async (req) => {
@@ -256,16 +258,14 @@ export function speakerEndpoints(config, options) {
256
258
  .map((s) => ({ end: Number(s?.end), start: Number(s?.start) }))
257
259
  .filter((s) => Number.isFinite(s.start) && s.end > s.start);
258
260
  const total = spans.reduce((t, s) => t + (s.end - s.start), 0);
259
- if (typeof body.recordingId !== 'string' || !Number.isInteger(body.speaker) || total < PICK_MIN_S - 0.05 || total > PICK_MAX_S + 0.5) {
261
+ if (typeof body.transcriptionId !== 'string' || !Number.isInteger(body.speaker) || total < PICK_MIN_S - 0.05 || total > PICK_MAX_S + 0.5) {
260
262
  return json({ error: `Pick ${PICK_MIN_S} to ${PICK_MAX_S} seconds of their speech.` }, 400);
261
263
  }
262
- const source = await ownRecording(req, doc, body.recordingId);
264
+ const source = await ownSource(req, doc, body.transcriptionId);
263
265
  if (!source)
264
- return json({ error: 'That recording is not one of theirs.' }, 403);
266
+ return json({ error: 'That transcription is not one of theirs.' }, 403);
265
267
  try {
266
- // A failed lookup is an error to show, not a reason to try the retired /v1/voices/from-speaker.
267
- const transcriptionId = source.transcriptionId ?? (await api.job(source.recordingId)).transcriptionId;
268
- const trial = await api.speakerFromAppearance({ draft: true, name: nameOf(req, doc), recordingId: source.recordingId, spans, speaker: body.speaker, transcriptionId }, `payload:${collection}:${id}:trial:${randomUUID()}`);
268
+ const trial = await api.speakerFromAppearance({ draft: true, name: nameOf(req, doc), spans, speaker: body.speaker, transcriptionId: source.transcriptionId }, `payload:${collection}:${id}:trial:${randomUUID()}`);
269
269
  // The trial it replaces (other samples picked) is not wanted any more.
270
270
  if (typeof body.replace === 'string' && body.replace !== trial.id)
271
271
  await dropTrial(api, body.replace);
@@ -439,7 +439,7 @@ export function lookupEndpoints(options) {
439
439
  if (!lang)
440
440
  return json({ error: 'Which language?' }, 400);
441
441
  try {
442
- return json(await client.availableVoices(lang, req.searchParams.get('recording') ?? undefined));
442
+ return json(await client.availableVoices(lang, req.searchParams.get('transcription') ?? undefined));
443
443
  }
444
444
  catch (err) {
445
445
  return apiError(err);
package/dist/readings.js CHANGED
@@ -18,7 +18,8 @@ export const readingsCollection = (slug) => ({
18
18
  upload: { mimeTypes: ['audio/mpeg'] },
19
19
  fields: [
20
20
  { name: 'lang', type: 'text', admin: { readOnly: true } },
21
- { name: 'recordingId', type: 'text', admin: { readOnly: true } },
21
+ { name: 'transcriptionId', type: 'text', admin: { readOnly: true } },
22
+ { name: 'recordingId', type: 'text', admin: { hidden: true, readOnly: true } },
22
23
  { name: 'voice', type: 'text', admin: { readOnly: true } },
23
24
  ],
24
25
  });
package/dist/types.d.ts CHANGED
@@ -12,7 +12,7 @@ export type VocalStackPluginOptions = {
12
12
  * `overrides` adjusts the added collection (access, labels, admin, upload
13
13
  * options). A host may instead define its own upload collection with that slug;
14
14
  * the plugin then uses it as it is. It needs to accept `audio/mpeg` and have text
15
- * fields `lang`, `recordingId` and `voice`.
15
+ * fields `lang`, `transcriptionId` and `voice` (and `recordingId`, kept for readings saved before 0.9.0).
16
16
  */
17
17
  readings?: false | {
18
18
  overrides?: (collection: CollectionConfig) => CollectionConfig;
@@ -116,18 +116,22 @@ export type SpeakerCollectionConfig = {
116
116
  name?: (args: {
117
117
  doc: Record<string, unknown>;
118
118
  }) => string;
119
- /** Transcribed recordings this person speaks in, offered as the sample to clone from. */
119
+ /** Transcriptions this person speaks in, offered as the sample to clone from. */
120
+ transcriptions?: (args: {
121
+ doc: Record<string, unknown>;
122
+ req: PayloadRequest;
123
+ }) => Promise<SpeakerSource[]> | SpeakerSource[];
124
+ /** @deprecated The name before 0.9.0; use `transcriptions`. Sources without a `transcriptionId` are left out. */
120
125
  recordings?: (args: {
121
126
  doc: Record<string, unknown>;
122
127
  req: PayloadRequest;
123
128
  }) => Promise<SpeakerSource[]> | SpeakerSource[];
124
129
  };
125
- /** A transcribed recording to take a voice sample from. */
130
+ /** A transcription to take a voice sample from. */
126
131
  export type SpeakerSource = {
127
132
  label: string;
128
- recordingId: string;
129
133
  sentences?: TranscriptSentence[];
130
- transcriptionId?: string;
134
+ transcriptionId: string;
131
135
  };
132
136
  export type CloneState = 'failed' | 'none' | 'ready' | 'training';
133
137
  /** The `vocalstackSpeaker` group on a speaker collection's documents. */
@@ -232,6 +236,7 @@ export type TranscriptStatus = 'done' | 'failed' | 'idle' | 'processing';
232
236
  export type VocalStackFieldData = {
233
237
  error?: null | string;
234
238
  language?: null | string;
239
+ /** Saved before 0.9.0 beside `transcriptionId`; no longer read from VocalStack. */
235
240
  recordingId?: null | string;
236
241
  sentences?: null | TranscriptSentence[];
237
242
  status?: null | TranscriptStatus;
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export declare const PACKAGE_NAME = "@vocalstack/payload";
2
- export declare const VERSION = "0.8.1";
2
+ export declare const VERSION = "0.9.0";
package/dist/version.js CHANGED
@@ -1,3 +1,3 @@
1
1
  // Written by scripts/version.mjs from package.json. Do not edit.
2
2
  export const PACKAGE_NAME = "@vocalstack/payload";
3
- export const VERSION = "0.8.1";
3
+ export const VERSION = "0.9.0";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vocalstack/payload",
3
- "version": "0.8.1",
3
+ "version": "0.9.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",
@@ -50,6 +50,6 @@
50
50
  },
51
51
  "packageManager": "pnpm@10.15.1",
52
52
  "dependencies": {
53
- "@vocalstack/js-sdk": "2.0.0-alpha.1"
53
+ "@vocalstack/js-sdk": "2.0.0-alpha.15"
54
54
  }
55
55
  }