@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.
package/README.md CHANGED
@@ -37,10 +37,10 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
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
38
  - **Translations and readings**, under every finished transcript: translate it into up to 10 of VocalStack's 100 languages (VocalStack's limit per recording), and have each translation read aloud where VocalStack has a voice for it. VocalStack picks the voices; a toggle on each transcript chooses between **synthetic** voices and the speakers' own **cloned** voices (where they have one, made with their permission), saved as `voices`. One click in the admin does both; the server carries on until it is done, with no one watching. Saved in the `vocalstack` group as:
39
39
  - `translations`: `{ [lang]: { translatedAt, sentences, pending?, error?, requestedAt? } }`, the transcript's sentences (same ids and times) translated. `pending` while the server is still translating it.
40
- - `speech`: `{ [lang]: { voice, 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.
40
+ - `speech`: `{ [lang]: { voice, cast, readIn, state, error, durationS, requestedAt, renderedAt, sentences, audio } }`. `state` is `translating` (waiting for its translation), `queued`, `running`, `failed` or `sealed`; once sealed, `sentences` are the translation in the reading's own timing, with words, for a read-along player, and `audio` is the MP3 kept in your storage.
41
41
  - `POST …/vocalstack/voices { voices: 'synthetic' | 'cloned' }`, `POST …/vocalstack/request { langs, speak? }` (translate, and read aloud unless `speak: false`; carried on by the server), `POST …/vocalstack/translate { langs }` (one step; answers `more: true` when it stopped for time), `DELETE …/vocalstack/translate?lang=`, `POST …/vocalstack/speak { langs }`, `GET …/vocalstack/speak`, and the public `GET …/vocalstack/audio?lang=`, which redirects to the reading's MP3 (or, with no `lang` or the spoken one, the recording's audio) for anyone who may read the document.
42
42
  - **Languages for listeners** (opt in with `listeners`): visitors pick any language VocalStack offers, and it is made for them and kept for everyone after. `GET /api/vocalstack/languages` is public, `POST …/vocalstack/listen { lang }` asks for a language and `GET …/vocalstack/listen?lang=` says where it stands; see below.
43
- - **Voices** (opt in with `voices`): documents of a collection of people get a sidebar panel to clone that person's voice from a minute of a recording they speak in, or from an uploaded sample, with their permission. Kept in a hidden `vocalstackVoice` group (`voiceId`, `state`: `none`/`training`/`ready`/`failed`, `progress`, `error`, `sampleS`, `consentAt`, `createdAt`), with `GET`/`POST`/`DELETE /api/{collection}/:id/vocalstack/voice`, `…/voice/sources` and `…/voice/preview`.
43
+ - **Speakers** (opt in with `speakers`): documents of a collection of people get a sidebar panel that saves that person as a VocalStack speaker and clones their voice, from a minute of a recording they speak in or from an uploaded sample, with their permission. Kept in a hidden `vocalstackSpeaker` group (`speakerId`, `cloneId`, `state` of the voice: `none`/`training`/`ready`/`failed`, `progress`, `error`, `sampleS`, `consentAt`, `createdAt`), with `GET`/`POST`/`DELETE /api/{collection}/:id/vocalstack/speaker`, `…/speaker/sources` and `…/speaker/preview`.
44
44
  - **Settings → VocalStack** (a global), where an editor connects an account. The key is stored server-side and is unreadable over the REST and GraphQL APIs.
45
45
 
46
46
  ## Options
@@ -52,13 +52,14 @@ Then run `payload generate:importmap`. The plugin adds fields to the targeted co
52
52
  | `audioFields` | none | Audio that isn't an upload document; see below. |
53
53
  | `spokenLanguage` | auto-detect | A Whisper language code (`en`, `ro`, …). |
54
54
  | `fileURL` | the doc's `url`, made absolute | `({ doc, collection, req }) => string`: the address VocalStack fetches. Point it at your bucket's public URL to skip the Payload file proxy. |
55
- | `access` | signed-in users who can update the doc | Extra check for transcribing, translating, voices and the admin lookups, and for changing the connection. |
55
+ | `access` | signed-in users who can update the doc | Extra check for transcribing, translating, speakers, voices and the admin lookups, and for changing the connection. |
56
56
  | `oneClickConnect` | `false` | Show **Connect VocalStack** (see below). |
57
57
  | `apiURL` / `dashboardURL` | `https://api.vocalstack.com` / `https://app.vocalstack.com` | |
58
58
  | `enabled` | `true` | `false` keeps the schema but removes the button and the endpoints. |
59
- | `voices` | none | Collections of people who get a cloned voice; see below. |
59
+ | `speakers` | none | Collections of people saved as VocalStack speakers, each with a cloned voice; see below. (`voices`, its name in 0.5, still works.) |
60
60
  | `readings` | `{ slug: 'vocalstack-readings' }` | The upload collection finished readings are kept in, added by the plugin; `overrides: (collection) => collection` adjusts it. `false` streams readings from VocalStack instead. See below for bringing your own. |
61
61
  | `listeners` | off | `true`, or `{ languages?, speak?, access?, perHour? }`: let visitors ask for a transcript in their language; see below. |
62
+ | `voiceMode` | the transcript's toggle | `({ collection, doc, req, row }) => 'synthetic' \| 'cloned' \| undefined`: the site decides how transcripts are read aloud, and the toggle is hidden. See below. |
62
63
 
63
64
  ### Audio that isn't an upload
64
65
 
