@vocalstack/payload 0.2.0 → 0.5.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.
@@ -1,5 +1,7 @@
1
1
  import type { Endpoint } from 'payload';
2
2
  import type { VoiceCollectionConfig, VocalStackPluginOptions } from '../types.js';
3
+ export declare const PICK_MIN_S = 5;
4
+ export declare const PICK_MAX_S = 60;
3
5
  /**
4
6
  * A person's cloned voice, kept in the `vocalstackVoice` group of their document:
5
7
  * GET /:id/vocalstack/voice where its training stands
@@ -9,12 +11,15 @@ import type { VoiceCollectionConfig, VocalStackPluginOptions } from '../types.js
9
11
  * GET /:id/vocalstack/voice/sources recordings to take the sample from
10
12
  * GET /:id/vocalstack/voice/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
11
13
  * GET /:id/vocalstack/voice/preview the voice speaking (?lang=&format=ogg|caf)
14
+ * POST /:id/vocalstack/voice/trial a trial voice from picked sentences { recordingId, speaker, spans, replace? }
15
+ * GET /:id/vocalstack/voice/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
16
+ * POST /:id/vocalstack/voice/trial/keep { voice, name, consent } keep it as their voice; DELETE …/trial?voice= drop it
12
17
  * A sample is only ever taken from the recordings `config.recordings` offers for that document.
13
18
  */
14
19
  export declare function voiceEndpoints(config: VoiceCollectionConfig, options: VocalStackPluginOptions): Endpoint[];
15
20
  /**
16
- * Shared admin lookups (signed in, and `options.access` when set):
17
- * GET /vocalstack/languages what can be translated and spoken
18
- * GET /vocalstack/voices?lang=&recording= voices that can speak a language
21
+ * Shared lookups:
22
+ * GET /vocalstack/languages what can be translated and spoken (public with `listeners` on)
23
+ * GET /vocalstack/voices?lang=&recording= voices that can speak a language (signed in, and `options.access`)
19
24
  */
20
25
  export declare function lookupEndpoints(options: VocalStackPluginOptions): Endpoint[];
@@ -1,9 +1,10 @@
1
1
  import { addDataAndFileToRequest } from 'payload';
2
2
  import { randomUUID } from 'node:crypto';
3
3
  import { DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
4
+ import { forListeners, languageList, listenerOptions } from '../languages.js';
4
5
  import { resolveAPIKey } from '../settings.js';
5
6
  import { apiError, canUpdate } from './transcribe.js';
6
- const json = (body, status = 200) => Response.json(body, { status });
7
+ const json = (body, status = 200, headers) => Response.json(body, { headers, status });
7
8
  // VocalStack clones from 30 s to 120 s of speech (a clip is at most 120 s).
8
9
  const MIN_SAMPLE_S = 30;
9
10
  const MAX_SAMPLE_S = 120;
@@ -17,6 +18,19 @@ const fieldData = (v) => ({
17
18
  state: STATES.has(v.state) ? v.state : 'training',
18
19
  voiceId: v.id,
19
20
  });
21
+ /** A trial voice, as the panel follows it. */
22
+ const trialOf = (v) => ({ error: v.error ?? null, id: v.id, progress: v.progress, state: v.state });
23
+ /** Delete a trial voice; a kept one is never deleted this way. */
24
+ async function dropTrial(api, id) {
25
+ if (!id)
26
+ return;
27
+ const voice = await api.voice(id).catch(() => null);
28
+ if (voice?.draft)
29
+ await api.deleteVoice(id).catch(() => undefined);
30
+ }
31
+ // Picked from a recording, as in the VocalStack dashboard: at least 5 s makes a voice, at most 60 s.
32
+ export const PICK_MIN_S = 5;
33
+ export const PICK_MAX_S = 60;
20
34
  const EMPTY = { consentAt: null, createdAt: null, error: null, progress: null, sampleS: null, state: 'none', voiceId: null };
21
35
  /**
22
36
  * A person's cloned voice, kept in the `vocalstackVoice` group of their document:
@@ -27,6 +41,9 @@ const EMPTY = { consentAt: null, createdAt: null, error: null, progress: null, s
27
41
  * GET /:id/vocalstack/voice/sources recordings to take the sample from
28
42
  * GET /:id/vocalstack/voice/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
29
43
  * GET /:id/vocalstack/voice/preview the voice speaking (?lang=&format=ogg|caf)
44
+ * POST /:id/vocalstack/voice/trial a trial voice from picked sentences { recordingId, speaker, spans, replace? }
45
+ * GET /:id/vocalstack/voice/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
46
+ * POST /:id/vocalstack/voice/trial/keep { voice, name, consent } keep it as their voice; DELETE …/trial?voice= drop it
30
47
  * A sample is only ever taken from the recordings `config.recordings` offers for that document.
31
48
  */
32
49
  export function voiceEndpoints(config, options) {
@@ -190,6 +207,121 @@ export function voiceEndpoints(config, options) {
190
207
  }
191
208
  },
192
209
  },
