@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,18 +1,47 @@
1
+ import { after } from 'next/server.js';
2
+ import { createLocalReq } from 'payload';
1
3
  import { DEFAULT_API_URL, UNAVAILABLE, VocalStackAPI, VocalStackAPIError } from '../api.js';
4
+ import { allowNewLanguage, forListeners, LANGUAGE_LIMIT, languageList, listenerOptions } from '../languages.js';
2
5
  import { readingsSlug } from '../readings.js';
3
6
  import { resolveAPIKey } from '../settings.js';
4
7
  import { spokenSentences } from '../text.js';
5
8
  import { apiError, canUpdate, locate } from './transcribe.js';
6
- const json = (body, status = 200) => Response.json(body, { status });
9
+ const json = (body, status = 200, headers) => Response.json(body, { headers, status });
7
10
  // Translating is slow (an hour-long recording takes minutes): batches run side by side, and a call
8
11
  // stops starting new ones after a while so it answers before the host's time limit.
9
- // The client calls again to carry on; what is done is saved each time.
12
+ // What is done is saved each time.
10
13
  const BATCH = 30;
11
14
  const PARALLEL = 4;
12
15
  const BUDGET_MS = 150_000;
16
+ // A step of translating: saved when it ends, so whoever watches sees the count go up.
17
+ const STEP_MS = 20_000;
18
+ // How long work carries on after a response (the host's time limit is longer).
19
+ const BACKGROUND_MS = 120_000;
13
20
  const LANG = /^[a-z]{2,3}(-[a-z0-9]+)?$/i;
14
21
  /** The transcript's sentences that can be translated: settled, numbered, with text. */
15
22
  const translatable = (data) => (Array.isArray(data.sentences) ? data.sentences : []).filter((s) => !s.draft && s.id !== undefined && s.text.trim());
23
+ /** Whether a language is fully translated (older translations, made before `pending`, are). */
24
+ export const isTranslated = (t) => Boolean(t && !t.pending && !t.error && t.sentences?.length);
25
+ /** The languages a transcript has (translated or read, asked for or done), besides the one it was spoken in. */
26
+ const languagesInUse = (data) => {
27
+ const used = new Set([...Object.keys(data.translations ?? {}), ...Object.keys(data.speech ?? {})]);
28
+ if (data.language)
29
+ used.delete(data.language);
30
+ return used;
31
+ };
32
+ /** The languages of `langs` that would go past the limit: none when they all fit. */
33
+ const pastLimit = (data, langs) => {
34
+ const used = languagesInUse(data);
35
+ const fresh = langs.filter((l) => !used.has(l));
36
+ return used.size + fresh.length > LANGUAGE_LIMIT ? fresh : [];
37
+ };
38
+ const limitError = (data) => json({
39
+ code: 'language_limit_reached',
40
+ error: `This recording is already in ${LANGUAGE_LIMIT} languages, as many as one recording may have. Use one of those, or remove one first.`,
41
+ languages: [...languagesInUse(data)],
42
+ }, 409);
43
+ /** VocalStack said no for good (a language it will not do, the language limit): asking again will not help. */
44
+ const isPermanent = (err) => err instanceof VocalStackAPIError && [400, 403, 404, 409, 422].includes(err.status) && err.code !== 'unavailable';
16
45
  /** Translate what is still missing in `lang`, within the time budget, and save it. Whether some is left, and the field as saved. */