@@ -79,28 +80,60 @@ vocalstackPlugin({
79
80
 
80
81
  Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?field=attachments&row=<row id>`. A new row needs saving first.
81
82
 
82
- ### Voices
83
+ ### Speakers
83
84
 
84
85
  ```ts
85
86
  import { vocalstackPlugin } from '@vocalstack/payload'
86
87
 
87
88
  vocalstackPlugin({
88
- voices: [
89
+ speakers: [
89
90
  {
90
91
  collection: 'speakers',
91
92
  // Recordings this speaker is in, offered as the sample to clone from.
92
93
  recordings: async ({ doc, req }) => {
93
94
  const { docs } = await req.payload.find({ collection: 'episodes', where: { speaker: { equals: doc.id } }, req })
94
- return docs.flatMap((e) => (e.vocalstack?.recordingId ? [{ label: e.title, recordingId: e.vocalstack.recordingId, sentences: e.vocalstack.sentences }] : []))
95
+ return docs.flatMap((e) => (e.vocalstack?.recordingId ? [{ label: e.title, recordingId: e.vocalstack.recordingId, sentences: e.vocalstack.sentences, transcriptionId: e.vocalstack.transcriptionId }] : []))
95
96
  },
96
97
  },
97
98
  ],
98
99
  })
99
100
  ```
100
101
 
101
- A sample from a recording can only come from the recordings `recordings` returns for that document: cloning, and hearing a stretch first (`GET /:id/vocalstack/voice/clip`), refuse any other.
102
+ A sample from a recording can only come from the recordings `recordings` returns for that document: cloning, and hearing a stretch first (`GET /:id/vocalstack/speaker/clip`), refuse any other. Pass each recording's `transcriptionId` too, or the plugin looks it up.
102
103
 
103
- Cloning needs at least 30 seconds of the person speaking alone (a minute is better, at most two), and the editor confirms they have the person's permission. From a recording, the editor clicks where the stretch starts and hears it before cloning; the plugin takes it from VocalStack. An uploaded sample is sent through your server, so on hosts that cap request bodies (Vercel: 4.5 MB) keep it to a minute or two of MP3 or M4A. Training takes a few minutes; the panel follows it. Deleting the voice deletes it in VocalStack too. Readings don't name a voice: VocalStack picks it for each recording.
104
+ Cloning needs at least 30 seconds of the person speaking alone (a minute is better, at most two), and the editor confirms they have the person's permission. From a recording, the editor clicks where the stretch starts and hears it before cloning; the plugin takes it from VocalStack. An uploaded sample is sent through your server, so on hosts that cap request bodies (Vercel: 4.5 MB) keep it to a minute or two of MP3 or M4A. Training takes a few minutes; the panel follows it. Deleting the speaker deletes them and their voice in VocalStack too. When VocalStack transcribes a new recording, it checks who speaks against your saved speakers first.
105
+
106
+ A cloned voice only ever reads words its own speaker said. With `cloned` (from the toggle, or from `voiceMode` once a person has a voice), each speaker VocalStack has matched to a clone is read in it: the speaker it was made from, or one VocalStack recognised as the same person when it transcribed the recording. Everyone else is read in a stock voice. VocalStack doesn't always recognise a speaker, and recordings transcribed before the voice existed are not matched, so a reading reports what it got as `speech[lang].readIn`: `cloned`, `synthetic`, or `mixed`.
107
+
108
+ ```ts
109
+ voiceMode: async ({ doc, req }) => {
110
+ const speaker = await req.payload.findByID({ collection: 'speakers', id: doc.speaker, depth: 0, req })
111
+ return speakerData(speaker).state === 'ready' ? 'cloned' : 'synthetic'
112
+ }
113
+ ```
114
+
115
+ `speakerData(doc)` (from `@vocalstack/payload`) reads the `vocalstackSpeaker` group, or the `vocalstackVoice` group of a document 0.5 saved and nobody has opened since.
116
+
117
+ ### Upgrading from 0.5
118
+
119
+ 0.6 follows VocalStack's rename of saved voices to **speakers** (`/v1/speakers`; a speaker's voice is only the sound, its clone). It talks to VocalStack before and after that change: it calls `/v1/speakers` first and falls back to `/v1/voices` on a 404, so nothing needs doing on the day the API changes.
120
+
121
+ - **Option**: `voices` is now `speakers`. `voices` is still read when `speakers` is not set. Types: `SpeakerCollectionConfig`, `SpeakerSource`, `SpeakerFieldData`, `CloneState` (the old names are deprecated aliases).
122
+ - **Fields**: speaker collections get a new hidden group, `vocalstackSpeaker` (`speakerId`, `cloneId`, and the fields `vocalstackVoice` had). The `vocalstackVoice` group stays in the schema and is kept in step (`voiceId` is the clone's id) for one more minor version, so code reading it keeps working; move it to `speakerData(doc)` or `vocalstackSpeaker`. The sidebar field is now `vocalstackSpeakerPanel` (a UI field, nothing stored).
123
+ - **Data**: nothing is lost. A document still holding only `vocalstackVoice` is read through it and copied into `vocalstackSpeaker` the first time its panel opens. To copy them all at once, call `migrateSpeakerFields({ collection, payload, req })` from a migration:
124
+
125
+ ```ts
126
+ // migrations/20261107_vocalstack_speakers.ts, after `payload migrate:create`
127
+ import { migrateSpeakerFields } from '@vocalstack/payload'
128
+ import type { MigrateUpArgs } from '@payloadcms/db-postgres'
129
+
130
+ export async function up({ payload, req }: MigrateUpArgs) {
131
+ await migrateSpeakerFields({ collection: 'speakers', payload, req })
132
+ }
133
+ ```
134
+
135
+ - **Run** `payload generate:importmap` (the panel's component is now `SpeakerField`), and with Postgres or SQLite `payload migrate:create` for the new columns (the old ones are kept).
136
+ - **Endpoints**: `/:id/vocalstack/speaker…` replaces `/:id/vocalstack/voice…`; the old paths still answer. Answers carry `vocalstackSpeaker` (and `vocalstackVoice` as before).
104
137
 
105
138
  ### Translations and readings
106
139
 
package/dist/api.d.ts CHANGED
@@ -51,16 +51,15 @@ export type Transcript = {
51
51
  text: string;
52
52
  }[];
53
53
  };
54
- export type Voice = {
54
+ export type SavedSpeaker = {
55
+ cloneId: null | string;
55
56
  createdAt: string;
56
- /** A trial voice, to hear before it is kept. */
57
57
  draft?: boolean;
58
58
  error?: null | string;
59
59
  id: string;
60
60
  name: string;
61
61
  progress: number;
62
62
  sampleS: number;
63
- /** `training`, `ready` or `failed`. */
64
63
  state: string;
65
64
  };
66
65
  export type VoiceOption = {
@@ -72,7 +71,7 @@ export type VoiceOption = {
72
71
  quality: number;
73
72
  ready?: boolean;
74
73
  };
75
- /** A recording's spoken translation in one language and voice (`voiceKey` is `''` for the default voice). */
74
+ /** A recording's spoken translation in one language, in one cast of voices. */
76
75
  export type VoiceTrack = {
77
76
  /** Seconds each sentence's clip lasts, by sentence id. */
78
77
  clipDur?: Record<string, number>;
@@ -82,12 +81,19 @@ export type VoiceTrack = {
82
81
  lang: string;
83
82
  /** `queued`, `running`, `failed`, `sealed` (the track is ready), or `clips` (sentences only). */
84
83
  state: string;
85
- /** `synthetic` or `cloned` (the API's voice modes); older APIs answer a voice name here, or nothing. */
84
+ /** The voice it was asked in by name, if it was. */
86
85
  voice?: null | string;
86
+ /** The track's key: `''` for the default voice on older tracks, else its cast (`cast:0=M1;1=F1`). */
87
87
  voiceKey: string;
88
+ /** What it is read in: `cloned`, `synthetic`, or `mixed` (some speakers had no usable clone). Null on older tracks. */
89
+ voices?: 'cloned' | 'mixed' | 'synthetic' | null;
88
90
  /** Each sentence's words as [start, end] within its clip, by sentence id. */
89
91
  wordTimes?: Record<string, [number, number][]>;
90
92
  };
93
+ /** How a reading is voiced: in the speakers' cloned voices where VocalStack has them, or in stock voices. */
94
+ export type SpeakAs = {
95
+ cloned: boolean;
96
+ };
91
97
  export type Language = {
92
98
  code: string;
93
99
  name: string;
@@ -107,6 +113,7 @@ export declare class VocalStackAPIError extends Error {
107
113
  constructor(status: number, code: string, message: string);
108
114
  }
109
115
  export declare class VocalStackAPI {
116
+ #private;
110
117
  readonly sdk: VocalStack;
111
118
  constructor(apiKey: string, baseURL?: string);
112
119
  me(): Promise<Record<string, unknown>>;
@@ -136,13 +143,13 @@ export declare class VocalStackAPI {
136
143
  translations: Record<string, string>;
137
144
  }>;
138
145
  /**
139
- * Render spoken translations, one job per language, in the recording's default cast: VocalStack
140
- * picks each speaker's voice. `cloned` lets it use speakers' own cloned voices (each made with
141
- * that speaker's permission); otherwise it reads in stock voices.
146
+ * Read translations aloud, one job per language. `cloned` reads each speaker in their own cloned
147
+ * voice where VocalStack can use one (a clone of that speaker, made with their permission, or the
148
+ * clone of a saved speaker VocalStack recognised as them) and in a stock voice otherwise; `synthetic` reads
149
+ * everyone in stock voices. Each track says which it got (`voices`: cloned, synthetic or mixed).
150
+ * A clone only ever reads words its own speaker said.
142
151
  */
143
- speak(recordingId: string, langs: string[], opts?: {
144
- cloned?: boolean;
145
- }): Promise<VoiceTrack[]>;
152
+ speak(recordingId: string, langs: string[], as?: SpeakAs): Promise<VoiceTrack[]>;
146
153
  voiceTracks(recordingId: string, lang?: string): Promise<VoiceTrack[]>;
147
154
  /** An address of the recording's audio, or of a spoken translation's, that works for an hour or so. */
148
155
  audioURL(recordingId: string, opts: {
@@ -153,17 +160,18 @@ export declare class VocalStackAPI {
153
160
  }): Promise<string>;
154
161
  /** A stretch of the recording as WAV (16 kHz mono), at most 120 s. */
155
162
  clip(recordingId: string, startS: number, endS: number): Promise<Response>;
156
- voice(id: string): Promise<Voice>;
157
- /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
158
- createVoice(sample: Blob, fileName: string, meta: {
163
+ savedSpeaker(id: string): Promise<SavedSpeaker>;
164
+ /** Save a speaker from a recorded sample (30 s or more), cloning their voice. Needs the speaker's permission. */
165
+ createSpeaker(sample: Blob, fileName: string, meta: {
159
166
  consent: boolean;
160
167
  name: string;
161
- }, idempotencyKey: string): Promise<Voice>;
168
+ }, idempotencyKey: string): Promise<SavedSpeaker>;
162
169
  /**
163
- * Clone a speaker's voice from stretches of a transcribed recording (5–60 s in all). `draft`
164
- * makes a trial voice to hear first; keep it with `keepVoice`, or delete it.
170
+ * Save a speaker from stretches of a transcribed recording (5–60 s in all), cloning their voice.
171
+ * `draft` makes a trial to hear first; keep it with `keepSpeaker`, or delete it. Saved speakers
172
+ * are the ones VocalStack looks for first when it works out who speaks in a new recording.
165
173
  */
166
- voiceFromSpeaker(opts: {
174
+ speakerFromAppearance(opts: {
167
175
  draft: boolean;
168
176
  name: string;
169
177
  recordingId: string;
@@ -172,16 +180,17 @@ export declare class VocalStackAPI {
172
180
  start: number;
173
181
  }[];
174
182
  speaker: number;
175
- }, idempotencyKey: string): Promise<Voice>;
176
- /** Keep a trial voice, as `name`, with the speaker's permission. */
177
- keepVoice(id: string, name: string): Promise<Voice>;
178
- deleteVoice(id: string): Promise<unknown>;
183
+ transcriptionId?: string;
184
+ }, idempotencyKey: string): Promise<SavedSpeaker>;
185
+ /** Keep a trial speaker, as `name`, with the speaker's permission. */
186
+ keepSpeaker(id: string, name: string): Promise<SavedSpeaker>;
187
+ deleteSpeaker(id: string): Promise<void>;
188
+ /** The saved speaker's cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
189
+ speakerVoicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
179
190
  availableVoices(lang: string, recordingId?: string): Promise<{
180
191
  lang: string;
181
192
  voices: VoiceOption[];
182
193
  }>;
183
- /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
184
- voicePreview(id: string, lang?: string, format?: 'caf' | 'ogg'): Promise<Response>;
185
194
  }
186
195
  /** A short label for the connected account, from whatever `/v1/me` carries. */
187
196
  export declare function accountLabel(me: Record<string, unknown>): string | undefined;
package/dist/api.js CHANGED
@@ -7,6 +7,22 @@
7
7
  import { VocalStack, VocalStackError } from '@vocalstack/js-sdk';
8
8
  export const DEFAULT_API_URL = 'https://api.vocalstack.com';
9
9
  export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
10
+ function savedSpeakerOf(raw) {
11
+ const clone = 'voice' in raw ? (raw.voice ?? null) : raw;
12
+ return {
13
+ cloneId: clone?.id ?? null,
14
+ createdAt: raw.createdAt,
15
+ draft: raw.draft ?? clone?.draft,
16
+ error: clone?.error ?? null,
17
+ id: raw.id,
18
+ name: raw.name,
19
+ progress: clone?.progress ?? 0,
20
+ sampleS: clone?.sampleS ?? 0,
21
+ state: clone?.state ?? 'none',
22
+ };
23
+ }
24
+ const speakerRoutes = new Map();
25
+ const both = (rest) => ({ speakers: `/v1/speakers${rest}`, voices: `/v1/voices${rest}` });
10
26
  export const UNAVAILABLE = 'VocalStack is unavailable, try again shortly.';
11
27
  export class VocalStackAPIError extends Error {
12
28
  code;
@@ -22,7 +38,7 @@ function timeoutFor(url, method = 'GET') {
22
38
  const path = new URL(url).pathname;
23
39
  if (path.endsWith('/translation'))
24
40
  return 180_000;
25
- if (method === 'POST' && path === '/v1/voices')
41
+ if (method === 'POST' && (path === '/v1/speakers' || path === '/v1/voices'))
26
42
  return 120_000;
27
43
  if (path.endsWith('/audio/clip') || path.endsWith('/preview'))
28
44
  return 60_000;
@@ -52,7 +68,11 @@ const call = async (run) => {
52
68
  };
53
69
  export class VocalStackAPI {
54
70
  sdk;
71
+ #apiKey;
72
+ #baseURL;
55
73
  constructor(apiKey, baseURL = DEFAULT_API_URL) {
74
+ this.#apiKey = apiKey;
75
+ this.#baseURL = baseURL.replace(/\/+$/, '');
56
76
  this.sdk = new VocalStack({
57
77
  apiKey,
58
78
  baseUrl: baseURL,
@@ -102,21 +122,27 @@ export class VocalStackAPI {
102
122
  return call(() => this.sdk.recordings.translation(recordingId, lang, sentenceIds));
103
123
  }
104
124
  /**
105
- * Render spoken translations, one job per language, in the recording's default cast: VocalStack
106
- * picks each speaker's voice. `cloned` lets it use speakers' own cloned voices (each made with
107
- * that speaker's permission); otherwise it reads in stock voices.
125
+ * Read translations aloud, one job per language. `cloned` reads each speaker in their own cloned
126
+ * voice where VocalStack can use one (a clone of that speaker, made with their permission, or the
127
+ * clone of a saved speaker VocalStack recognised as them) and in a stock voice otherwise; `synthetic` reads
128
+ * everyone in stock voices. Each track says which it got (`voices`: cloned, synthetic or mixed).
129
+ * A clone only ever reads words its own speaker said.
108
130
  */
109
- async speak(recordingId, langs, opts = {}) {
110
- const render = (body) => call(() => this.sdk.recordings.renderVoice(recordingId, body));
111
- try {
112
- return await render({ langs, voice: opts.cloned ? 'cloned' : 'synthetic' });
113
- }
114
- catch (err) {
115
- // An API from before `voice: 'synthetic' | 'cloned'` takes it for a voice id: there, consent turns clones on.
116
- if (!(err instanceof VocalStackAPIError && err.status === 400 && /no voice '(cloned|synthetic)'/.test(err.message)))
117
- throw err;
118
- return render({ consent: opts.cloned ? true : undefined, langs });
119
- }
131
+ async speak(recordingId, langs, as = { cloned: false }) {
132
+ const ask = { langs, voices: as.cloned ? 'cloned' : 'synthetic' };
133
+ // Straight to the API: the SDK on npm (2.0.0-alpha.1) leaves `voices` out of the body.
134
+ const res = await call(() => fetch(`${this.#baseURL}/v1/recordings/${encodeURIComponent(recordingId)}/voice`, {
135
+ body: JSON.stringify(ask),
136
+ headers: { authorization: `Bearer ${this.#apiKey}`, 'content-type': 'application/json' },
137
+ method: 'POST',
138
+ signal: AbortSignal.timeout(30_000),
139
+ }));
140
+ const body = (await res.json().catch(() => null));
141
+ if (res.ok)
142
+ return body;
143
+ if (res.status === 502 || res.status === 503 || res.status === 504)
144
+ throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
145
+ throw new VocalStackAPIError(res.status, body?.code ?? 'http_error', body?.message ?? `VocalStack answered ${res.status}`);
120
146
  }