210
+ {
211
+ // A trial voice from sentences of one of their recordings, to hear before keeping it.
212
+ method: 'post',
213
+ path: '/:id/vocalstack/voice/trial',
214
+ handler: async (req) => {
215
+ const found = await open(req, 'create');
216
+ if (found instanceof Response)
217
+ return found;
218
+ const { api, doc, id } = found;
219
+ const body = (await req.json?.().catch(() => ({})));
220
+ const spans = (Array.isArray(body.spans) ? body.spans : [])
221
+ .map((s) => ({ end: Number(s?.end), start: Number(s?.start) }))
222
+ .filter((s) => Number.isFinite(s.start) && s.end > s.start);
223
+ const total = spans.reduce((t, s) => t + (s.end - s.start), 0);
224
+ if (typeof body.recordingId !== 'string' || !Number.isInteger(body.speaker) || total < PICK_MIN_S - 0.05 || total > PICK_MAX_S + 0.5) {
225
+ return json({ error: `Pick ${PICK_MIN_S} to ${PICK_MAX_S} seconds of their speech.` }, 400);
226
+ }
227
+ if (!(await ownRecording(req, doc, body.recordingId)))
228
+ return json({ error: 'That recording is not one of theirs.' }, 403);
229
+ try {
230
+ const voice = await api.voiceFromSpeaker({ draft: true, name: nameOf(req, doc), recordingId: body.recordingId, spans, speaker: body.speaker }, `payload:${collection}:${id}:trial:${randomUUID()}`);
231
+ // The trial it replaces (other samples picked) is not wanted any more.
232
+ if (typeof body.replace === 'string' && body.replace !== voice.id)
233
+ await dropTrial(api, body.replace);
234
+ return json({ voice: trialOf(voice) }, 201);
235
+ }
236
+ catch (err) {
237
+ return apiError(err);
238
+ }
239
+ },
240
+ },
241
+ {
242
+ method: 'get',
243
+ path: '/:id/vocalstack/voice/trial',
244
+ handler: async (req) => {
245
+ const found = await open(req, 'create');
246
+ if (found instanceof Response)
247
+ return found;
248
+ try {
249
+ const voice = await found.api.voice(req.searchParams.get('voice') ?? '');
250
+ if (!voice.draft)
251
+ return json({ error: 'Not a trial voice.' }, 404);
252
+ return json({ voice: trialOf(voice) });
253
+ }
254
+ catch (err) {
255
+ return apiError(err);
256
+ }
257
+ },
258
+ },
259
+ {
260
+ method: 'get',
261
+ path: '/:id/vocalstack/voice/trial/preview',
262
+ handler: async (req) => {
263
+ const found = await open(req, 'hear');
264
+ if (found instanceof Response)
265
+ return found;
266
+ const format = req.searchParams.get('format') === 'caf' ? 'caf' : 'ogg';
267
+ try {
268
+ const voice = await found.api.voice(req.searchParams.get('voice') ?? '');
269
+ if (!voice.draft)
270
+ return json({ error: 'Not a trial voice.' }, 404);
271
+ const res = await found.api.voicePreview(voice.id, req.searchParams.get('lang') ?? undefined, format);
272
+ if (res.status === 202)
273
+ return json({ pending: true }, 202);
274
+ if (!res.ok)
275
+ return json({ error: `VocalStack answered ${res.status}` }, res.status >= 500 ? 502 : res.status);
276
+ return new Response(res.body, { headers: { 'cache-control': 'private, max-age=600', 'content-type': res.headers.get('content-type') ?? 'audio/ogg' } });
277
+ }
278
+ catch (err) {
279
+ return apiError(err);
280
+ }
281
+ },
282
+ },
283
+ {
284
+ // Keep the trial as their voice (with their permission); the voice they had before goes.
285
+ method: 'post',
286
+ path: '/:id/vocalstack/voice/trial/keep',
287
+ handler: async (req) => {
288
+ const found = await open(req, 'create');
289
+ if (found instanceof Response)
290
+ return found;
291
+ const { api, doc, id } = found;
292
+ const body = (await req.json?.().catch(() => ({})));
293
+ if (body.consent !== true)
294
+ return json({ error: 'Confirm you have their permission to clone their voice.' }, 400);
295
+ if (typeof body.voice !== 'string')
296
+ return json({ error: 'Which voice?' }, 400);
297
+ const name = (typeof body.name === 'string' && body.name.trim() ? body.name.trim() : nameOf(req, doc)).slice(0, 60);
298
+ try {
299
+ const trial = await api.voice(body.voice);
300
+ if (!trial.draft)
301
+ return json({ error: 'Not a trial voice.' }, 404);
302
+ const voice = await api.keepVoice(trial.id, name);
303
+ const previous = doc.vocalstackVoice?.voiceId;
304
+ const data = await save(req, id, { ...fieldData(voice), consentAt: new Date().toISOString() });
305
+ if (previous && previous !== voice.id)
306
+ await api.deleteVoice(previous).catch(() => undefined);
307
+ return json({ name: nameOf(req, doc), vocalstackVoice: data });
308
+ }
309
+ catch (err) {
310
+ return apiError(err);
311
+ }
312
+ },
313
+ },
314
+ {
315
+ method: 'delete',
316
+ path: '/:id/vocalstack/voice/trial',
317
+ handler: async (req) => {
318
+ const found = await open(req, 'create');
319
+ if (found instanceof Response)
320
+ return found;
321
+ await dropTrial(found.api, req.searchParams.get('voice') ?? '');
322
+ return json({ ok: true });
323
+ },
324
+ },
193
325
  {
194
326
  method: 'get',
195
327
  path: '/:id/vocalstack/voice/preview',
@@ -217,19 +349,24 @@ export function voiceEndpoints(config, options) {
217
349
  },
218
350
  ];
