@vocalstack/payload 0.1.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.
@@ -0,0 +1,790 @@
1
+ import { after } from 'next/server.js';
2
+ import { createLocalReq } from 'payload';
3
+ import { DEFAULT_API_URL, UNAVAILABLE, VocalStackAPI, VocalStackAPIError } from '../api.js';
4
+ import { allowNewLanguage, forListeners, LANGUAGE_LIMIT, languageList, listenerOptions } from '../languages.js';
5
+ import { readingsSlug } from '../readings.js';
6
+ import { resolveAPIKey } from '../settings.js';
7
+ import { spokenSentences } from '../text.js';
8
+ import { apiError, canUpdate, locate } from './transcribe.js';
9
+ const json = (body, status = 200, headers) => Response.json(body, { headers, status });
10
+ // Translating is slow (an hour-long recording takes minutes): batches run side by side, and a call
11
+ // stops starting new ones after a while so it answers before the host's time limit.
12
+ // What is done is saved each time.
13
+ const BATCH = 30;
14
+ const PARALLEL = 4;
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;
20
+ const LANG = /^[a-z]{2,3}(-[a-z0-9]+)?$/i;
21
+ /** The transcript's sentences that can be translated: settled, numbered, with text. */
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';
45
+ /** Translate what is still missing in `lang`, within the time budget, and save it. Whether some is left, and the field as saved. */
46
+ async function translate(api, target, lang, deadline) {
47
+ const sentences = translatable(target.data);
48
+ const have = new Map((target.data.translations?.[lang]?.sentences ?? []).map((s) => [s.id, s.text]));
49
+ const missing = sentences.filter((s) => !have.get(s.id)).map((s) => s.id);
50
+ const batches = [];
51
+ const got = new Map();
52
+ let failure;
53
+ // What VocalStack translated before (for anyone) costs nothing to read back; only the rest is translated.
54
+ if (missing.length) {
55
+ try {
56
+ const stored = await api.storedTranslations(target.data.recordingId, lang);
57
+ for (const id of missing)
58
+ if (stored[String(id)]?.trim())
59
+ got.set(id, stored[String(id)].trim());
60
+ }
61
+ catch (err) {
62
+ if (isPermanent(err))
63
+ throw err;
64
+ // Not readable just now: translate them all instead.
65
+ }
66
+ const left = missing.filter((id) => !got.has(id));
67
+ for (let i = 0; i < left.length; i += BATCH)
68
+ batches.push(left.slice(i, i + BATCH));
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
+ });
86
+ const worker = async () => {
87
+ for (let batch = batches.shift(); batch; batch = batches.shift()) {
88
+ if (Date.now() > deadline || failure) {
89
+ batches.unshift(batch);
90
+ return;
91
+ }
92
+ try {
93
+ const { translations } = await api.translation(target.data.recordingId, lang, batch);
94
+ for (const [id, text] of Object.entries(translations))
95
+ if (text?.trim())
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);
100
+ }
101
+ catch (err) {
102
+ failure ??= err;
103
+ batches.unshift(batch);
104
+ }
105
+ }
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);
110
+ await Promise.all(Array.from({ length: PARALLEL }, worker));
111
+ // Nothing came back at all: say why, rather than "call again" forever.
112
+ if (failure && !got.size)
113
+ throw failure;
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)
120
+ throw new VocalStackAPIError(503, 'unavailable', UNAVAILABLE);
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 };
125
+ }
126
+ /** A file name from the recording's name: `episode-12-ro.mp3`. */
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`;
128
+ /**
129
+ * Download a finished reading's MP3 from VocalStack, once, and keep it as an upload in
130
+ * the readings collection, so listeners are served from the site's storage from then on.
131
+ */
132
+ async function keepReading(req, api, slug, target, lang, speech) {
133
+ if (speech.audio || speech.state !== 'sealed')
134
+ return speech;
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)
148
+ throw new VocalStackAPIError(502, 'unavailable', UNAVAILABLE);
149
+ const data = Buffer.from(await res.arrayBuffer());
150
+ const doc = (await req.payload.create({
151
+ collection: slug,
152
+ data: { lang, recordingId: target.data.recordingId, voice: speech.voice ?? '' },
153
+ file: { data, mimetype: 'audio/mpeg', name: readingName(target, lang, speech.voice), size: data.length },
154
+ overrideAccess: true,
155
+ req,
156
+ }));
157
+ return { ...speech, audio: { filename: doc.filename ?? null, id: doc.id, url: doc.url ?? '' } };
158
+ }
159
+ /** Readings being downloaded right now, so overlapping status checks fetch each one once. */
160
+ const keeping = new Set();
161
+ /** Remove a reading's kept file (it is being replaced, or its language dropped). */
162
+ async function dropReading(req, slug, speech) {
163
+ if (!slug || !speech?.audio)
164
+ return;
165
+ await req.payload.delete({ collection: slug, id: speech.audio.id, overrideAccess: true, req }).catch(() => { });
166
+ }
167
+ /** Delete kept readings of this recording, in these languages, that the field does not point to. */
168
+ async function sweepReadings(req, slug, data, langs) {
169
+ if (!data.recordingId || !langs.length)
170
+ return;
171
+ const found = await req.payload.find({
172
+ collection: slug,
173
+ depth: 0,
174
+ limit: 50,
175
+ overrideAccess: true,
176
+ pagination: false,
177
+ req,
178
+ where: { and: [{ recordingId: { equals: data.recordingId } }, { lang: { in: langs } }] },
179
+ });
180
+ const keep = new Set(langs.map((l) => data.speech?.[l]?.audio?.id).filter((id) => id !== undefined).map(String));
181
+ for (const doc of found.docs)
182
+ if (!keep.has(String(doc.id)))
183
+ await req.payload.delete({ collection: slug, id: doc.id, overrideAccess: true, req }).catch(() => { });
184
+ }
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
+ }
210
+ /** A spoken translation brought up to date from VocalStack's track. */
211
+ function settle(speech, track, translation) {
212
+ if (!track) {
213
+ // Asked for but not listed (yet): a job is created with the request, so give it a little while.
214
+ const age = Date.now() - new Date(speech.requestedAt).getTime();
215
+ return age < 120_000 ? speech : { ...speech, error: 'VocalStack has no reading of this language. Try again.', state: 'failed' };
216
+ }
217
+ if (track.state === 'failed')
218
+ return { ...speech, error: track.error ?? 'The reading failed.', state: 'failed' };
219
+ if (track.state !== 'sealed')
220
+ return { ...speech, done: track.clips?.length ?? 0, error: null, state: track.state === 'queued' ? 'queued' : 'running', voice: keyOf(track) || speech.voice };
221
+ return {
222
+ ...speech,
223
+ voice: keyOf(track) || speech.voice,
224
+ done: null,
225
+ durationS: track.durationS ?? null,
226
+ error: null,
227
+ renderedAt: new Date().toISOString(),
228
+ sentences: spokenSentences(translation?.sentences ?? [], track.clipDur ?? {}, track.wordTimes ?? {}),
229
+ state: 'sealed',
230
+ };
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
+ }
479
+ /**
480
+ * Translations of a transcript, and spoken readings of them, on the same document or
481
+ * row as the transcript (`?field=&row=` as for transcribing):
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
492
+ */
493
+ export function speechEndpoints(collection, options, rowFields) {
494
+ const apiURL = options.apiURL ?? DEFAULT_API_URL;
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);
499
+ /** An editor's target with a finished transcript, and the API to work on it. */
500
+ const editable = async (req, verb) => {
501
+ const id = req.routeParams?.id;
502
+ if (!(await canUpdate(req, collection, id)))
503
+ return json({ error: `You may not ${verb} this transcript.` }, 403);
504
+ if (options.access && !(await options.access({ req })))
505
+ return json({ error: `You may not ${verb} this transcript.` }, 403);
506
+ const apiKey = await resolveAPIKey(req, options);
507
+ if (!apiKey)
508
+ return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
509
+ const target = await locate(req, collection, options, rowFields, 'admin');
510
+ if (target instanceof Response)
511
+ return target;
512
+ if (target.data.status !== 'done' || !target.data.recordingId)
513
+ return json({ error: 'Transcribe the audio first.' }, 409);
514
+ return { api: new VocalStackAPI(apiKey, apiURL), target };
515
+ };
516
+ /** The body's languages (none of them the spoken one), and whether to read them aloud. VocalStack picks the voice. */
517
+ const bodyOf = async (req, spoken) => {
518
+ const body = (await req.json?.().catch(() => ({})));
519
+ const langs = Array.isArray(body.langs) ? [...new Set(body.langs.map(String).map((l) => l.toLowerCase()))] : [];
520
+ if (!langs.length || langs.some((l) => !LANG.test(l) || l === spoken))
521
+ return undefined;
522
+ return { langs, speak: body.speak !== false };
523
+ };
524
+ const endpoints = [
525
+ {
526
+ method: 'post',
527
+ path: '/:id/vocalstack/translate',
528
+ handler: async (req) => {
529
+ const found = await editable(req, 'translate');
530
+ if (found instanceof Response)
531
+ return found;
532
+ const { api, target } = found;
533
+ const asked = await bodyOf(req, target.data.language);
534
+ if (!asked)
535
+ return json({ error: 'Name the languages to translate into.' }, 400);
536
+ if (pastLimit(target.data, asked.langs).length)
537
+ return limitError(target.data);
538
+ const deadline = Date.now() + STEP_MS;
539
+ try {
540
+ let more = false;
541
+ let data = target.data;
542
+ for (const lang of asked.langs) {
543
+ if (Date.now() > deadline) {
544
+ more = true;
545
+ continue;
546
+ }
547
+ const done = await translate(api, { ...target, data }, lang, deadline);
548
+ data = done.data;
549
+ more ||= done.more;
550
+ }
551
+ return json({ more, vocalstack: data });
552
+ }
553
+ catch (err) {
554
+ return apiError(err);
555
+ }
556
+ },
557
+ },
558
+ {
559
+ method: 'delete',
560
+ path: '/:id/vocalstack/translate',
561
+ handler: async (req) => {
562
+ const found = await editable(req, 'change');
563
+ if (found instanceof Response)
564
+ return found;
565
+ const lang = req.searchParams.get('lang') ?? '';
566
+ await dropReading(req, readings, found.target.data.speech?.[lang]);
567
+ const vocalstack = await found.target.save((current) => {
568
+ const { [lang]: _t, ...translations } = current.translations ?? {};
569
+ const { [lang]: _s, ...speech } = current.speech ?? {};
570
+ return { speech, translations };
571
+ });
572
+ return json({ vocalstack });
573
+ },
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
+ },
610
+ {
611
+ method: 'post',
612
+ path: '/:id/vocalstack/speak',
613
+ handler: async (req) => {
614
+ const found = await editable(req, 'read out');
615
+ if (found instanceof Response)
616
+ return found;
617
+ const { api, target } = found;
618
+ const asked = await bodyOf(req, target.data.language);
619
+ if (!asked)
620
+ return json({ error: 'Name the languages to read out.' }, 400);
621
+ if (pastLimit(target.data, asked.langs).length)
622
+ return limitError(target.data);
623
+ try {
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));
627
+ let data = target.data;
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
+ }));
641
+ }
642
+ if (later.length) {
643
+ data = await requestLanguages({ ...target, data }, later, { speak: () => true });
644
+ carryOn(req, true);
645
+ }
646
+ return json({ vocalstack: data }, 202);
647
+ }
648
+ catch (err) {
649
+ return apiError(err);
650
+ }
651
+ },
652
+ },
653
+ {
654
+ method: 'get',
655
+ path: '/:id/vocalstack/speak',
656
+ handler: async (req) => {
657
+ if (!req.user)
658
+ return json({ error: 'Sign in first.' }, 401);
659
+ const target = await locate(req, collection, options, rowFields, 'user');
660
+ if (target instanceof Response)
661
+ return target;
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)))
670
+ return answer(target.data);
671
+ const apiKey = await resolveAPIKey(req, options);
672
+ if (!apiKey)
673
+ return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
674
+ try {
675
+ return answer(await refresh(req, new VocalStackAPI(apiKey, apiURL), readings, target, keyOf(req)));
676
+ }
677
+ catch (err) {
678
+ return apiError(err);
679
+ }
680
+ },
681
+ },
682
+ {
683
+ method: 'get',
684
+ path: '/:id/vocalstack/audio',
685
+ handler: async (req) => {
686
+ // Public: whoever may read the document may listen, signed in or not.
687
+ const target = await locate(req, collection, options, rowFields, 'user');
688
+ if (target instanceof Response)
689
+ return target;
690
+ const { language, recordingId, speech } = target.data;
691
+ if (!recordingId)
692
+ return json({ error: 'No audio.' }, 404);
693
+ const lang = req.searchParams.get('lang')?.toLowerCase();
694
+ const spoken = !lang || lang === language;
695
+ const reading = spoken ? undefined : speech?.[lang];
696
+ if (!spoken && reading?.state !== 'sealed')
697
+ return json({ error: 'There is no reading in that language.' }, 404);
698
+ // Kept files are served from the site's own storage: no VocalStack request.
699
+ const own = spoken ? await target.url().catch(() => undefined) : reading?.audio?.url;
700
+ if (own) {
701
+ return new Response(null, { headers: { 'cache-control': 'public, max-age=3600, s-maxage=86400', location: new URL(own, req.url ?? 'http://localhost').toString() }, status: 302 });
702
+ }
703
+ const apiKey = await resolveAPIKey(req, options);
704
+ if (!apiKey)
705
+ return json({ error: 'Not available.' }, 404);
706
+ try {
707
+ const url = await new VocalStackAPI(apiKey, apiURL).audioURL(recordingId, spoken ? { kind: 'delivery' } : { kind: 'voice', lang, voice: reading?.voice ?? undefined });
708
+ // The signed address lasts a while; hand out the same one for a few minutes.
709
+ return new Response(null, { headers: { 'cache-control': 'public, max-age=300, s-maxage=300', location: url }, status: 302 });
710
+ }
711
+ catch (err) {
712
+ return apiError(err);
713
+ }
714
+ },
715
+ },
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
+ ];
790
+ }