121
147
  voiceTracks(recordingId, lang) {
122
148
  return call(() => this.sdk.recordings.voice(recordingId, lang));
@@ -134,34 +160,86 @@ export class VocalStackAPI {
134
160
  clip(recordingId, startS, endS) {
135
161
  return call(() => this.sdk.recordings.clip(recordingId, startS, endS));
136
162
  }
137
- voice(id) {
138
- return call(() => this.sdk.voices.get(id));
163
+ async #speakerRequest(method, paths, init = {}) {
164
+ const first = speakerRoutes.get(this.#baseURL) ?? 'speakers';
165
+ const order = first === 'speakers' ? ['speakers', 'voices'] : ['voices', 'speakers'];
166
+ const query = Object.entries(init.query ?? {}).filter((e) => e[1] !== undefined);
167
+ const qs = query.length ? `?${new URLSearchParams(query)}` : '';
168
+ let last;
169
+ for (const route of order) {
170
+ const path = paths[route];
171
+ if (!path)
172
+ continue;
173
+ const url = `${this.#baseURL}${path}${qs}`;
174
+ const headers = { accept: init.audio ? '*/*' : 'application/json', authorization: `Bearer ${this.#apiKey}` };
175
+ if (init.body)
176
+ headers['content-type'] = 'application/json';
177
+ if (init.idempotencyKey)
178
+ headers['idempotency-key'] = init.idempotencyKey;
179
+ const body = init.form ?? (init.body ? JSON.stringify(init.body(route)) : undefined);
180
+ const res = await call(() => fetch(url, { body, headers, method, signal: AbortSignal.timeout(timeoutFor(url, method)) }));
181
+ if (res.status !== 404) {
182
+ speakerRoutes.set(this.#baseURL, route);
183
+ return res;
184
+ }
185
+ last = res;
186
+ }
187
+ if (!last)
188
+ throw new VocalStackAPIError(404, 'not_found', 'Not found.');
189
+ return last;
190
+ }
191
+ async #speaker(method, paths, init) {
192
+ const res = await this.#speakerRequest(method, paths, init);
193
+ const body = (await res.json().catch(() => null));
194
+ if (res.ok && body)
195
+ return savedSpeakerOf(body);
196
+ if (res.status === 502 || res.status === 503 || res.status === 504)
197
+ throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
198
+ throw new VocalStackAPIError(res.status, body?.code ?? 'http_error', body?.message ?? `VocalStack answered ${res.status}`);
199
+ }
200
+ savedSpeaker(id) {
201
+ return this.#speaker('GET', both(`/${encodeURIComponent(id)}`));
139
202
  }
140
- /** Clone a voice from a recorded sample (30 s or more). Needs the speaker's permission. */
141
- createVoice(sample, fileName, meta, idempotencyKey) {
142
- return call(() => this.sdk.voices.create({ ...meta, fileName, sample }, { idempotencyKey }));
203
+ /** Save a speaker from a recorded sample (30 s or more), cloning their voice. Needs the speaker's permission. */
204
+ createSpeaker(sample, fileName, meta, idempotencyKey) {
205
+ const form = new FormData();
206
+ form.append('meta', JSON.stringify(meta));
207
+ form.append('sample', sample, fileName);
208
+ return this.#speaker('POST', both(''), { form, idempotencyKey });
143
209
  }
144
210
  /**
145
- * Clone a speaker's voice from stretches of a transcribed recording (5–60 s in all). `draft`
146
- * makes a trial voice to hear first; keep it with `keepVoice`, or delete it.
211
+ * Save a speaker from stretches of a transcribed recording (5–60 s in all), cloning their voice.
212
+ * `draft` makes a trial to hear first; keep it with `keepSpeaker`, or delete it. Saved speakers
213
+ * are the ones VocalStack looks for first when it works out who speaks in a new recording.
147
214
  */
148
- voiceFromSpeaker(opts, idempotencyKey) {
149
- return call(() => this.sdk.voices.createFromSpeaker({ ...opts, consent: true, library: false }, { idempotencyKey }));
215
+ speakerFromAppearance(opts, idempotencyKey) {
216
+ const { recordingId, speaker, transcriptionId, ...rest } = opts;
217
+ const common = { ...rest, consent: true, library: true };
218
+ return this.#speaker('POST', { speakers: transcriptionId ? '/v1/speakers/from-appearance' : undefined, voices: '/v1/voices/from-speaker' }, {
219
+ body: (route) => (route === 'speakers' ? { ...common, appearance: speaker, transcriptionId } : { ...common, recordingId, speaker }),
220
+ idempotencyKey,
221
+ });
150
222
  }
151
- /** Keep a trial voice, as `name`, with the speaker's permission. */
152
- keepVoice(id, name) {
153
- return call(() => this.sdk.voices.update(id, { consent: true, draft: false, name }));
223
+ /** Keep a trial speaker, as `name`, with the speaker's permission. */
224
+ keepSpeaker(id, name) {
225
+ return this.#speaker('PATCH', both(`/${encodeURIComponent(id)}`), { body: () => ({ consent: true, draft: false, library: true, name }) });
154
226
  }
155
- deleteVoice(id) {
156
- return call(() => this.sdk.voices.delete(id));
227
+ async deleteSpeaker(id) {
228
+ const res = await this.#speakerRequest('DELETE', both(`/${encodeURIComponent(id)}`));
229
+ if (res.ok)
230
+ return;
231
+ const body = (await res.json().catch(() => null));
232
+ if (res.status === 502 || res.status === 503 || res.status === 504)
233
+ throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
234
+ throw new VocalStackAPIError(res.status, body?.code ?? 'http_error', body?.message ?? `VocalStack answered ${res.status}`);
235
+ }
236
+ /** The saved speaker's cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
237
+ speakerVoicePreview(id, lang, format = 'ogg') {
238
+ return this.#speakerRequest('GET', both(`/${encodeURIComponent(id)}/preview`), { audio: true, query: { format, lang } });
157
239
  }
158
240
  availableVoices(lang, recordingId) {
159
241
  return call(() => this.sdk.voices.available(lang, { recording: recordingId }));
160
242
  }
161
- /** The cloned voice speaking a few seconds of `lang`, Ogg/Opus or CAF. 202 while it is being made. */
162
- voicePreview(id, lang, format = 'ogg') {
163
- return call(() => this.sdk.voices.clonePreview(id, { format, lang }));
164
- }
165
243
  }
166
244
  /** A short label for the connected account, from whatever `/v1/me` carries. */
167
245
  export function accountLabel(me) {
@@ -0,0 +1 @@
1
+ export declare const SpeakerField: React.FC;
@@ -15,25 +15,27 @@ const styles = `
15
15
  `;
16
16
  /** Ogg/Opus where the browser plays it, else CAF (Safari). */
17
17
  const previewFormat = () => (typeof Audio !== 'undefined' && new Audio().canPlayType('audio/ogg; codecs=opus') ? 'ogg' : 'caf');
18
- export const VoiceField = () => {
18
+ export const SpeakerField = () => {
19
19
  const { id, collectionSlug } = useDocumentInfo();
20
20
  const { dispatchFields } = useForm();
21
21
  const { connection } = useConnection();
22
22
  const call = useAPI();
23
- const base = `/${collectionSlug}/${id}/vocalstack/voice`;
23
+ const base = `/${collectionSlug}/${id}/vocalstack/speaker`;
24
24
  const [voice, setVoice] = useState();
25
25
  const [name, setName] = useState('');
26
26
  const [error, setError] = useState();
27
27
  const [busy, setBusy] = useState(false);
28
28
  const [creating, setCreating] = useState(false);
29
29
  const timer = useRef(undefined);
30
- // Keep the form's copy in step with the server's, so saving the document keeps the voice.
30
+ // Keep the form's copy in step with the server's, so saving the document keeps the speaker.
31
31
  const apply = useCallback((res) => {
32
- setVoice(res.vocalstackVoice);
32
+ setVoice(res.vocalstackSpeaker);
33
33
  if (res.name)
34
34
  setName(res.name);
35
- for (const [key, value] of Object.entries(res.vocalstackVoice)) {
36
- dispatchFields({ type: 'UPDATE', initialValue: value, path: `vocalstackVoice.${key}`, value });
35
+ for (const group of ['vocalstackSpeaker', 'vocalstackVoice']) {
36
+ for (const [key, value] of Object.entries(res[group] ?? {})) {
37
+ dispatchFields({ type: 'UPDATE', initialValue: value, path: `${group}.${key}`, value });
38
+ }
37
39
  }
38
40
  }, [dispatchFields]);
39
41
  const refresh = useCallback(async () => {
@@ -42,7 +44,7 @@ export const VoiceField = () => {
42
44
  const res = await call(base);
43
45
  apply(res);
44
46
  setError(undefined);
45
- if (res.vocalstackVoice.state === 'training')
47
+ if (res.vocalstackSpeaker.state === 'training')
46
48
  timer.current = setTimeout(refresh, POLL_MS);
47
49
  }
48
50
  catch (err) {
@@ -60,12 +62,12 @@ export const VoiceField = () => {
60
62
  // eslint-disable-next-line react-hooks/exhaustive-deps
61
63
  }, [id, connection?.connected]);
62
64
  const remove = async () => {
63
- if (!window.confirm(`Delete ${name || 'this'} voice? Readings already made with it stay as they are.`))
65
+ if (!window.confirm(`Delete ${name || 'this speaker'} from VocalStack, with their cloned voice? Readings already made with it stay as they are.`))
64
66
  return;
65
67
  setBusy(true);
66
68
  try {
67
69
  apply(await call(base, { method: 'DELETE' }));
68
- toast.success('Voice deleted.');
70
+ toast.success('Speaker deleted.');
69
71
  }
70
72
  catch (err) {
71
73
  setError(err.message);
@@ -76,7 +78,7 @@ export const VoiceField = () => {
76
78
  };
77
79
  const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
78
80
  const state = voice?.state ?? 'none';
79
- return (_jsxs("div", { className: "field-type vs-brand vs-voice", style: { marginBottom: 'var(--base)' }, children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsxs("div", { className: "field-label", style: { alignItems: 'center', display: 'flex', gap: 8, marginBottom: 'calc(var(--base) / 2)' }, children: [_jsx(Logo, { height: 14 }), " ", _jsx("span", { children: "Voice" })] }), !id ? (_jsx("p", { style: muted, children: "Save first, then create a voice." })) : connection && !connection.connected ? (_jsx("p", { style: muted, children: "Connect VocalStack (Settings \u2192 VocalStack) to create a voice." })) : !voice ? (_jsx("p", { style: muted, children: error ?? 'Checking…' })) : creating || state === 'none' || state === 'failed' ? (creating ? (_jsx(CreateVoice, { base: base, name: name, onCancel: () => setCreating(false), onCreated: (res) => {
81
+ return (_jsxs("div", { className: "field-type vs-brand vs-voice", style: { marginBottom: 'var(--base)' }, children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsxs("div", { className: "field-label", style: { alignItems: 'center', display: 'flex', gap: 8, marginBottom: 'calc(var(--base) / 2)' }, children: [_jsx(Logo, { height: 14 }), " ", _jsx("span", { children: "Speaker" })] }), !id ? (_jsx("p", { style: muted, children: "Save first, then save them as a speaker." })) : connection && !connection.connected ? (_jsx("p", { style: muted, children: "Connect VocalStack (Settings \u2192 VocalStack) to save them as a speaker." })) : !voice ? (_jsx("p", { style: muted, children: error ?? 'Checking…' })) : creating || state === 'none' || state === 'failed' ? (creating ? (_jsx(CreateVoice, { base: base, name: name, onCancel: () => setCreating(false), onCreated: (res) => {
80
82
  apply(res);
81
83
  setCreating(false);
82
84
  timer.current = setTimeout(refresh, POLL_MS);
@@ -123,7 +125,7 @@ const ReadyVoice = ({ base, busy, onDelete, voice }) => {
123
125
  };
124
126
  const names = new Map(langs?.languages.map((l) => [l.code, l.name]));
125
127
  const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
126
- return (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [_jsxs("p", { style: muted, children: ["Ready", voice.sampleS ? `, cloned from ${Math.round(voice.sampleS)} s of speech` : '', ". Translations are read in this voice."] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx("select", { "aria-label": "Preview language", onChange: (e) => setLang(e.target.value), value: lang, children: (langs?.voice ?? ['en']).map((code) => (_jsx("option", { value: code, children: names.get(code) ?? code }, code))) }), _jsx(Button, { buttonStyle: "secondary", disabled: waiting, margin: false, onClick: play, size: "small", children: waiting ? 'Making…' : '▶ Hear' })] }), src && _jsx("audio", { controls: true, ref: audio, src: src, style: { width: '100%' } }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsx("div", { children: _jsx(Button, { buttonStyle: "error", disabled: busy, margin: false, onClick: onDelete, size: "small", children: "Delete voice" }) })] }));
128
+ return (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [_jsxs("p", { style: muted, children: ["Ready", voice.sampleS ? `, cloned from ${Math.round(voice.sampleS)} s of speech` : '', ". Translations are read in this voice."] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx("select", { "aria-label": "Preview language", onChange: (e) => setLang(e.target.value), value: lang, children: (langs?.voice ?? ['en']).map((code) => (_jsx("option", { value: code, children: names.get(code) ?? code }, code))) }), _jsx(Button, { buttonStyle: "secondary", disabled: waiting, margin: false, onClick: play, size: "small", children: waiting ? 'Making…' : '▶ Hear' })] }), src && _jsx("audio", { controls: true, ref: audio, src: src, style: { width: '100%' } }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsx("div", { children: _jsx(Button, { buttonStyle: "error", disabled: busy, margin: false, onClick: onDelete, size: "small", children: "Delete speaker" }) })] }));
127
129
  };
128
130
  const CreateVoice = ({ base, name, onCancel, onCreated }) => {
129
131
  const call = useAPI();
@@ -169,7 +169,7 @@ export const SpeechField = ({ field, path = '' }) => {
169
169
  ? `${t.sentences.length} of ${total} sentences translated`
170
170
  : t
171
171
  ? `${t.sentences.length} sentences translated`
172
- : 'Not translated' })] }), _jsxs("div", { style: { display: 'grid', gap: 6 }, children: [t?.pending ? (_jsxs(_Fragment, { children: [_jsx(Progress, { done: t.sentences.length, label: TRANSLATING, since: t.requestedAt ?? undefined, total: total }), s?.state === 'translating' && _jsx("span", { className: "vs-speech-muted", children: "Read aloud once translated." }), t.error && _jsxs("span", { className: "vs-speech-muted", children: [t.error, " Trying again shortly."] })] })) : busy ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), busy] })) : s?.state === 'queued' || s?.state === 'running' ? (_jsx(Progress, { done: s.done ?? 0, label: s.state === 'queued' ? 'Waiting to be read aloud…' : 'Being read aloud…', since: s.requestedAt, total: t?.sentences.length ?? 0 })) : s?.state === 'sealed' ? (_jsx("audio", { controls: true, preload: "none", src: `${serverURL}${api}${base}/audio${withQuery({ lang, v: s.renderedAt ?? '' })}` }, s.renderedAt ?? '')) : t?.error && !t.sentences.length ? (_jsxs("p", { className: "vs-speech-error", children: ["Translating failed: ", t.error] })) : s?.state === 'translating' ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), "Waiting for VocalStack to read it aloud\u2026"] })) : s?.state === 'failed' ? (_jsxs("p", { className: "vs-speech-error", children: ["Reading failed: ", s.error ?? 'no reason given'] })) : !canSpeak.has(lang) ? (_jsxs("span", { className: "vs-speech-muted", children: ["VocalStack cannot read ", names.get(lang) ?? lang, " aloud yet."] })) : null, canSpeak.has(lang) && !busy && !t?.pending && (!s || s.state === 'failed' || (s.state === 'sealed' && (s.cast ?? 'synthetic') !== voices)) && (_jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => speak([lang]), size: "small", children: !s ? 'Read aloud' : s.state === 'failed' ? 'Try again' : `Read again in ${voices} voices` }) }))] }), _jsx(Button, { buttonStyle: "secondary", disabled: Boolean(busy), margin: false, onClick: () => remove(lang), size: "small", children: "Remove" })] }, lang));
172
+ : 'Not translated' })] }), _jsxs("div", { style: { display: 'grid', gap: 6 }, children: [t?.pending ? (_jsxs(_Fragment, { children: [_jsx(Progress, { done: t.sentences.length, label: TRANSLATING, since: t.requestedAt ?? undefined, total: total }), s?.state === 'translating' && _jsx("span", { className: "vs-speech-muted", children: "Read aloud once translated." }), t.error && _jsxs("span", { className: "vs-speech-muted", children: [t.error, " Trying again shortly."] })] })) : busy ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), busy] })) : s?.state === 'queued' || s?.state === 'running' ? (_jsx(Progress, { done: s.done ?? 0, label: s.state === 'queued' ? 'Waiting to be read aloud…' : 'Being read aloud…', since: s.requestedAt, total: t?.sentences.length ?? 0 })) : s?.state === 'sealed' ? (_jsxs(_Fragment, { children: [_jsx("audio", { controls: true, preload: "none", src: `${serverURL}${api}${base}/audio${withQuery({ lang, v: s.renderedAt ?? '' })}` }, s.renderedAt ?? ''), s.cast === 'cloned' && s.readIn === 'mixed' && (_jsx("span", { className: "vs-speech-muted", children: "Some speakers are read in stock voices: they have no cloned voice to use." })), s.cast === 'cloned' && s.readIn === 'synthetic' && (_jsx("span", { className: "vs-speech-muted", children: "Read in stock voices: no speaker has a cloned voice to use." }))] })) : t?.error && !t.sentences.length ? (_jsxs("p", { className: "vs-speech-error", children: ["Translating failed: ", t.error] })) : s?.state === 'translating' ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), "Waiting for VocalStack to read it aloud\u2026"] })) : s?.state === 'failed' ? (_jsxs("p", { className: "vs-speech-error", children: ["Reading failed: ", s.error ?? 'no reason given'] })) : !canSpeak.has(lang) ? (_jsxs("span", { className: "vs-speech-muted", children: ["VocalStack cannot read ", names.get(lang) ?? lang, " aloud yet."] })) : null, canSpeak.has(lang) && !busy && !t?.pending && (!s || s.state === 'failed' || (s.state === 'sealed' && (s.cast ?? 'synthetic') !== voices)) && (_jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => speak([lang]), size: "small", children: !s ? 'Read aloud' : s.state === 'failed' ? 'Try again' : `Read again in ${voices} voices` }) }))] }), _jsx(Button, { buttonStyle: "secondary", disabled: Boolean(busy), margin: false, onClick: () => remove(lang), size: "small", children: "Remove" })] }, lang));
173
173
  }), _jsx(AddLanguages, { busy: Object.keys(working).length > 0, canSpeak: canSpeak, exclude: new Set([...shown, ...(spoken ? [spoken] : [])]), langs: langs, left: LANGUAGE_LIMIT - shown.filter((l) => l !== spoken).length, onAdd: (list, speakToo) => run(list, 'Starting…', () => request(list, speakToo)) }), error && _jsx("p", { className: "vs-speech-error", children: error })] }));