219
351
  }
220
- let languages;
221
352
  /**
222
- * Shared admin lookups (signed in, and `options.access` when set):
223
- * GET /vocalstack/languages what can be translated and spoken
224
- * GET /vocalstack/voices?lang=&recording= voices that can speak a language
353
+ * Shared lookups:
354
+ * GET /vocalstack/languages what can be translated and spoken (public with `listeners` on)
355
+ * GET /vocalstack/voices?lang=&recording= voices that can speak a language (signed in, and `options.access`)
225
356
  */
226
357
  export function lookupEndpoints(options) {
227
358
  const apiURL = options.apiURL ?? DEFAULT_API_URL;
228
- const api = async (req) => {
359
+ const listeners = listenerOptions(options);
360
+ const allowed = async (req) => {
229
361
  if (!req.user)
230
362
  return json({ error: 'Sign in first.' }, 401);
231
363
  if (options.access && !(await options.access({ req })))
232
364
  return json({ error: 'You may not use VocalStack here.' }, 403);
365
+ };
366
+ const api = async (req) => {
367
+ const refused = await allowed(req);
368
+ if (refused)
369
+ return refused;
233
370
  const apiKey = await resolveAPIKey(req, options);
234
371
  if (!apiKey)
235
372
  return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
@@ -240,17 +377,16 @@ export function lookupEndpoints(options) {
240
377
  method: 'get',
241
378
  path: '/vocalstack/languages',
242
379
  handler: async (req) => {
243
- const client = await api(req);
244
- if (client instanceof Response)
245
- return client;
246
- try {
247
- if (!languages || Date.now() - languages.at > 3600_000)
248
- languages = { at: Date.now(), value: await client.languages() };
249
- return json(languages.value);
250
- }
251
- catch (err) {
252
- return apiError(err);
380
+ // Listeners pick from the languages the site offers them; editors see all of VocalStack's.
381
+ if (!req.user && listeners) {
382
+ return json(forListeners(await languageList(req, options), listeners), 200, { 'cache-control': 'public, max-age=3600, s-maxage=3600' });
253
383
  }
384
+ const refused = await allowed(req);
385
+ if (refused)
386
+ return refused;
387
+ if (!(await resolveAPIKey(req, options)))
388
+ return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
389
+ return json(await languageList(req, options));
254
390
  },
255
391
  },
256
392
  {
package/dist/index.d.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  import type { Plugin } from 'payload';
2
- import type { VocalStackPluginOptions, VoiceFieldData } from './types.js';
2
+ import type { VocalStackPluginOptions } from './types.js';
3
3
  export type * from './types.js';
4
4
  export { spokenSentences, timedTokens, transcriptText } from './text.js';
5
- /** The voice to read translations in (`clone:<id>`), once a person's cloned voice is ready. */
6
- export declare const clonedVoiceKey: (data?: null | VoiceFieldData) => string | undefined;
7
5
  export declare const vocalstackPlugin: (options?: VocalStackPluginOptions) => Plugin;
package/dist/index.js CHANGED
@@ -1,13 +1,11 @@
1
1
  import { connectionEndpoints } from './endpoints/connection.js';
2
- import { speechEndpoints } from './endpoints/speech.js';
2
+ import { refreshAfterRead, speechEndpoints } from './endpoints/speech.js';
3
3
  import { streamEndpoint } from './endpoints/stream.js';
4
4
  import { transcribeEndpoints } from './endpoints/transcribe.js';
5
5
  import { lookupEndpoints, voiceEndpoints } from './endpoints/voices.js';
6
6
  import { readingsCollection, readingsSlug } from './readings.js';
7
7
  import { settingsGlobal } from './settings.js';
8
8
  export { spokenSentences, timedTokens, transcriptText } from './text.js';
9
- /** The voice to read translations in (`clone:<id>`), once a person's cloned voice is ready. */
10
- export const clonedVoiceKey = (data) => data?.state === 'ready' && data.voiceId ? `clone:${data.voiceId}` : undefined;
11
9
  const isAudioDoc = (data) => typeof data?.mimeType === 'string' && data.mimeType.startsWith('audio/');
12
10
  /** An upload collection that can hold audio: `audio/*`, a wildcard, or no restriction at all. */
13
11
  function acceptsAudio(collection) {
@@ -68,6 +66,8 @@ function transcriptionFields(enabled, options, target) {
68
66
  { name: 'translations', type: 'json', ...hidden },
69
67
  // { [lang]: { voice, state, …, sentences } }: translations read aloud, in the reading's timing.
70
68
  { name: 'speech', type: 'json', ...hidden },
69
+ // Readings in speakers' cloned voices, or in stock ones (set from the translations panel).
70
+ { name: 'voices', type: 'select', defaultValue: 'synthetic', options: ['synthetic', 'cloned'], ...hidden },
71
71
  ...(enabled
72
72
  ? [
73
73
  {
@@ -113,6 +113,20 @@ function voiceFields(enabled) {
113
113
  },
114
114
  ];
115
115
  }
116
+ /** Readings still being made when a document is read: brought up to date after the response, for whoever reads next. */
117
+ const readingsAfterRead = (options, rowFields, isUpload) => ({ collection, doc, req }) => {
118
+ if (!doc?.id)
119
+ return doc;
120
+ if (isUpload)
121
+ refreshAfterRead(req.payload, collection.slug, options, rowFields, doc.id, doc.vocalstack);
122
+ for (const { field } of rowFields) {
123
+ for (const row of doc[field] ?? []) {
124
+ if (row?.id && row.vocalstack && typeof row.vocalstack === 'object')
125
+ refreshAfterRead(req.payload, collection.slug, options, rowFields, doc.id, row.vocalstack, { field, row: row.id });
126
+ }
127
+ }
128
+ return doc;
129
+ };
116
130
  /** Add fields to the named array, looking through unnamed containers (rows, collapsibles, unnamed tabs). */
117
131
  function addToArray(fields, name, extra) {
118
132
  let found = false;
@@ -176,6 +190,9 @@ export const vocalstackPlugin = (options = {}) => (config) => {
176
190
  ]
177
191
  : collection.endpoints,
178
192
  fields,
193
+ hooks: enabled
194
+ ? { ...collection.hooks, afterRead: [...(collection.hooks?.afterRead ?? []), readingsAfterRead(options, rowFields, isUpload)] }
195
+ : collection.hooks,
179
196
  };
180
197
  }),
181
198
  endpoints: enabled ? [...(config.endpoints ?? []), ...connectionEndpoints(options), ...lookupEndpoints(options)] : config.endpoints,
@@ -0,0 +1,17 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { ListenerOptions, VocalStackPluginOptions } from './types.js';
3
+ import { type Languages } from './api.js';
4
+ /** The most languages one recording is translated or read into, besides its spoken one (VocalStack's limit). */
5
+ export declare const LANGUAGE_LIMIT = 10;
6
+ /**
7
+ * What VocalStack translates and reads aloud: asked now and then, and remembered. While
8
+ * VocalStack cannot be asked, the last answer (or the list shipped with the plugin) stands in,
9
+ * so a site never loses its language list to an outage.
10
+ */
11
+ export declare function languageList(req: PayloadRequest, options: VocalStackPluginOptions): Promise<Languages>;
12
+ /** The listener options, or nothing when listeners may not ask for languages. */
13
+ export declare const listenerOptions: (options: VocalStackPluginOptions) => ListenerOptions | undefined;
14
+ /** The languages listeners are offered: VocalStack's, narrowed to the site's own list when it has one. */
15
+ export declare function forListeners(all: Languages, listeners: ListenerOptions): Languages;
16
+ /** Whether this visitor may ask for another new language now; counts it when so. */
17
+ export declare function allowNewLanguage(req: PayloadRequest, perHour: number): boolean;
@@ -0,0 +1,64 @@
1
+ import { DEFAULT_API_URL, VocalStackAPI } from './api.js';
2
+ import { LANGUAGES_SNAPSHOT } from './languagesSnapshot.js';
3
+ import { resolveAPIKey } from './settings.js';
4
+ /** The most languages one recording is translated or read into, besides its spoken one (VocalStack's limit). */
5
+ export const LANGUAGE_LIMIT = 10;
6
+ let cached;
7
+ const FRESH_MS = 3600_000;
8
+ /**
9
+ * What VocalStack translates and reads aloud: asked now and then, and remembered. While
10
+ * VocalStack cannot be asked, the last answer (or the list shipped with the plugin) stands in,
11
+ * so a site never loses its language list to an outage.
12
+ */
13
+ export async function languageList(req, options) {
14
+ if (cached && Date.now() - cached.at < FRESH_MS)
15
+ return cached.value;
16
+ try {
17
+ const apiKey = await resolveAPIKey(req, options);
18
+ if (!apiKey)
19
+ return cached?.value ?? LANGUAGES_SNAPSHOT;
20
+ const value = await new VocalStackAPI(apiKey, options.apiURL ?? DEFAULT_API_URL).languages();
21
+ if (value?.languages?.length)
22
+ cached = { at: Date.now(), value };
23
+ return cached?.value ?? LANGUAGES_SNAPSHOT;
24
+ }
25
+ catch {
26
+ // Ask again in a few minutes rather than on every request.
27
+ if (cached)
28
+ cached = { ...cached, at: Date.now() - FRESH_MS + 300_000 };
29
+ return cached?.value ?? LANGUAGES_SNAPSHOT;
30
+ }
31
+ }
32
+ /** The listener options, or nothing when listeners may not ask for languages. */
33
+ export const listenerOptions = (options) => !options.listeners ? undefined : options.listeners === true ? {} : options.listeners;
34
+ /** The languages listeners are offered: VocalStack's, narrowed to the site's own list when it has one. */
35
+ export function forListeners(all, listeners) {
36
+ if (!listeners.languages?.length)
37
+ return all;
38
+ const allowed = new Set(listeners.languages.map((l) => l.toLowerCase()));
39
+ const languages = all.languages.filter((l) => allowed.has(l.code));
40
+ return {
41
+ languages,
42
+ translation: languages.filter((l) => l.translation).map((l) => l.code),
43
+ voice: languages.filter((l) => l.voice).map((l) => l.code),
44
+ };
45
+ }
46
+ /** New languages asked for, by visitor, this hour (on this server). */
47
+ const asked = new Map();
48
+ /** Whether this visitor may ask for another new language now; counts it when so. */
49
+ export function allowNewLanguage(req, perHour) {
50
+ const ip = (req.headers.get('x-forwarded-for')?.split(',')[0] ?? req.headers.get('x-real-ip') ?? 'unknown').trim();
51
+ const now = Date.now();
52
+ const recent = (asked.get(ip) ?? []).filter((t) => now - t < 3600_000);
53
+ if (recent.length >= perHour) {
54
+ asked.set(ip, recent);
55
+ return false;
56
+ }
57
+ recent.push(now);
58
+ asked.set(ip, recent);
59
+ if (asked.size > 5000)
60
+ for (const [k, v] of asked)
61
+ if (!v.some((t) => now - t < 3600_000))
62
+ asked.delete(k);
63
+ return true;
64
+ }
@@ -0,0 +1,2 @@
1
+ import type { Languages } from './api.js';
2
+ export declare const LANGUAGES_SNAPSHOT: Languages;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * VocalStack's languages as they were when this version was built: what listeners are
3
+ * offered while VocalStack cannot be asked (it is down, or not connected yet).
4
+ * [code, name, native name, read aloud]
5
+ */
6
+ const ROWS = [
7
+ ["af", "Afrikaans", "Afrikaans", false],
8
+ ["am", "Amharic", "አማርኛ", false],
9
+ ["ar", "Arabic", "العربية", true],
10
+ ["as", "Assamese", "অসমীয়া", false],
11
+ ["az", "Azerbaijani", "Azərbaycan dili", false],
12
+ ["ba", "Bashkir", "Башҡортса", false],
13
+ ["be", "Belarusian", "Беларуская", false],
14
+ ["bg", "Bulgarian", "Български", true],
15
+ ["bn", "Bengali", "বাংলা", true],
16
+ ["bo", "Tibetan", "བོད་སྐད་", false],
17
+ ["br", "Breton", "Brezhoneg", false],
18
+ ["bs", "Bosnian", "Bosanski", false],
19
+ ["ca", "Catalan", "Català", true],
20
+ ["cs", "Czech", "Čeština", true],
21
+ ["cy", "Welsh", "Cymraeg", true],
22
+ ["da", "Danish", "Dansk", true],
23
+ ["de", "German", "Deutsch", true],
24
+ ["el", "Greek", "Ελληνικά", true],
25
+ ["en", "English", "English", true],
26
+ ["es", "Spanish", "Español", true],
27
+ ["et", "Estonian", "Eesti", true],
28
+ ["eu", "Basque", "Euskara", true],
29
+ ["fa", "Persian", "فارسی", true],
30
+ ["fi", "Finnish", "Suomi", true],
31
+ ["fo", "Faroese", "Føroyskt", false],
32
+ ["fr", "French", "Français", true],
33
+ ["gl", "Galician", "Galego", false],
34
+ ["gu", "Gujarati", "ગુજરાતી", false],
35
+ ["ha", "Hausa", "Hausa", false],
36
+ ["haw", "Hawaiian", "ʻŌlelo Hawaiʻi", false],
37
+ ["he", "Hebrew", "עברית", true],
38
+ ["hi", "Hindi", "हिन्दी", true],
39
+ ["hr", "Croatian", "Hrvatski", true],
40
+ ["ht", "Haitian Creole", "Kreyòl ayisyen", false],
41
+ ["hu", "Hungarian", "Magyar", true],
42
+ ["hy", "Armenian", "Հայերեն", true],
43
+ ["id", "Indonesian", "Bahasa Indonesia", true],
44
+ ["is", "Icelandic", "Íslenska", true],
45
+ ["it", "Italian", "Italiano", true],
46
+ ["ja", "Japanese", "日本語", true],
47
+ ["jw", "Javanese", "Basa Jawa", false],
48
+ ["ka", "Georgian", "ქართული", true],
49
+ ["kk", "Kazakh", "Қазақ тілі", true],
50
+ ["km", "Khmer", "ខ្មែរ", false],
51
+ ["kn", "Kannada", "ಕನ್ನಡ", false],
52
+ ["ko", "Korean", "한국어", true],
53
+ ["la", "Latin", "Latina", false],
54
+ ["lb", "Luxembourgish", "Lëtzebuergesch", true],
55
+ ["ln", "Lingala", "Lingála", false],
56
+ ["lo", "Lao", "ລາວ", false],
57
+ ["lt", "Lithuanian", "Lietuvių", true],
58
+ ["lv", "Latvian", "Latviešu", true],
59
+ ["mg", "Malagasy", "Malagasy", false],
60
+ ["mi", "Māori", "Te Reo Māori", false],
61
+ ["mk", "Macedonian", "Македонски", false],
62
+ ["ml", "Malayalam", "മലയാളം", true],
63
+ ["mn", "Mongolian", "Монгол", false],
64
+ ["mr", "Marathi", "मराठी", true],
65
+ ["ms", "Malay", "Bahasa Melayu", false],
66
+ ["mt", "Maltese", "Malti", false],
67
+ ["my", "Burmese", "မြန်မာစာ", false],
68
+ ["ne", "Nepali", "नेपाली", true],
69
+ ["nl", "Dutch", "Nederlands", true],
70
+ ["nn", "Norwegian Nynorsk", "Nynorsk", false],
71
+ ["no", "Norwegian", "Norsk", true],
72
+ ["oc", "Occitan", "Occitan", false],
73
+ ["pa", "Punjabi", "ਪੰਜਾਬੀ", false],
74
+ ["pl", "Polish", "Polski", true],
75
+ ["ps", "Pashto", "پښتو", false],
76
+ ["pt", "Portuguese", "Português", true],
77
+ ["ro", "Romanian", "Română", true],
78
+ ["ru", "Russian", "Русский", true],
79
+ ["sa", "Sanskrit", "संस्कृतम्", false],
80
+ ["sd", "Sindhi", "سنڌي", false],
81
+ ["si", "Sinhala", "සිංහල", false],
82
+ ["sk", "Slovak", "Slovenčina", true],
83
+ ["sl", "Slovenian", "Slovenščina", true],
84
+ ["sn", "Shona", "chiShona", false],
85
+ ["so", "Somali", "Soomaali", false],
86
+ ["sq", "Albanian", "Shqip", true],
87
+ ["sr", "Serbian", "Српски", true],
88
+ ["su", "Sundanese", "Basa Sunda", false],
89
+ ["sv", "Swedish", "Svenska", true],
90
+ ["sw", "Swahili", "Kiswahili", true],
91
+ ["ta", "Tamil", "தமிழ்", false],
92
+ ["te", "Telugu", "తెలుగు", true],
93
+ ["tg", "Tajik", "Тоҷикӣ", false],
94
+ ["th", "Thai", "ไทย", true],
95
+ ["tk", "Turkmen", "Türkmençe", false],
96
+ ["tl", "Tagalog", "Tagalog", false],
97
+ ["tr", "Turkish", "Türkçe", true],
98
+ ["tt", "Tatar", "Татарча", false],
99
+ ["uk", "Ukrainian", "Українська", true],
100
+ ["ur", "Urdu", "اردو", true],
101
+ ["uz", "Uzbek", "Oʻzbekcha", false],
102
+ ["vi", "Vietnamese", "Tiếng Việt", true],
103
+ ["yi", "Yiddish", "ייִדיש", false],
104
+ ["yo", "Yoruba", "Yorùbá", false],
105
+ ["yue", "Cantonese", "粵語", false],
106
+ ["zh", "Chinese", "中文", true],
107
+ ];
108
+ export const LANGUAGES_SNAPSHOT = {
109
+ languages: ROWS.map(([code, name, native, voice]) => ({ code, name, native, translation: true, voice })),
110
+ translation: ROWS.map(([code]) => code),
111
+ voice: ROWS.filter(([, , , voice]) => voice).map(([code]) => code),
112
+ };
package/dist/types.d.ts CHANGED
@@ -67,15 +67,37 @@ export type VocalStackPluginOptions = {
67
67
  */
68
68
  voices?: VoiceCollectionConfig[];
69
69
  /**
70
- * The VocalStack voice (`clone:<id>`, `F1`, …) a transcript's translations are spoken in
71
- * by default, e.g. the cloned voice of the person speaking. Nothing: VocalStack's default.
70
+ * Let the site's visitors ask for a transcript in their own language: it is translated,
71
+ * read aloud where VocalStack has a voice for it, and kept on the document (and the
72
+ * readings collection) like an editor's. Off by default. `true` allows every language
73
+ * VocalStack translates; see {@link ListenerOptions}.
72
74
  */
73
- speechVoice?: (args: {
75
+ listeners?: boolean | ListenerOptions;
76
+ /**
77
+ * Whether a transcript is read in its speakers' cloned voices or in synthetic ones, decided by
78
+ * the site (e.g. from the person speaking: `cloned` once they have a voice). `cloned` reads each
79
+ * speaker in their clone where VocalStack has one for them, and in a stock voice otherwise.
80
+ * Answer nothing to leave it to the transcript's own toggle. When set, the toggle is not shown.
81
+ */
82
+ voiceMode?: (args: {
74
83
  collection: CollectionSlug;
75
84
  doc: Record<string, unknown>;
76
85
  req: PayloadRequest;
77
86
  row?: ArrayRow;
78
- }) => Promise<string | undefined> | string | undefined;
87
+ }) => Promise<undefined | VoiceMode> | undefined | VoiceMode;
88
+ };
89
+ export type ListenerOptions = {
90
+ /** Languages visitors may ask for. Default: every language VocalStack translates. */
91
+ languages?: string[];
92
+ /** Read new languages aloud too, where VocalStack has a voice for them. Default `true`. */
93
+ speak?: boolean;
94
+ /** Who may ask for a new language. Default: anyone who may read the document. */
95
+ access?: (args: {
96
+ lang: string;
97
+ req: PayloadRequest;
98
+ }) => boolean | Promise<boolean>;
99
+ /** New languages one visitor (by IP address) may ask for in an hour, on this server. Default 10. */
100
+ perHour?: number;
79
101
  };
80
102
  export type VoiceCollectionConfig = {
81
103
  collection: CollectionSlug;
@@ -109,10 +131,21 @@ export type VoiceFieldData = {
109
131
  export type Translation = {
110
132
  /** The transcript's sentences (same ids and times), their text translated. */
111
133
  sentences: TranscriptSentence[];
112
- translatedAt: string;
134
+ translatedAt: null | string;
135
+ /**
136
+ * Asked for and not finished: the server carries on translating (when the document is
137
+ * read, or its progress asked for) until every sentence is done, with no one watching.
138
+ */
139
+ pending?: boolean;
140
+ /** Why translating stopped, when it failed for good. */
141
+ error?: null | string;
142
+ requestedAt?: null | string;
113
143
  };
114
- export type SpeechState = 'failed' | 'queued' | 'running' | 'sealed';
144
+ /** `translating`: asked for, waiting for its translation to finish before VocalStack reads it. */
145
+ export type SpeechState = 'failed' | 'queued' | 'running' | 'sealed' | 'translating';
115
146
  export type Speech = {
147
+ /** While it is made: how many sentences have been voiced so far. */
148
+ done?: null | number;
116
149
  durationS?: null | number;
117
150
  error?: null | string;
118
151
  renderedAt?: null | string;
@@ -120,7 +153,11 @@ export type Speech = {
120
153
  /** Once sealed: the translated sentences in the spoken track's timing, with their words. */
121
154
  sentences?: null | TranscriptSentence[];
122
155
  state: SpeechState;
123
- /** The voice it is spoken in; `null` for VocalStack's default. */
156
+ /** Read in speakers' cloned voices, or in stock (synthetic) ones. */
157
+ cast?: null | VoiceMode;
158
+ /** What VocalStack read it in: `cloned`, `synthetic`, or `mixed` (some speakers had no usable clone). */
159
+ readIn?: 'cloned' | 'mixed' | 'synthetic' | null;
160
+ /** VocalStack's key for the voices it is read in (e.g. `cast:-1=M1`); `null` until VocalStack says. */
124
161
  voice: null | string;
125
162
  /** Once sealed: the reading's MP3, saved once in the readings upload collection and served from there. */
126
163
  audio?: null | {
@@ -171,7 +208,11 @@ export type VocalStackFieldData = {
171
208
  translations?: null | Record<string, Translation>;
172
209
  /** Spoken translations, by language code. */
173
210
  speech?: null | Record<string, Speech>;
211
+ /** The voices readings of this transcript are made in. Default `synthetic`. */
212
+ voices?: null | VoiceMode;
174
213
  };
214
+ /** `cloned`: each speaker's own cloned voice, where they have one; `synthetic`: VocalStack's stock voices. */
215
+ export type VoiceMode = 'cloned' | 'synthetic';
175
216
  /** [start, end, text], seconds. */
176
217
  export type TranscriptWord = [number, number, string];
177
218
  export type TranscriptSentence = {
@@ -208,10 +249,35 @@ export type ConnectionResponse = {
208
249
  /** `options`: the key is in the plugin config; `admin`: connected from the admin panel. */
209
250
  source?: 'admin' | 'options';
210
251
  };
252
+ /** Where one language of a transcript stands, for a listener: what the listen endpoint answers. */
253
+ export type ListenStatus = {
254
+ lang: string;
255
+ /** `ready`: it can be read (and heard, when `speech` is `ready`). `none`: never asked for. */
256
+ state: 'failed' | 'none' | 'ready' | 'translating';
257
+ /** Sentences translated so far, and in all. */
258
+ done: number;
259
+ total: number;
260
+ error?: null | string;
261
+ /** Whether VocalStack reads this language aloud. */
262
+ voice: boolean;
263
+ speech?: {
264
+ /** Sentences read so far (while `reading`). */
265
+ done?: null | number;
266
+ /** The reading's MP3, kept in the site's own storage, once ready. */
267
+ audio?: null | string;
268
+ error?: null | string;
269
+ state: 'failed' | 'reading' | 'ready' | 'waiting';
270
+ } | null;
271
+ /** Changes whenever the translation or the reading does: a cache key for the text and audio. */
272
+ version: string;
273
+ };
211
274
  /** What the translate and speak endpoints answer. */
212
275
  export type SpeechResponse = {
213
- /** The voice readings use unless one is picked (`speechVoice`); `null`: VocalStack's default. */
214
- defaultVoice?: null | string;
276
+ /** The voices readings are made in now, and whether the site decides it (`voiceMode`) rather than the toggle. */
277
+ voiceMode?: {
278
+ fixed: boolean;
279
+ mode: VoiceMode;
280
+ };
215
281
  /** The translate endpoint ran out of time; call it again to carry on. */
216
282
  more?: boolean;
217
283
  vocalstack: VocalStackFieldData;