17
46
  async function translate(api, target, lang, deadline) {
18
47
  const sentences = translatable(target.data);
@@ -29,54 +58,70 @@ async function translate(api, target, lang, deadline) {
29
58
  if (stored[String(id)]?.trim())
30
59
  got.set(id, stored[String(id)].trim());
31
60
  }
32
- catch {
61
+ catch (err) {
62
+ if (isPermanent(err))
63
+ throw err;
33
64
  // Not readable just now: translate them all instead.
34
65
  }
35
66
  const left = missing.filter((id) => !got.has(id));
36
67
  for (let i = 0; i < left.length; i += BATCH)
37
68
  batches.push(left.slice(i, i + BATCH));
38
69
  }
70
+ /** Save what is translated so far (each batch, so whoever watches sees it go up), and at the end whether some is left. */
71
+ const write = (end) => target.save((current) => {
72
+ const before = current.translations?.[lang];
73
+ const known = new Map((before?.sentences ?? []).map((s) => [s.id, s.text]));
74
+ const translation = {
75
+ ...before,
76
+ error: null,
77
+ sentences: translatable(current).flatMap(({ end, id, speaker, start }) => {
78
+ const text = got.get(id) ?? known.get(id);
79
+ return text ? [{ end, id, speaker, start, text }] : [];
80
+ }),
81
+ translatedAt: new Date().toISOString(),
82
+ ...(end && before?.pending ? { pending: end.more } : {}),
83
+ };
84
+ return { translations: { ...current.translations, [lang]: translation } };
85
+ });
39
86
  const worker = async () => {
40
87
  for (let batch = batches.shift(); batch; batch = batches.shift()) {
41
- if (Date.now() > deadline || failure)
88
+ if (Date.now() > deadline || failure) {
89
+ batches.unshift(batch);
42
90
  return;
91
+ }
43
92
  try {
44
93
  const { translations } = await api.translation(target.data.recordingId, lang, batch);
45
94
  for (const [id, text] of Object.entries(translations))
46
95
  if (text?.trim())
47
96
  got.set(Number(id), text.trim());
97
+ // More to come in this call: show this much now.
98
+ if (batches.length)
99
+ await write().catch(() => undefined);
48
100
  }
49
101
  catch (err) {
50
102
  failure ??= err;
103
+ batches.unshift(batch);
51
104
  }
52
105
  }
53
106
  };
107
+ // Read back from VocalStack's store: show those straight away, before translating the rest.
108
+ if (got.size && batches.length)
109
+ await write().catch(() => undefined);
54
110
  await Promise.all(Array.from({ length: PARALLEL }, worker));
55
- let data = target.data;
56
- if (got.size) {
57
- data = await target.save((current) => {
58
- const before = new Map((current.translations?.[lang]?.sentences ?? []).map((s) => [s.id, s.text]));
59
- const translation = {
60
- sentences: translatable(current).flatMap(({ end, id, speaker, start }) => {
61
- const text = got.get(id) ?? before.get(id);
62
- return text ? [{ end, id, speaker, start, text }] : [];
63
- }),
64
- translatedAt: new Date().toISOString(),
65
- };
66
- return { translations: { ...current.translations, [lang]: translation } };
67
- });
68
- }
69
- // Nothing came back at all: say why, rather than "call again" forever. VocalStack
70
- // answers an empty set when its translator is down, so for a language with no
71
- // translation yet that is unavailable too.
111
+ // Nothing came back at all: say why, rather than "call again" forever.
72
112
  if (failure && !got.size)
73
113
  throw failure;
74
- const ranOut = Date.now() > deadline;
75
- if (missing.length && !got.size && !have.size && !ranOut)
114
+ // Batches not sent (out of time, or after a failure) are what is left. A few sentences
115
+ // VocalStack will not translate (it answers nothing for them) do not keep it going.
116
+ const more = batches.length > 0;
117
+ // VocalStack answers an empty set when its translator is down, so for a language with
118
+ // no translation yet that is unavailable too.
119
+ if (missing.length && !got.size && !have.size && !more)
76
120
  throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
77
- // A few sentences VocalStack will not translate (it answers nothing for them) must
78
- // not keep the language "still translating": only running out of time leaves more.
79
- return { data, more: ranOut && got.size < missing.length };
121
+ const wasPending = Boolean(target.data.translations?.[lang]?.pending);
122
+ if (!got.size && !(wasPending && !more))
123
+ return { data: target.data, more };
124
+ return { data: await write({ more }), more };
80
125
  }
81
126
  /** A file name from the recording's name: `episode-12-ro.mp3`. */
82
127
  const readingName = (target, lang, voice) => `${(target.name || target.fileName.replace(/\.[^.]+$/, '')).replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80) || 'reading'}-${lang}${voice ? '-' + voice.replace(/[^\w-]+/g, '-') : ''}.mp3`;