174
174
  };
175
175
  /** Work under way: the share of sentences done, counted up as each step is saved, and the time it has taken. */
@@ -1,4 +1,4 @@
1
- import type { VoiceFieldData, VoiceSource } from '../types.js';
1
+ import type { SpeakerAnswer, SpeakerSource } from '../types.js';
2
2
  /** As in the VocalStack dashboard: at least 5 s makes a voice, 20 s a steadier one, 25 s is plenty; 60 s at most. */
3
3
  export declare const PICK_MIN_S = 5;
4
4
  export declare const sampleStyles = "\n .vs-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 4px; }\n .vs-step { border-top: 3px solid var(--theme-elevation-150); padding-top: 6px; font-size: 12px; color: var(--theme-elevation-500); }\n .vs-step--on { border-color: var(--vs-accent); color: var(--theme-text); font-weight: 600; }\n .vs-step--done { border-color: color-mix(in srgb, var(--vs-accent) 45%, transparent); }\n .vs-sample { border: 1px solid var(--theme-elevation-150); border-radius: 8px; overflow: hidden; }\n .vs-sample-body { padding: 10px 12px; display: grid; gap: 8px; }\n .vs-sample-head { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: var(--theme-elevation-500); }\n .vs-sample-text { font-size: 14px; line-height: 1.45; min-height: 2.9em; }\n .vs-sample-play { display: flex; align-items: center; gap: 10px; }\n .vs-play { width: 34px; height: 34px; flex: none; border-radius: 50%; border: 0; background: var(--vs-accent); color: #fff; cursor: pointer; font-size: 12px; }\n .vs-play:disabled { opacity: .5; cursor: default; }\n .vs-wave { flex: 1; display: flex; align-items: center; gap: 2px; height: 28px; min-width: 0; }\n .vs-wave span { flex: 1; border-radius: 1px; background: var(--theme-elevation-250); }\n .vs-wave span.on { background: var(--vs-accent); }\n .vs-sample-use { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--theme-elevation-150);\n background: var(--theme-elevation-50); font-size: 14px; cursor: pointer; }\n .vs-pager { display: flex; gap: 4px; }\n .vs-pager button { border: 0; background: none; color: var(--theme-text); cursor: pointer; font-size: 16px; padding: 0 6px; }\n .vs-pager button:disabled { opacity: .3; cursor: default; }\n .vs-meter { position: relative; height: 6px; border-radius: 3px; background: var(--theme-elevation-100); overflow: hidden; }\n .vs-meter span { position: absolute; inset: 0 auto 0 0; background: var(--vs-accent); transition: width .3s; }\n .vs-meter-marks { position: relative; height: 16px; font-size: 11px; color: var(--theme-elevation-500); }\n .vs-meter-marks span { position: absolute; transform: translateX(-50%); }\n .vs-chips { display: flex; flex-wrap: wrap; gap: 6px; }\n .vs-chip { display: inline-flex; gap: 6px; align-items: center; border: 1px solid var(--theme-elevation-150); border-radius: 12px; padding: 2px 4px 2px 10px; font-size: 12px; }\n .vs-chip button { border: 0; background: none; cursor: pointer; color: var(--theme-elevation-500); }\n .vs-chips--none { border: 1px dashed var(--theme-elevation-200); border-radius: 12px; padding: 4px 10px; font-size: 12px; color: var(--theme-elevation-500); }\n";
