@vocalstack/payload 0.2.0 → 0.4.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 key as VocalStack knows it: its mode (`synthetic` | `cloned`) on newer APIs,
136
+ // its cast key on older ones. A key the API does not take (400) is followed by the next.
137
+ const keys = [...new Set([speech.voice ?? undefined, speech.cast ?? undefined, undefined])];
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,31 @@ 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: its mode (`synthetic` | `cloned`) where the API names one, else its cast key. */
196
+ const keyOf = (t) => (t.voice === 'synthetic' || t.voice === 'cloned' ? t.voice : t.voiceKey);
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 { fixed: true, mode: decided };
208
+ return { fixed: false, mode: target.data.voices === 'cloned' ? 'cloned' : 'synthetic' };
209
+ }
132
210
  /** A spoken translation brought up to date from VocalStack's track. */
133
211
  function settle(speech, track, translation) {
134
212
  if (!track) {
@@ -139,9 +217,11 @@ function settle(speech, track, translation) {
139
217
  if (track.state === 'failed')
140
218
  return { ...speech, error: track.error ?? 'The reading failed.', state: 'failed' };
141
219
  if (track.state !== 'sealed')
142
- return { ...speech, error: null, state: track.state === 'queued' ? 'queued' : 'running' };
220
+ return { ...speech, done: track.clips?.length ?? 0, error: null, state: track.state === 'queued' ? 'queued' : 'running', voice: keyOf(track) || speech.voice };
143
221
  return {
144
222
  ...speech,
223
+ voice: keyOf(track) || speech.voice,
224
+ done: null,
145
225
  durationS: track.durationS ?? null,
146
226
  error: null,
147
227
  renderedAt: new Date().toISOString(),
@@ -149,18 +229,273 @@ function settle(speech, track, translation) {
149
229
  state: 'sealed',
150
230
  };
151
231
  }
232
+ /** What is left to do on a transcript's languages. */
233
+ function waiting(data, readings) {
234
+ const all = Object.entries(data.speech ?? {});
235
+ return {
236
+ /** Readings VocalStack is making. */
237
+ pending: all.filter(([, s]) => s.state === 'queued' || s.state === 'running'),
238
+ /** Translations still to finish, and readings waiting for theirs. */
239
+ translating: [
240
+ ...new Set([
241
+ ...Object.entries(data.translations ?? {})
242
+ .filter(([, t]) => t.pending)
243
+ .map(([l]) => l),
244
+ ...all.filter(([, s]) => s.state === 'translating').map(([l]) => l),
245
+ ]),
246
+ ],
247
+ /** Finished readings whose file is not kept yet: made before readings were kept, or a download that failed. */
248
+ unkept: readings ? all.filter(([, s]) => s.state === 'sealed' && !s.audio) : [],
249
+ };
250
+ }
251
+ const hasWork = (data, readings) => {
252
+ const w = waiting(data, readings);
253
+ return Boolean(w.pending.length || w.translating.length || w.unkept.length);
254
+ };
255
+ /**
256
+ * Bring readings up to date from VocalStack, and keep each finished one's file (once;
257
+ * after that VocalStack is not asked for it again). The field as saved.
258
+ */
259
+ async function refresh(req, api, readings, target, key) {
260
+ const { pending, unkept } = waiting(target.data, readings);
261
+ if ((!pending.length && !unkept.length) || !target.data.recordingId)
262
+ return target.data;
263
+ const next = {};
264
+ if (pending.length) {
265
+ const tracks = await api.voiceTracks(target.data.recordingId);
266
+ for (const [lang, speech] of pending) {
267
+ const settled = settle(speech, trackFor(tracks, lang, speech), target.data.translations?.[lang]);
268
+ if (settled.state !== speech.state || settled.error !== speech.error || settled.done !== speech.done)
269
+ next[lang] = settled;
270
+ }
271
+ }
272
+ if (readings) {
273
+ for (const [lang, speech] of [...unkept, ...Object.entries(next)]) {
274
+ if (keeping.has(`${key}:${lang}`))
275
+ continue;
276
+ keeping.add(`${key}:${lang}`);
277
+ try {
278
+ next[lang] = await keepReading(req, api, readings, target, lang, next[lang] ?? speech);
279
+ }
280
+ catch {
281
+ // Not now: it is still playable from VocalStack, and the next look tries again.
282
+ }
283
+ finally {
284
+ keeping.delete(`${key}:${lang}`);
285
+ }
286
+ }
287
+ }
288
+ if (!Object.keys(next).length)
289
+ return target.data;
290
+ const losers = [];
291
+ const saved = await target.save((current) => {
292
+ const merged = { ...current.speech };
293
+ for (const [lang, s] of Object.entries(next)) {
294
+ // Kept by an overlapping request meanwhile (another server): theirs stays, ours goes.
295
+ const theirs = current.speech?.[lang]?.audio;
296
+ if (theirs && s.audio && theirs.id !== s.audio.id) {
297
+ losers.push(s);
298
+ merged[lang] = { ...s, audio: theirs };
299
+ }
300
+ else
301
+ merged[lang] = s;
302
+ }
303
+ return { speech: merged };
304
+ });
305
+ for (const loser of losers)
306
+ await dropReading(req, readings, loser);
307
+ // Requests on other servers can still both keep a reading: whatever the document
308
+ // does not point to, for these languages of this recording, is a spare copy.
309
+ if (readings)
310
+ await sweepReadings(req, readings, saved, Object.keys(next));
311
+ return saved;
312
+ }
313
+ /**
314
+ * Carry every language of a transcript forward, as far as `budgetMs` allows: translate what
315
+ * is asked for, step by step (each step saved), ask VocalStack to read each one aloud once its
316
+ * translation is done, then bring readings up to date and keep their files. The field as saved.
317
+ */
318
+ async function advance(req, api, readings, target, key, budgetMs, cloned) {
319
+ const deadline = Date.now() + budgetMs;
320
+ let data = target.data;
321
+ const at = () => ({ ...target, data });
322
+ for (const lang of waiting(data, readings).translating) {
323
+ if (!data.translations?.[lang]?.pending)
324
+ continue;
325
+ try {
326
+ for (let more = true; more && Date.now() < deadline;) {
327
+ const step = await translate(api, at(), lang, Math.min(deadline, Date.now() + STEP_MS));
328
+ data = step.data;
329
+ more = step.more;
330
+ }
331
+ }
332
+ catch (err) {
333
+ // For good (a language VocalStack will not do, the limit): stop. Otherwise say why and try again later.
334
+ const permanent = isPermanent(err);
335
+ const error = err instanceof Error ? err.message : String(err);
336
+ data = await target.save((current) => {
337
+ const t = current.translations?.[lang];
338
+ const s = current.speech?.[lang];
339
+ return {
340
+ translations: { ...current.translations, [lang]: { sentences: [], translatedAt: null, ...t, error, ...(permanent ? { pending: false } : {}) } },
341
+ ...(permanent && s?.state === 'translating' ? { speech: { ...current.speech, [lang]: { ...s, error, state: 'failed' } } } : {}),
342
+ };
343
+ });
344
+ }
345
+ }
346
+ // Readings waiting for a translation that is now done.
347
+ for (const [lang, s] of Object.entries(data.speech ?? {})) {
348
+ if (s.state !== 'translating' || !isTranslated(data.translations?.[lang]) || Date.now() > deadline + 30_000)
349
+ continue;
350
+ try {
351
+ const inClones = await cloned();
352
+ const tracks = await api.speak(data.recordingId, [lang], { cloned: inClones });
353
+ const requestedAt = new Date().toISOString();
354
+ const voice = askedKey(tracks, lang);
355
+ data = await target.save((current) => ({
356
+ speech: { ...current.speech, [lang]: { ...current.speech?.[lang], cast: inClones ? 'cloned' : 'synthetic', error: null, requestedAt, state: 'queued', voice } },
357
+ }));
358
+ }
359
+ catch (err) {
360
+ // Busy (a few readings at a time per recording): it stays waiting and is asked for again later.
361
+ if (!isPermanent(err))
362
+ continue;
363
+ const error = err instanceof Error ? err.message : String(err);
364
+ data = await target.save((current) => ({ speech: { ...current.speech, [lang]: { ...s, error, state: 'failed' } } }));
365
+ }
366
+ }
367
+ return refresh(req, api, readings, at(), key);
368
+ }
369
+ /**
370
+ * Ask for languages: each is translated (if it is not yet) and, with `speak`, read aloud once
371
+ * translated, in the voice VocalStack picks. Only marks them; `advance` does the work. The field as saved.
372
+ */
373
+ async function requestLanguages(target, langs, opts) {
374
+ const requestedAt = new Date().toISOString();
375
+ return target.save((current) => {
376
+ const translations = { ...current.translations };
377
+ const speech = { ...current.speech };
378
+ for (const lang of langs) {
379
+ const t = translations[lang];
380
+ // New, or failed before: ask again. Pending or done: as it is.
381
+ if (!t || (!t.pending && (t.error || !t.sentences?.length))) {
382
+ translations[lang] = { sentences: t?.sentences ?? [], translatedAt: t?.translatedAt ?? null, error: null, pending: true, requestedAt };
383
+ }
384
+ const s = speech[lang];
385
+ if (opts.speak(lang) && (!s || s.state === 'failed'))
386
+ speech[lang] = { error: null, requestedAt, state: 'translating', voice: null };
387
+ }
388
+ return { speech, translations };
389
+ });
390
+ }
391
+ /** Where one language stands, for a listener. */
392
+ function listenStatus(data, lang, voice, readings) {
393
+ const total = translatable(data).length;
394
+ const t = data.translations?.[lang];
395
+ const s = data.speech?.[lang];
396
+ const state = !t ? 'none' : t.pending ? 'translating' : t.error || !t.sentences?.length ? 'failed' : 'ready';
397
+ const speech = !s
398
+ ? null
399
+ : {
400
+ audio: s.audio?.url ?? null,
401
+ done: s.done ?? null,
402
+ error: s.error ?? null,
403
+ state: s.state === 'failed'
404
+ ? 'failed'
405
+ : s.state === 'translating'
406
+ ? 'waiting'
407
+ : s.state === 'sealed' && (s.audio || !readings)
408
+ ? 'ready'
409
+ : 'reading',
410
+ };
411
+ return {
412
+ done: Math.min(t?.sentences?.length ?? 0, total),
413
+ error: t?.error ?? null,
414
+ lang,
415
+ speech,
416
+ state,
417
+ total,
418
+ version: [t?.translatedAt ?? '', s?.renderedAt ?? '', s?.audio?.id ?? ''].join('|'),
419
+ voice,
420
+ };
421
+ }
422
+ /** When each document's languages were last carried forward here, so reads ask VocalStack now and then, not every time. */
423
+ const lookedAt = new Map();
424
+ const LOOK_EVERY_MS = 20_000;
425
+ /** Documents being carried forward right now on this server. */
426
+ const working = new Set();
427
+ /**
428
+ * Carry a document's languages forward after the response (kept alive until done), so
429
+ * translations and readings finish for listeners with no one watching them.
430
+ */
431
+ function background(payload, collection, options, rowFields, id, where, force = false) {
432
+ const key = `${collection}:${id}:${where?.row ?? ''}`;
433
+ if (working.has(key))
434
+ return;
435
+ if (!force && Date.now() - (lookedAt.get(key) ?? 0) < LOOK_EVERY_MS)
436
+ return;
437
+ lookedAt.set(key, Date.now());
438
+ working.add(key);
439
+ const work = async () => {
440
+ const req = await createLocalReq({ urlSuffix: where ? `?${new URLSearchParams(where)}` : '' }, payload);
441
+ req.routeParams = { id };
442
+ const apiKey = await resolveAPIKey(req, options);
443
+ if (!apiKey)
444
+ return;
445
+ const target = await locate(req, collection, options, rowFields, 'admin');
446
+ if (target instanceof Response)
447
+ return;
448
+ await advance(req, new VocalStackAPI(apiKey, options.apiURL ?? DEFAULT_API_URL), readingsSlug(options), target, key, BACKGROUND_MS, async () => {
449
+ const fresh = await locate(req, collection, options, rowFields, 'admin');
450
+ return (await voiceModeOf(req, collection, options, fresh instanceof Response ? target : fresh)).mode === 'cloned';
451
+ });
452
+ };
453
+ const run = () => work()
454
+ .catch((err) => payload.logger.warn({ err, msg: `VocalStack: could not carry on with the languages of ${key}` }))
455
+ .finally(() => working.delete(key));
456
+ try {
457
+ // On a request: after the response, kept alive until done.
458
+ after(run);
459
+ }
460
+ catch {
461
+ // Outside a request (a script, or work started by other work): just carry on in the background.
462
+ void run();
463
+ }
464
+ }
465
+ /** The row a request addresses (`?field=&row=`), for carrying it forward in the background. */
466
+ const rowOf = (req) => {
467
+ const field = req.searchParams.get('field');
468
+ return field ? { field, row: req.searchParams.get('row') ?? '' } : undefined;
469
+ };
470
+ /**
471
+ * A document was read with work still left on its languages: carry it forward after the
472
+ * response, so a translation or reading is ready for listeners without an editor watching.
473
+ */
474
+ export function refreshAfterRead(payload, collection, options, rowFields, id, data, where) {
475
+ if (!data?.recordingId || !hasWork(data, readingsSlug(options)))
476
+ return;
477
+ background(payload, collection, options, rowFields, id, where);
478
+ }
152
479
  /**
153
480
  * Translations of a transcript, and spoken readings of them, on the same document or
154
481
  * 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`
482
+ * POST /:id/vocalstack/translate { langs } translate (call again while `more`)
483
+ * DELETE /:id/vocalstack/translate?lang= drop a language, spoken reading too
484
+ * POST /:id/vocalstack/voices { voices } 'cloned' or 'synthetic', for readings from now on
485
+ * POST /:id/vocalstack/request { langs, speak? } translate and read aloud, carried on by the server
486
+ * POST /:id/vocalstack/speak { langs } read translations aloud (VocalStack picks the voice)
487
+ * GET /:id/vocalstack/speak where the readings stand
488
+ * GET /:id/vocalstack/audio?lang= public: the audio, or its reading in `lang`
489
+ * With `listeners` on, for anyone who may read the document:
490
+ * GET /:id/vocalstack/listen?lang= where a language stands
491
+ * POST /:id/vocalstack/listen { lang } ask for a language
160
492
  */
161
493
  export function speechEndpoints(collection, options, rowFields) {
162
494
  const apiURL = options.apiURL ?? DEFAULT_API_URL;
163
495
  const readings = readingsSlug(options);
496
+ const listeners = listenerOptions(options);
497
+ const keyOf = (req) => `${collection}:${req.routeParams?.id}:${req.searchParams.get('row') ?? ''}`;
498
+ const carryOn = (req, force = false) => background(req.payload, collection, options, rowFields, req.routeParams?.id, rowOf(req), force);
164
499
  /** An editor's target with a finished transcript, and the API to work on it. */
165
500
  const editable = async (req, verb) => {
166
501
  const id = req.routeParams?.id;
@@ -178,16 +513,15 @@ export function speechEndpoints(collection, options, rowFields) {
178
513
  return json({ error: 'Transcribe the audio first.' }, 409);
179
514
  return { api: new VocalStackAPI(apiKey, apiURL), target };
180
515
  };
181
- /** The body's languages (none of them the spoken one) and voice. */
516
+ /** The body's languages (none of them the spoken one), and whether to read them aloud. VocalStack picks the voice. */
182
517
  const bodyOf = async (req, spoken) => {
183
518
  const body = (await req.json?.().catch(() => ({})));
184
519
  const langs = Array.isArray(body.langs) ? [...new Set(body.langs.map(String).map((l) => l.toLowerCase()))] : [];
185
520
  if (!langs.length || langs.some((l) => !LANG.test(l) || l === spoken))
186
521
  return undefined;
187
- return { langs, voice: typeof body.voice === 'string' && body.voice.trim() ? body.voice.trim() : undefined };
522
+ return { langs, speak: body.speak !== false };
188
523
  };
189
- const defaultVoice = async (req, target) => (await options.speechVoice?.({ collection, doc: target.doc, req, row: target.row })) ?? null;
190
- return [
524
+ const endpoints = [
191
525
  {
192
526
  method: 'post',
193
527
  path: '/:id/vocalstack/translate',
@@ -199,7 +533,9 @@ export function speechEndpoints(collection, options, rowFields) {
199
533
  const asked = await bodyOf(req, target.data.language);
200
534
  if (!asked)
201
535
  return json({ error: 'Name the languages to translate into.' }, 400);
202
- const deadline = Date.now() + BUDGET_MS;
536
+ if (pastLimit(target.data, asked.langs).length)
537
+ return limitError(target.data);
538
+ const deadline = Date.now() + STEP_MS;
203
539
  try {
204
540
  let more = false;
205
541
  let data = target.data;
@@ -236,6 +572,41 @@ export function speechEndpoints(collection, options, rowFields) {
236
572
  return json({ vocalstack });
237
573
  },
238
574
  },
575
+ {
576
+ // Readings from now on in speakers' cloned voices, or in stock ones. Readings made before stay as they are.
577
+ method: 'post',
578
+ path: '/:id/vocalstack/voices',
579
+ handler: async (req) => {
580
+ const found = await editable(req, 'change');
581
+ if (found instanceof Response)
582
+ return found;
583
+ const body = (await req.json?.().catch(() => ({})));
584
+ if (body.voices !== 'cloned' && body.voices !== 'synthetic')
585
+ return json({ error: 'Choose cloned or synthetic voices.' }, 400);
586
+ const voices = body.voices;
587
+ const vocalstack = await found.target.save(() => ({ voices }));
588
+ return json({ vocalstack });
589
+ },
590
+ },
591
+ {
592
+ method: 'post',
593
+ path: '/:id/vocalstack/request',
594
+ handler: async (req) => {
595
+ const found = await editable(req, 'translate');
596
+ if (found instanceof Response)
597
+ return found;
598
+ const { target } = found;
599
+ const asked = await bodyOf(req, target.data.language);
600
+ if (!asked)
601
+ return json({ error: 'Name the languages to add.' }, 400);
602
+ if (pastLimit(target.data, asked.langs).length)
603
+ return limitError(target.data);
604
+ const voiced = new Set((await languageList(req, options)).voice);
605
+ const vocalstack = await requestLanguages(target, asked.langs, { speak: (l) => asked.speak && voiced.has(l) });
606
+ carryOn(req, true);
607
+ return json({ vocalstack }, 202);
608
+ },
609
+ },
239
610
  {
240
611
  method: 'post',
241
612
  path: '/:id/vocalstack/speak',
@@ -247,28 +618,32 @@ export function speechEndpoints(collection, options, rowFields) {
247
618
  const asked = await bodyOf(req, target.data.language);
248
619
  if (!asked)
249
620
  return json({ error: 'Name the languages to read out.' }, 400);
250
- const { langs } = asked;
251
- const voice = asked.voice ?? (await defaultVoice(req, target)) ?? undefined;
621
+ if (pastLimit(target.data, asked.langs).length)
622
+ return limitError(target.data);
252
623
  try {
253
- // A reading speaks the translation, so every language needs one first.
254
- const deadline = Date.now() + BUDGET_MS;
624
+ // A reading speaks the translation: those not translated yet are read once they are.
625
+ const ready = asked.langs.filter((l) => isTranslated(target.data.translations?.[l]));
626
+ const later = asked.langs.filter((l) => !ready.includes(l));
255
627
  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);
628
+ if (ready.length) {
629
+ const cloned = (await voiceModeOf(req, collection, options, target)).mode === 'cloned';
630
+ const tracks = await api.speak(target.data.recordingId, ready, { cloned });
631
+ for (const lang of ready)
632
+ await dropReading(req, readings, data.speech?.[lang]);
633
+ const requestedAt = new Date().toISOString();
634
+ const cast = cloned ? 'cloned' : 'synthetic';
635
+ data = await target.save((current) => ({
636
+ speech: {
637
+ ...current.speech,
638
+ ...Object.fromEntries(ready.map((l) => [l, { cast, error: null, requestedAt, state: 'queued', voice: askedKey(tracks, l) }])),
639
+ },
640
+ }));
263
641
  }
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);
642
+ if (later.length) {
643
+ data = await requestLanguages({ ...target, data }, later, { speak: () => true });
644
+ carryOn(req, true);
645
+ }
646
+ return json({ vocalstack: data }, 202);
272
647
  }
273
648
  catch (err) {
274
649
  return apiError(err);
@@ -284,70 +659,20 @@ export function speechEndpoints(collection, options, rowFields) {
284
659
  const target = await locate(req, collection, options, rowFields, 'user');
285
660
  if (target instanceof Response)
286
661
  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)
662
+ const voiceMode = await voiceModeOf(req, collection, options, target);
663
+ const answer = (vocalstack) => json({ vocalstack, voiceMode });
664
+ if (!target.data.recordingId || !hasWork(target.data, readings))
665
+ return answer(target.data);
666
+ // Translating goes on in the background; readings are looked at now.
667
+ if (waiting(target.data, readings).translating.length)
668
+ carryOn(req);
669
+ if (working.has(keyOf(req)))
293
670
  return answer(target.data);
294
671
  const apiKey = await resolveAPIKey(req, options);
295
672
  if (!apiKey)
296
673
  return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
297
674
  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);
675
+ return answer(await refresh(req, new VocalStackAPI(apiKey, apiURL), readings, target, keyOf(req)));
351
676
  }
352
677
  catch (err) {
353
678
  return apiError(err);
@@ -380,7 +705,7 @@ export function speechEndpoints(collection, options, rowFields) {
380
705
  return json({ error: 'Not available.' }, 404);
381
706
  try {
382
707
  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.
708
+ // The signed address lasts a while; hand out the same one for a few minutes.
384
709
  return new Response(null, { headers: { 'cache-control': 'public, max-age=300, s-maxage=300', location: url }, status: 302 });
385
710
  }
386
711
  catch (err) {
@@ -389,4 +714,77 @@ export function speechEndpoints(collection, options, rowFields) {
389
714
  },
390
715
  },
391
716
  ];
717
+ if (!listeners)
718
+ return endpoints;
719
+ /** A listener's target: readable by them, with a finished transcript. */
720
+ const readable = async (req) => {
721
+ const target = await locate(req, collection, options, rowFields, 'user');
722
+ if (target instanceof Response)
723
+ return target;
724
+ if (target.data.status !== 'done' || !target.data.recordingId)
725
+ return json({ error: 'There is no transcript to translate yet.' }, 409);
726
+ return target;
727
+ };
728
+ /** Done work may be cached a little; work under way is asked about again. */
729
+ const statusHeaders = (s) => ({
730
+ 'cache-control': s.state === 'ready' && (!s.speech || s.speech.state === 'ready' || s.speech.state === 'failed') ? 'public, max-age=30, s-maxage=30' : 'no-store',
731
+ });
732
+ return [
733
+ ...endpoints,
734
+ {
735
+ method: 'get',
736
+ path: '/:id/vocalstack/listen',
737
+ handler: async (req) => {
738
+ const target = await readable(req);
739
+ if (target instanceof Response)
740
+ return target;
741
+ const lang = req.searchParams.get('lang')?.toLowerCase() ?? '';
742
+ if (!LANG.test(lang))
743
+ return json({ error: 'Which language?' }, 400);
744
+ const voiced = new Set(forListeners(await languageList(req, options), listeners).voice);
745
+ if (hasWork(target.data, readings))
746
+ carryOn(req);
747
+ const status = listenStatus(target.data, lang, voiced.has(lang), readings);
748
+ return json(status, 200, statusHeaders(status));
749
+ },
750
+ },
751
+ {
752
+ method: 'post',
753
+ path: '/:id/vocalstack/listen',
754
+ handler: async (req) => {
755
+ const target = await readable(req);
756
+ if (target instanceof Response)
757
+ return target;
758
+ const body = (await req.json?.().catch(() => ({})));
759
+ const lang = typeof body.lang === 'string' ? body.lang.toLowerCase() : '';
760
+ if (!LANG.test(lang) || lang === target.data.language)
761
+ return json({ error: 'Which language?' }, 400);
762
+ const offered = forListeners(await languageList(req, options), listeners);
763
+ if (!offered.translation.includes(lang))
764
+ return json({ error: 'That language is not offered here.' }, 400);
765
+ const voiced = offered.voice.includes(lang);
766
+ const speak = listeners.speak !== false && voiced;
767
+ // Asked for already (by anyone): nothing new to start.
768
+ const now = listenStatus(target.data, lang, voiced, readings);
769
+ const translationAsked = now.state === 'translating' || now.state === 'ready';
770
+ const speechAsked = !speak || (now.speech && now.speech.state !== 'failed');
771
+ if (translationAsked && speechAsked) {
772
+ if (hasWork(target.data, readings))
773
+ carryOn(req);
774
+ return json(now, 200, { 'cache-control': 'no-store' });
775
+ }
776
+ if (pastLimit(target.data, [lang]).length)
777
+ return limitError(target.data);
778
+ if (listeners.access && !(await listeners.access({ lang, req })))
779
+ return json({ error: 'You may not ask for a new language here.' }, 403);
780
+ if (!(await resolveAPIKey(req, options)))
781
+ return json({ error: 'Translations are not available right now.' }, 503);
782
+ if (!allowNewLanguage(req, listeners.perHour ?? 10))
783
+ return json({ error: 'Too many new languages asked for; try again later.' }, 429);
784
+ const data = await requestLanguages(target, [lang], { speak: () => speak });
785
+ carryOn(req, true);
786
+ return json(listenStatus(data, lang, voiced, readings), 202, { 'cache-control': 'no-store' });
787
+ },
788
+ },
789
+ ];
392
790
  }