@@ -87,9 +132,19 @@ const readingName = (target, lang, voice) => `${(target.name || target.fileName.
87
132
  async function keepReading(req, api, slug, target, lang, speech) {
88
133
  if (speech.audio || speech.state !== 'sealed')
89
134
  return speech;
90
- const src = await api.audioURL(target.data.recordingId, { kind: 'voice', lang, voice: speech.voice ?? undefined });
91
- const res = await fetch(src);
92
- if (!res.ok)
135
+ // The reading's track by its key (`cast:…`), or the default voice for older (`''`) tracks.
136
+ // A key the API does not take (400) is followed by the default.
137
+ const keys = [...new Set([speech.voice || undefined, undefined])];
138
+ let res;
139
+ for (const voice of keys) {
140
+ const src = await api.audioURL(target.data.recordingId, { kind: 'voice', lang, voice });
141
+ // The first ask makes the MP3 (a long reading takes a while); VocalStack finishes it even
142
+ // when this gives up, and a later look finds it ready.
143
+ res = await fetch(src, { signal: AbortSignal.timeout(90_000) });
144
+ if (res.status !== 400)
145
+ break;
146
+ }
147
+ if (!res?.ok)
93
148
  throw new VocalStackAPIError(502, 'unavailable', UNAVAILABLE);
94
149
  const data = Buffer.from(await res.arrayBuffer());
95
150
  const doc = (await req.payload.create({
@@ -127,8 +182,32 @@ async function sweepReadings(req, slug, data, langs) {
127
182
  if (!keep.has(String(doc.id)))
128
183
  await req.payload.delete({ collection: slug, id: doc.id, overrideAccess: true, req }).catch(() => { });
129
184
  }
130
- /** The track VocalStack made for this language in this voice. */
131
- const trackFor = (tracks, lang, speech) => tracks.find((t) => t.lang === lang && t.voiceKey === (speech.voice ?? ''));
185
+ /**
186
+ * The track VocalStack is making for this language: the one keyed as it answered when asked.
187
+ * Older readings were keyed `''`; a new one is keyed by the cast it resolved to (`cast:…`).
188
+ */
189
+ function trackFor(tracks, lang, speech) {
190
+ const mine = tracks.filter((t) => t.lang === lang);
191
+ if (speech.voice)
192
+ return mine.find((t) => keyOf(t) === speech.voice);
193
+ return mine.find((t) => keyOf(t) && t.state !== 'clips') ?? mine.find((t) => t.voiceKey === '');
194
+ }
195
+ /** A track's key, which `/audio?voice=` takes: its cast (`cast:0=M1;1=F1`), or `''` on older tracks. */
196
+ const keyOf = (t) => t.voiceKey;
197
+ /** The key VocalStack gave the reading it just took on for `lang`. */
198
+ const askedKey = (tracks, lang) => {
199
+ const mine = (Array.isArray(tracks) ? tracks : []).filter((t) => t.lang === lang);
200
+ const found = mine.find((t) => keyOf(t) && (t.state === 'queued' || t.state === 'running')) ?? mine.find((t) => keyOf(t));
201
+ return found ? keyOf(found) : null;
202
+ };
203
+ /** The voices readings of this transcript are made in: the site's say (`voiceMode`), else the transcript's toggle. */
204
+ async function voiceModeOf(req, collection, options, target) {
205
+ const decided = await options.voiceMode?.({ collection, doc: target.doc, req, row: target.row });
206
+ if (decided === 'cloned' || decided === 'synthetic')
207
+ return { as: { cloned: decided === 'cloned' }, fixed: true, mode: decided };
208
+ const mode = target.data.voices === 'cloned' ? 'cloned' : 'synthetic';
209
+ return { as: { cloned: mode === 'cloned' }, fixed: false, mode };
210
+ }
132
211
  /** A spoken translation brought up to date from VocalStack's track. */
133
212
  function settle(speech, track, translation) {
134
213
  if (!track) {
@@ -138,10 +217,14 @@ function settle(speech, track, translation) {
138
217
  }
139
218
  if (track.state === 'failed')
140
219
  return { ...speech, error: track.error ?? 'The reading failed.', state: 'failed' };
220
+ const readIn = track.voices ?? speech.readIn ?? null;
141
221
  if (track.state !== 'sealed')
142
- return { ...speech, error: null, state: track.state === 'queued' ? 'queued' : 'running' };
222
+ return { ...speech, done: track.clips?.length ?? 0, error: null, readIn, state: track.state === 'queued' ? 'queued' : 'running', voice: keyOf(track) || speech.voice };
143
223
  return {
144
224
  ...speech,
225
+ readIn,
226
+ voice: keyOf(track) || speech.voice,
227
+ done: null,
145
228
  durationS: track.durationS ?? null,
146
229
  error: null,
147
230
  renderedAt: new Date().toISOString(),
@@ -149,18 +232,273 @@ function settle(speech, track, translation) {
149
232
  state: 'sealed',
150
233
  };
151
234
  }
235
+ /** What is left to do on a transcript's languages. */
236
+ function waiting(data, readings) {
237
+ const all = Object.entries(data.speech ?? {});
238
+ return {
239
+ /** Readings VocalStack is making. */
240
+ pending: all.filter(([, s]) => s.state === 'queued' || s.state === 'running'),
241
+ /** Translations still to finish, and readings waiting for theirs. */
242
+ translating: [
243
+ ...new Set([
244
+ ...Object.entries(data.translations ?? {})
245
+ .filter(([, t]) => t.pending)
246
+ .map(([l]) => l),
247
+ ...all.filter(([, s]) => s.state === 'translating').map(([l]) => l),
248
+ ]),
249
+ ],
250
+ /** Finished readings whose file is not kept yet: made before readings were kept, or a download that failed. */
251
+ unkept: readings ? all.filter(([, s]) => s.state === 'sealed' && !s.audio) : [],
252
+ };
253
+ }
254
+ const hasWork = (data, readings) => {
255
+ const w = waiting(data, readings);
256
+ return Boolean(w.pending.length || w.translating.length || w.unkept.length);
257
+ };
258
+ /**
259
+ * Bring readings up to date from VocalStack, and keep each finished one's file (once;
260
+ * after that VocalStack is not asked for it again). The field as saved.
261
+ */
262
+ async function refresh(req, api, readings, target, key) {
263
+ const { pending, unkept } = waiting(target.data, readings);
264
+ if ((!pending.length && !unkept.length) || !target.data.recordingId)
265
+ return target.data;
266
+ const next = {};
267
+ if (pending.length) {
268
+ const tracks = await api.voiceTracks(target.data.recordingId);
269
+ for (const [lang, speech] of pending) {
270
+ const settled = settle(speech, trackFor(tracks, lang, speech), target.data.translations?.[lang]);
271
+ if (settled.state !== speech.state || settled.error !== speech.error || settled.done !== speech.done)
272
+ next[lang] = settled;
273
+ }
274
+ }
275
+ if (readings) {
276
+ for (const [lang, speech] of [...unkept, ...Object.entries(next)]) {
277
+ if (keeping.has(`${key}:${lang}`))
278
+ continue;
279
+ keeping.add(`${key}:${lang}`);
280
+ try {
281
+ next[lang] = await keepReading(req, api, readings, target, lang, next[lang] ?? speech);
282
+ }
283
+ catch {
284
+ // Not now: it is still playable from VocalStack, and the next look tries again.
285
+ }
286
+ finally {
287
+ keeping.delete(`${key}:${lang}`);
288
+ }
289
+ }
290
+ }
291
+ if (!Object.keys(next).length)
292
+ return target.data;
293
+ const losers = [];
294
+ const saved = await target.save((current) => {
295
+ const merged = { ...current.speech };
296
+ for (const [lang, s] of Object.entries(next)) {
297
+ // Kept by an overlapping request meanwhile (another server): theirs stays, ours goes.
298
+ const theirs = current.speech?.[lang]?.audio;
299
+ if (theirs && s.audio && theirs.id !== s.audio.id) {
300
+ losers.push(s);
301
+ merged[lang] = { ...s, audio: theirs };
302
+ }
303
+ else
304
+ merged[lang] = s;
305
+ }
306
+ return { speech: merged };
307
+ });
308
+ for (const loser of losers)
309
+ await dropReading(req, readings, loser);
310
+ // Requests on other servers can still both keep a reading: whatever the document
311
+ // does not point to, for these languages of this recording, is a spare copy.
312
+ if (readings)
313
+ await sweepReadings(req, readings, saved, Object.keys(next));
314
+ return saved;
315
+ }
316
+ /**
317
+ * Carry every language of a transcript forward, as far as `budgetMs` allows: translate what
318
+ * is asked for, step by step (each step saved), ask VocalStack to read each one aloud once its
319
+ * translation is done, then bring readings up to date and keep their files. The field as saved.
320
+ */
321
+ async function advance(req, api, readings, target, key, budgetMs, speakAs) {
322
+ const deadline = Date.now() + budgetMs;
323
+ let data = target.data;
324
+ const at = () => ({ ...target, data });
325
+ for (const lang of waiting(data, readings).translating) {
326
+ if (!data.translations?.[lang]?.pending)
327
+ continue;
328
+ try {
329
+ for (let more = true; more && Date.now() < deadline;) {
330
+ const step = await translate(api, at(), lang, Math.min(deadline, Date.now() + STEP_MS));
331
+ data = step.data;
332
+ more = step.more;
333
+ }
334
+ }
335
+ catch (err) {
336
+ // For good (a language VocalStack will not do, the limit): stop. Otherwise say why and try again later.
337
+ const permanent = isPermanent(err);
338
+ const error = err instanceof Error ? err.message : String(err);
339
+ data = await target.save((current) => {
340
+ const t = current.translations?.[lang];
341
+ const s = current.speech?.[lang];
342
+ return {
343
+ translations: { ...current.translations, [lang]: { sentences: [], translatedAt: null, ...t, error, ...(permanent ? { pending: false } : {}) } },
344
+ ...(permanent && s?.state === 'translating' ? { speech: { ...current.speech, [lang]: { ...s, error, state: 'failed' } } } : {}),
345
+ };
346
+ });
347
+ }
348
+ }
349
+ // Readings waiting for a translation that is now done.
350
+ for (const [lang, s] of Object.entries(data.speech ?? {})) {
351
+ if (s.state !== 'translating' || !isTranslated(data.translations?.[lang]) || Date.now() > deadline + 30_000)
352
+ continue;
353
+ try {
354
+ const as = await speakAs();
355
+ const tracks = await api.speak(data.recordingId, [lang], as);
356
+ const requestedAt = new Date().toISOString();
357
+ const voice = askedKey(tracks, lang);
358
+ data = await target.save((current) => ({
359
+ speech: { ...current.speech, [lang]: { ...current.speech?.[lang], cast: as.cloned ? 'cloned' : 'synthetic', error: null, requestedAt, state: 'queued', voice } },
360
+ }));
361
+ }
362
+ catch (err) {
363
+ // Busy (a few readings at a time per recording): it stays waiting and is asked for again later.
364
+ if (!isPermanent(err))
365
+ continue;
366
+ const error = err instanceof Error ? err.message : String(err);
367
+ data = await target.save((current) => ({ speech: { ...current.speech, [lang]: { ...s, error, state: 'failed' } } }));
368
+ }
369
+ }
370
+ return refresh(req, api, readings, at(), key);
371
+ }
372
+ /**
373
+ * Ask for languages: each is translated (if it is not yet) and, with `speak`, read aloud once
374
+ * translated, in the voice VocalStack picks. Only marks them; `advance` does the work. The field as saved.
375
+ */
376
+ async function requestLanguages(target, langs, opts) {
377
+ const requestedAt = new Date().toISOString();
378
+ return target.save((current) => {
379
+ const translations = { ...current.translations };
380
+ const speech = { ...current.speech };
381
+ for (const lang of langs) {
382
+ const t = translations[lang];
383
+ // New, or failed before: ask again. Pending or done: as it is.
384
+ if (!t || (!t.pending && (t.error || !t.sentences?.length))) {
385
+ translations[lang] = { sentences: t?.sentences ?? [], translatedAt: t?.translatedAt ?? null, error: null, pending: true, requestedAt };
386
+ }
387
+ const s = speech[lang];
388
+ if (opts.speak(lang) && (!s || s.state === 'failed'))
389
+ speech[lang] = { error: null, requestedAt, state: 'translating', voice: null };
390
+ }
391
+ return { speech, translations };
392
+ });
393
+ }
394
+ /** Where one language stands, for a listener. */
395
+ function listenStatus(data, lang, voice, readings) {
396
+ const total = translatable(data).length;
397
+ const t = data.translations?.[lang];
398
+ const s = data.speech?.[lang];
399
+ const state = !t ? 'none' : t.pending ? 'translating' : t.error || !t.sentences?.length ? 'failed' : 'ready';
400
+ const speech = !s
401
+ ? null
402
+ : {
403
+ audio: s.audio?.url ?? null,
404
+ done: s.done ?? null,
405
+ error: s.error ?? null,
406
+ state: s.state === 'failed'
407
+ ? 'failed'
408
+ : s.state === 'translating'
409
+ ? 'waiting'
410
+ : s.state === 'sealed' && (s.audio || !readings)
411
+ ? 'ready'
412
+ : 'reading',
413
+ };
414
+ return {
415
+ done: Math.min(t?.sentences?.length ?? 0, total),
416
+ error: t?.error ?? null,
417
+ lang,
418
+ speech,
419
+ state,
420
+ total,
421
+ version: [t?.translatedAt ?? '', s?.renderedAt ?? '', s?.audio?.id ?? ''].join('|'),
422
+ voice,
423
+ };
424
+ }
425
+ /** When each document's languages were last carried forward here, so reads ask VocalStack now and then, not every time. */
426
+ const lookedAt = new Map();
427
+ const LOOK_EVERY_MS = 20_000;
428
+ /** Documents being carried forward right now on this server. */
429
+ const working = new Set();
430
+ /**
431
+ * Carry a document's languages forward after the response (kept alive until done), so
432
+ * translations and readings finish for listeners with no one watching them.
433
+ */
434
+ function background(payload, collection, options, rowFields, id, where, force = false) {
435
+ const key = `${collection}:${id}:${where?.row ?? ''}`;
436
+ if (working.has(key))
437
+ return;
438
+ if (!force && Date.now() - (lookedAt.get(key) ?? 0) < LOOK_EVERY_MS)
439
+ return;
440
+ lookedAt.set(key, Date.now());
441
+ working.add(key);
442
+ const work = async () => {
443
+ const req = await createLocalReq({ urlSuffix: where ? `?${new URLSearchParams(where)}` : '' }, payload);
444
+ req.routeParams = { id };
445
+ const apiKey = await resolveAPIKey(req, options);
446
+ if (!apiKey)
447
+ return;
448
+ const target = await locate(req, collection, options, rowFields, 'admin');
449
+ if (target instanceof Response)
450
+ return;
451
+ await advance(req, new VocalStackAPI(apiKey, options.apiURL ?? DEFAULT_API_URL), readingsSlug(options), target, key, BACKGROUND_MS, async () => {
452
+ const fresh = await locate(req, collection, options, rowFields, 'admin');
453
+ return (await voiceModeOf(req, collection, options, fresh instanceof Response ? target : fresh)).as;
454
+ });
455
+ };
456
+ const run = () => work()
457
+ .catch((err) => payload.logger.warn({ err, msg: `VocalStack: could not carry on with the languages of ${key}` }))
458
+ .finally(() => working.delete(key));
459
+ try {
460
+ // On a request: after the response, kept alive until done.
461
+ after(run);
462
+ }
463
+ catch {
464
+ // Outside a request (a script, or work started by other work): just carry on in the background.
465
+ void run();
466
+ }
467
+ }
468
+ /** The row a request addresses (`?field=&row=`), for carrying it forward in the background. */
469
+ const rowOf = (req) => {
470
+ const field = req.searchParams.get('field');
471
+ return field ? { field, row: req.searchParams.get('row') ?? '' } : undefined;
472
+ };
473
+ /**
474
+ * A document was read with work still left on its languages: carry it forward after the
475
+ * response, so a translation or reading is ready for listeners without an editor watching.
476
+ */
477
+ export function refreshAfterRead(payload, collection, options, rowFields, id, data, where) {
478
+ if (!data?.recordingId || !hasWork(data, readingsSlug(options)))
479
+ return;
480
+ background(payload, collection, options, rowFields, id, where);
481
+ }
152
482
  /**
153
483
  * Translations of a transcript, and spoken readings of them, on the same document or
154
484
  * row as the transcript (`?field=&row=` as for transcribing):
155
- * POST /:id/vocalstack/translate { langs } translate (call again while `more`)
156
- * DELETE /:id/vocalstack/translate?lang= drop a language, spoken reading too
157
- * POST /:id/vocalstack/speak { langs, voice? } read translations aloud
158
- * GET /:id/vocalstack/speak where the readings stand
159
- * GET /:id/vocalstack/audio?lang= public: the audio, or its reading in `lang`
485
+ * POST /:id/vocalstack/translate { langs } translate (call again while `more`)
486
+ * DELETE /:id/vocalstack/translate?lang= drop a language, spoken reading too
487
+ * POST /:id/vocalstack/voices { voices } 'cloned' or 'synthetic', for readings from now on
488
+ * POST /:id/vocalstack/request { langs, speak? } translate and read aloud, carried on by the server
489
+ * POST /:id/vocalstack/speak { langs } read translations aloud (VocalStack picks the voice)
490
+ * GET /:id/vocalstack/speak where the readings stand
491
+ * GET /:id/vocalstack/audio?lang= public: the audio, or its reading in `lang`
492
+ * With `listeners` on, for anyone who may read the document:
493
+ * GET /:id/vocalstack/listen?lang= where a language stands
494
+ * POST /:id/vocalstack/listen { lang } ask for a language
160
495
  */
161
496
  export function speechEndpoints(collection, options, rowFields) {
162
497
  const apiURL = options.apiURL ?? DEFAULT_API_URL;
163
498
  const readings = readingsSlug(options);
499
+ const listeners = listenerOptions(options);
500
+ const keyOf = (req) => `${collection}:${req.routeParams?.id}:${req.searchParams.get('row') ?? ''}`;
501
+ const carryOn = (req, force = false) => background(req.payload, collection, options, rowFields, req.routeParams?.id, rowOf(req), force);
164
502
  /** An editor's target with a finished transcript, and the API to work on it. */
165
503
  const editable = async (req, verb) => {
166
504
  const id = req.routeParams?.id;
@@ -178,16 +516,15 @@ export function speechEndpoints(collection, options, rowFields) {
178
516
  return json({ error: 'Transcribe the audio first.' }, 409);
179
517
  return { api: new VocalStackAPI(apiKey, apiURL), target };
180
518
  };
181
- /** The body's languages (none of them the spoken one) and voice. */
519
+ /** The body's languages (none of them the spoken one), and whether to read them aloud. VocalStack picks the voice. */
182
520
  const bodyOf = async (req, spoken) => {
183
521
  const body = (await req.json?.().catch(() => ({})));
184
522
  const langs = Array.isArray(body.langs) ? [...new Set(body.langs.map(String).map((l) => l.toLowerCase()))] : [];
185
523
  if (!langs.length || langs.some((l) => !LANG.test(l) || l === spoken))
186
524
  return undefined;
187
- return { langs, voice: typeof body.voice === 'string' && body.voice.trim() ? body.voice.trim() : undefined };
525
+ return { langs, speak: body.speak !== false };
188
526
  };
189
- const defaultVoice = async (req, target) => (await options.speechVoice?.({ collection, doc: target.doc, req, row: target.row })) ?? null;
190
- return [
527
+ const endpoints = [
191
528
  {
192
529
  method: 'post',
193
530
  path: '/:id/vocalstack/translate',
@@ -199,7 +536,9 @@ export function speechEndpoints(collection, options, rowFields) {
199
536
  const asked = await bodyOf(req, target.data.language);
200
537
  if (!asked)
201
538
  return json({ error: 'Name the languages to translate into.' }, 400);
202
- const deadline = Date.now() + BUDGET_MS;
539
+ if (pastLimit(target.data, asked.langs).length)
540
+ return limitError(target.data);
541
+ const deadline = Date.now() + STEP_MS;
203
542
  try {
204
543
  let more = false;
205
544
  let data = target.data;
@@ -236,6 +575,41 @@ export function speechEndpoints(collection, options, rowFields) {
236
575
  return json({ vocalstack });
237
576
  },
238
577
  },
578
+ {
579
+ // Readings from now on in speakers' cloned voices, or in stock ones. Readings made before stay as they are.
580
+ method: 'post',
581
+ path: '/:id/vocalstack/voices',
582
+ handler: async (req) => {
583
+ const found = await editable(req, 'change');
584
+ if (found instanceof Response)
585
+ return found;
586
+ const body = (await req.json?.().catch(() => ({})));
587
+ if (body.voices !== 'cloned' && body.voices !== 'synthetic')
588
+ return json({ error: 'Choose cloned or synthetic voices.' }, 400);
589
+ const voices = body.voices;
590
+ const vocalstack = await found.target.save(() => ({ voices }));
591
+ return json({ vocalstack });
592
+ },
593
+ },
594
+ {
595
+ method: 'post',
596
+ path: '/:id/vocalstack/request',
597
+ handler: async (req) => {
598
+ const found = await editable(req, 'translate');
599
+ if (found instanceof Response)
600
+ return found;
601
+ const { target } = found;
602
+ const asked = await bodyOf(req, target.data.language);
603
+ if (!asked)
604
+ return json({ error: 'Name the languages to add.' }, 400);
605
+ if (pastLimit(target.data, asked.langs).length)
606
+ return limitError(target.data);
607
+ const voiced = new Set((await languageList(req, options)).voice);
608
+ const vocalstack = await requestLanguages(target, asked.langs, { speak: (l) => asked.speak && voiced.has(l) });
609
+ carryOn(req, true);
610
+ return json({ vocalstack }, 202);
611
+ },
612
+ },
239
613
  {
240
614
  method: 'post',
241
615
  path: '/:id/vocalstack/speak',
@@ -247,28 +621,32 @@ export function speechEndpoints(collection, options, rowFields) {
247
621
  const asked = await bodyOf(req, target.data.language);
248
622
  if (!asked)
249
623
  return json({ error: 'Name the languages to read out.' }, 400);
250
- const { langs } = asked;
251
- const voice = asked.voice ?? (await defaultVoice(req, target)) ?? undefined;
624
+ if (pastLimit(target.data, asked.langs).length)
625
+ return limitError(target.data);
252
626
  try {
253
- // A reading speaks the translation, so every language needs one first.
254
- const deadline = Date.now() + BUDGET_MS;
627
+ // A reading speaks the translation: those not translated yet are read once they are.
628
+ const ready = asked.langs.filter((l) => isTranslated(target.data.translations?.[l]));
629
+ const later = asked.langs.filter((l) => !ready.includes(l));
255
630
  let data = target.data;
256
- for (const lang of langs) {
257
- if (data.translations?.[lang]?.sentences.length)
258
- continue;
259
- const done = await translate(api, { ...target, data }, lang, deadline);
260
- data = done.data;
261
- if (done.more)
262
- return json({ code: 'translating', error: 'Still translating; try again in a moment.' }, 409);
631
+ if (ready.length) {
632
+ const { as } = await voiceModeOf(req, collection, options, target);
633
+ const tracks = await api.speak(target.data.recordingId, ready, as);
634
+ for (const lang of ready)
635
+ await dropReading(req, readings, data.speech?.[lang]);
636
+ const requestedAt = new Date().toISOString();
637
+ const cast = as.cloned ? 'cloned' : 'synthetic';
638
+ data = await target.save((current) => ({
639
+ speech: {
640
+ ...current.speech,
641
+ ...Object.fromEntries(ready.map((l) => [l, { cast, error: null, requestedAt, state: 'queued', voice: askedKey(tracks, l) }])),
642
+ },
643
+ }));
263
644
  }
264
- await api.speak(target.data.recordingId, langs, voice);
265
- for (const lang of langs)
266
- await dropReading(req, readings, data.speech?.[lang]);
267
- const requestedAt = new Date().toISOString();
268
- const vocalstack = await target.save((current) => ({
269
- speech: { ...current.speech, ...Object.fromEntries(langs.map((l) => [l, { error: null, requestedAt, state: 'queued', voice: voice ?? null }])) },
270
- }));
271
- return json({ defaultVoice: await defaultVoice(req, target), vocalstack }, 202);
645
+ if (later.length) {
646
+ data = await requestLanguages({ ...target, data }, later, { speak: () => true });
647
+ carryOn(req, true);
648
+ }
649
+ return json({ vocalstack: data }, 202);
272
650
  }
273
651
  catch (err) {
274
652
  return apiError(err);
@@ -284,70 +662,21 @@ export function speechEndpoints(collection, options, rowFields) {
284
662
  const target = await locate(req, collection, options, rowFields, 'user');
285
663
  if (target instanceof Response)
286
664
  return target;
287
- const all = Object.entries(target.data.speech ?? {});
288
- const pending = all.filter(([, s]) => s.state === 'queued' || s.state === 'running');
289
- // Finished readings whose file is not kept yet (made before readings were kept, or a download that failed).
290
- const unkept = readings ? all.filter(([, s]) => s.state === 'sealed' && !s.audio) : [];
291
- const answer = async (vocalstack) => json({ defaultVoice: await defaultVoice(req, target), vocalstack });
292
- if ((!pending.length && !unkept.length) || !target.data.recordingId)
665
+ const { fixed, mode } = await voiceModeOf(req, collection, options, target);
666
+ const voiceMode = { fixed, mode };
667
+ const answer = (vocalstack) => json({ vocalstack, voiceMode });
668
+ if (!target.data.recordingId || !hasWork(target.data, readings))
669
+ return answer(target.data);
670
+ // Translating goes on in the background; readings are looked at now.
671
+ if (waiting(target.data, readings).translating.length)
672
+ carryOn(req);
673
+ if (working.has(keyOf(req)))
293
674
  return answer(target.data);
294
675
  const apiKey = await resolveAPIKey(req, options);
295
676
  if (!apiKey)
296
677
  return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
297
678
  try {
298
- const api = new VocalStackAPI(apiKey, apiURL);
299
- const next = {};
300
- if (pending.length) {
301
- const tracks = await api.voiceTracks(target.data.recordingId);
302
- for (const [lang, speech] of pending) {
303
- const settled = settle(speech, trackFor(tracks, lang, speech), target.data.translations?.[lang]);
304
- if (settled.state !== speech.state || settled.error !== speech.error)
305
- next[lang] = settled;
306
- }
307
- }
308
- // Each finished reading is downloaded once and kept; after that VocalStack is not asked for it again.
309
- if (readings) {
310
- for (const [lang, speech] of [...unkept, ...Object.entries(next)]) {
311
- const key = `${collection}:${req.routeParams?.id}:${req.searchParams.get('row') ?? ''}:${lang}`;
312
- if (keeping.has(key))
313
- continue;
314
- keeping.add(key);
315
- try {
316
- const done = await keepReading(req, api, readings, target, lang, next[lang] ?? speech);
317
- next[lang] = done;
318
- }
319
- catch {
320
- // Not now: it is still playable from VocalStack, and the next look tries again.
321
- }
322
- finally {
323
- keeping.delete(key);
324
- }
325
- }
326
- }
327
- if (!Object.keys(next).length)
328
- return answer(target.data);
329
- const losers = [];
330
- const saved = await target.save((current) => {
331
- const merged = { ...current.speech };
332
- for (const [lang, s] of Object.entries(next)) {
333
- // Kept by an overlapping request meanwhile (another server): theirs stays, ours goes.
334
- const theirs = current.speech?.[lang]?.audio;
335
- if (theirs && s.audio && theirs.id !== s.audio.id) {
336
- losers.push(s);
337
- merged[lang] = { ...s, audio: theirs };
338
- }
339
- else
340
- merged[lang] = s;
341
- }
342
- return { speech: merged };
343
- });
344
- for (const loser of losers)
345
- await dropReading(req, readings, loser);
346
- // Requests on other servers can still both keep a reading: whatever the document
347
- // does not point to, for these languages of this recording, is a spare copy.
348
- if (readings)
349
- await sweepReadings(req, readings, saved, Object.keys(next));
350
- return answer(saved);
679
+ return answer(await refresh(req, new VocalStackAPI(apiKey, apiURL), readings, target, keyOf(req)));
351
680
  }
352
681
  catch (err) {
353
682
  return apiError(err);
@@ -380,7 +709,7 @@ export function speechEndpoints(collection, options, rowFields) {
380
709
  return json({ error: 'Not available.' }, 404);
381
710
  try {
382
711
  const url = await new VocalStackAPI(apiKey, apiURL).audioURL(recordingId, spoken ? { kind: 'delivery' } : { kind: 'voice', lang, voice: reading?.voice ?? undefined });
383
- // The signed address lasts an hour; hand out the same one for a few minutes.
712
+ // The signed address lasts a while; hand out the same one for a few minutes.
384
713
  return new Response(null, { headers: { 'cache-control': 'public, max-age=300, s-maxage=300', location: url }, status: 302 });
385
714
  }
386
715
  catch (err) {
@@ -389,4 +718,77 @@ export function speechEndpoints(collection, options, rowFields) {
389
718
  },
390
719
  },
391
720
  ];
721
+ if (!listeners)
722
+ return endpoints;
723
+ /** A listener's target: readable by them, with a finished transcript. */
724
+ const readable = async (req) => {
725
+ const target = await locate(req, collection, options, rowFields, 'user');
726
+ if (target instanceof Response)
727
+ return target;
728
+ if (target.data.status !== 'done' || !target.data.recordingId)
729
+ return json({ error: 'There is no transcript to translate yet.' }, 409);
730
+ return target;
731
+ };
732
+ /** Done work may be cached a little; work under way is asked about again. */
733
+ const statusHeaders = (s) => ({
734
+ 'cache-control': s.state === 'ready' && (!s.speech || s.speech.state === 'ready' || s.speech.state === 'failed') ? 'public, max-age=30, s-maxage=30' : 'no-store',
735
+ });
736
+ return [
737
+ ...endpoints,
738
+ {
739
+ method: 'get',
740
+ path: '/:id/vocalstack/listen',
741
+ handler: async (req) => {
742
+ const target = await readable(req);
743
+ if (target instanceof Response)
744
+ return target;
745
+ const lang = req.searchParams.get('lang')?.toLowerCase() ?? '';
746
+ if (!LANG.test(lang))
747
+ return json({ error: 'Which language?' }, 400);
748
+ const voiced = new Set(forListeners(await languageList(req, options), listeners).voice);
749
+ if (hasWork(target.data, readings))
750
+ carryOn(req);
751
+ const status = listenStatus(target.data, lang, voiced.has(lang), readings);
752
+ return json(status, 200, statusHeaders(status));
753
+ },
754
+ },
755
+ {
756
+ method: 'post',
757
+ path: '/:id/vocalstack/listen',
758
+ handler: async (req) => {
759
+ const target = await readable(req);
760
+ if (target instanceof Response)
761
+ return target;
762
+ const body = (await req.json?.().catch(() => ({})));
763
+ const lang = typeof body.lang === 'string' ? body.lang.toLowerCase() : '';
764
+ if (!LANG.test(lang) || lang === target.data.language)
765
+ return json({ error: 'Which language?' }, 400);
766
+ const offered = forListeners(await languageList(req, options), listeners);
767
+ if (!offered.translation.includes(lang))
768
+ return json({ error: 'That language is not offered here.' }, 400);
769
+ const voiced = offered.voice.includes(lang);
770
+ const speak = listeners.speak !== false && voiced;
771
+ // Asked for already (by anyone): nothing new to start.
772
+ const now = listenStatus(target.data, lang, voiced, readings);
773
+ const translationAsked = now.state === 'translating' || now.state === 'ready';
774
+ const speechAsked = !speak || (now.speech && now.speech.state !== 'failed');
775
+ if (translationAsked && speechAsked) {
776
+ if (hasWork(target.data, readings))
777
+ carryOn(req);
778
+ return json(now, 200, { 'cache-control': 'no-store' });
779
+ }
780
+ if (pastLimit(target.data, [lang]).length)
781
+ return limitError(target.data);
782
+ if (listeners.access && !(await listeners.access({ lang, req })))
783
+ return json({ error: 'You may not ask for a new language here.' }, 403);
784
+ if (!(await resolveAPIKey(req, options)))
785
+ return json({ error: 'Translations are not available right now.' }, 503);
786
+ if (!allowNewLanguage(req, listeners.perHour ?? 10))
787
+ return json({ error: 'Too many new languages asked for; try again later.' }, 429);
788
+ const data = await requestLanguages(target, [lang], { speak: () => speak });
789
+ carryOn(req, true);
790
+ return json(listenStatus(data, lang, voiced, readings), 202, { 'cache-control': 'no-store' });
791
+ },
792
+ },
793
+ ];
392
794
  }