@@ -9,11 +9,8 @@ export declare const sampleStyles = "\n .vs-steps { display: grid; grid-templat
9
9
  export declare const VoiceFromRecording: React.FC<{
10
10
  base: string;
11
11
  name: string;
12
- onCreated: (res: {
13
- name?: string;
14
- vocalstackVoice: VoiceFieldData;
15
- }) => void;
16
- sources: VoiceSource[];
12
+ onCreated: (res: SpeakerAnswer) => void;
13
+ sources: SpeakerSource[];
17
14
  }>;
18
15
  /** Record them speaking, in the browser, as the sample to clone from. */
19
16
  export declare const RecordSample: React.FC<{
@@ -217,7 +217,7 @@ export const VoiceFromRecording = ({ base, name, onCreated, sources }) => {
217
217
  method: 'POST',
218
218
  });
219
219
  kept.current = true;
220
- toast.success('Voice saved.');
220
+ toast.success('Speaker saved.');
221
221
  onCreated(res);
222
222
  }
223
223
  catch (err) {
@@ -245,7 +245,7 @@ export const VoiceFromRecording = ({ base, name, onCreated, sources }) => {
245
245
  ? `Enough for a voice. ${PICK_GOOD_S}s or more sounds steadier.`
246
246
  : `Good. About ${PICK_TARGET_S}s gives it more to choose from.` }), picked.size ? (_jsx("div", { className: "vs-chips", children: [...picked]
247
247
  .sort((a, b) => a - b)
248
- .map((i) => (_jsxs("span", { className: "vs-chip", children: [_jsxs("button", { onClick: () => setIdx(i), style: { color: 'inherit', padding: 0 }, type: "button", children: [i + 1, " \u00B7 ", Math.round(secs(clips[i])), "s"] }), _jsx("button", { "aria-label": `Leave sample ${i + 1} out`, onClick: () => toggle(i), type: "button", children: "\u2715" })] }, i))) })) : (_jsx("span", { className: "vs-chips--none", children: "No samples picked yet" })), _jsx("div", { children: _jsx(Button, { disabled: !enough || busy, margin: false, onClick: tryVoice, size: "small", children: "Next" }) })] })), step === 2 && (_jsxs(_Fragment, { children: [!trial || trial.state === 'training' || trial.state === 'queued' ? (_jsxs("p", { style: muted, children: ["Making the voice", trial?.progress ? ` · ${trial.progress}%` : '…', " It takes a minute or two."] })) : trial.state === 'failed' ? (_jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["The voice could not be made: ", trial.error ?? 'no reason given', ". Pick other samples."] })) : (_jsx(TrialPreview, { base: base, voice: trial.id })), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setStep(1), size: "small", children: "Back" }), _jsx(Button, { disabled: trial?.state !== 'ready', margin: false, onClick: () => setStep(3), size: "small", children: "Next" })] })] })), step === 3 && (_jsxs(_Fragment, { children: [_jsxs("label", { style: { display: 'grid', fontSize: 13, gap: 4 }, children: ["Name", _jsx("input", { maxLength: 60, onChange: (e) => setVoiceName(e.target.value), style: { font: 'inherit', padding: '6px 8px' }, value: voiceName })] }), _jsxs("label", { style: { alignItems: 'flex-start', display: 'flex', fontSize: 13, gap: 8 }, children: [_jsx("input", { checked: consent, onChange: (e) => setConsent(e.target.checked), style: { marginTop: 3 }, type: "checkbox" }), _jsxs("span", { children: ["I have ", name || 'their', "\u2019s permission to clone their voice."] })] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setStep(2), size: "small", children: "Back" }), _jsx(Button, { disabled: busy || !consent || !voiceName.trim(), margin: false, onClick: keep, size: "small", children: busy ? 'Saving…' : 'Save voice' })] })] })), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error })] }));
248
+ .map((i) => (_jsxs("span", { className: "vs-chip", children: [_jsxs("button", { onClick: () => setIdx(i), style: { color: 'inherit', padding: 0 }, type: "button", children: [i + 1, " \u00B7 ", Math.round(secs(clips[i])), "s"] }), _jsx("button", { "aria-label": `Leave sample ${i + 1} out`, onClick: () => toggle(i), type: "button", children: "\u2715" })] }, i))) })) : (_jsx("span", { className: "vs-chips--none", children: "No samples picked yet" })), _jsx("div", { children: _jsx(Button, { disabled: !enough || busy, margin: false, onClick: tryVoice, size: "small", children: "Next" }) })] })), step === 2 && (_jsxs(_Fragment, { children: [!trial || trial.state === 'training' || trial.state === 'queued' ? (_jsxs("p", { style: muted, children: ["Making the voice", trial?.progress ? ` · ${trial.progress}%` : '…', " It takes a minute or two."] })) : trial.state === 'failed' ? (_jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["The voice could not be made: ", trial.error ?? 'no reason given', ". Pick other samples."] })) : (_jsx(TrialPreview, { base: base, voice: trial.id })), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setStep(1), size: "small", children: "Back" }), _jsx(Button, { disabled: trial?.state !== 'ready', margin: false, onClick: () => setStep(3), size: "small", children: "Next" })] })] })), step === 3 && (_jsxs(_Fragment, { children: [_jsxs("label", { style: { display: 'grid', fontSize: 13, gap: 4 }, children: ["Name", _jsx("input", { maxLength: 60, onChange: (e) => setVoiceName(e.target.value), style: { font: 'inherit', padding: '6px 8px' }, value: voiceName })] }), _jsxs("label", { style: { alignItems: 'flex-start', display: 'flex', fontSize: 13, gap: 8 }, children: [_jsx("input", { checked: consent, onChange: (e) => setConsent(e.target.checked), style: { marginTop: 3 }, type: "checkbox" }), _jsxs("span", { children: ["I have ", name || 'their', "\u2019s permission to clone their voice."] })] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setStep(2), size: "small", children: "Back" }), _jsx(Button, { disabled: busy || !consent || !voiceName.trim(), margin: false, onClick: keep, size: "small", children: busy ? 'Saving…' : 'Save speaker' })] })] })), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error })] }));
249
249
  };
250
250
  /** Ogg/Opus where the browser plays it, else CAF (Safari). */
251
251
  const previewFormat = () => (typeof Audio !== 'undefined' && new Audio().canPlayType('audio/ogg; codecs=opus') ? 'ogg' : 'caf');