@vocalstack/payload 0.1.0 → 0.2.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,226 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Button, toast, useConfig, useDocumentInfo, useForm } from '@payloadcms/ui';
4
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
5
+ import { BrandStyles, Logo } from './Brand.js';
6
+ import { useAPI, useConnection } from './useConnection.js';
7
+ const POLL_MS = 3000;
8
+ const TARGET_S = 60;
9
+ const MIN_S = 30;
10
+ const MAX_S = 120;
11
+ const styles = `
12
+ .vs-voice-list { max-height: 260px; overflow-y: auto; border: 1px solid var(--theme-elevation-150); border-radius: var(--style-radius-s, 4px);
13
+ background: var(--theme-input-bg, var(--theme-elevation-0)); font-size: 13px; line-height: 1.5; }
14
+ .vs-voice-line { display: flex; gap: 8px; width: 100%; padding: 6px 10px; border: 0; background: none; color: inherit; text-align: left; cursor: pointer; font: inherit; }
15
+ .vs-voice-line:hover { background: var(--theme-elevation-50); }
16
+ .vs-voice-line--in { background: color-mix(in srgb, var(--vs-accent) 14%, transparent); }
17
+ .vs-voice-line--start { box-shadow: inset 3px 0 0 var(--vs-accent); }
18
+ .vs-voice-time { color: var(--theme-elevation-500); font-variant-numeric: tabular-nums; flex: none; }
19
+ .vs-voice-tabs { display: flex; gap: 4px; margin-bottom: 8px; }
20
+ .vs-voice select, .vs-voice input[type=file] { width: 100%; font: inherit; }
21
+ .vs-voice select { padding: 6px 8px; border: 1px solid var(--theme-elevation-150); border-radius: var(--style-radius-s, 4px);
22
+ background: var(--theme-input-bg, var(--theme-elevation-0)); color: var(--theme-text); }
23
+ `;
24
+ const clock = (s) => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
25
+ /** Whole sentences from `start`, about a minute of them: VocalStack clones from 30–120 s. */
26
+ function stretchFrom(sentences, start) {
27
+ const from = sentences[start];
28
+ const ids = new Set();
29
+ let endS = from.end;
30
+ for (let i = start; i < sentences.length; i++) {
31
+ const s = sentences[i];
32
+ if (s.end - from.start > MAX_S)
33
+ break;
34
+ ids.add(s.id);
35
+ endS = s.end;
36
+ if (endS - from.start >= TARGET_S)
37
+ break;
38
+ }
39
+ return { endS, ids, startS: from.start };
40
+ }
41
+ /** Ogg/Opus where the browser plays it, else CAF (Safari). */
42
+ const previewFormat = () => (typeof Audio !== 'undefined' && new Audio().canPlayType('audio/ogg; codecs=opus') ? 'ogg' : 'caf');
43
+ export const VoiceField = () => {
44
+ const { id, collectionSlug } = useDocumentInfo();
45
+ const { dispatchFields } = useForm();
46
+ const { connection } = useConnection();
47
+ const call = useAPI();
48
+ const base = `/${collectionSlug}/${id}/vocalstack/voice`;
49
+ const [voice, setVoice] = useState();
50
+ const [name, setName] = useState('');
51
+ const [error, setError] = useState();
52
+ const [busy, setBusy] = useState(false);
53
+ const [creating, setCreating] = useState(false);
54
+ const timer = useRef(undefined);
55
+ // Keep the form's copy in step with the server's, so saving the document keeps the voice.
56
+ const apply = useCallback((res) => {
57
+ setVoice(res.vocalstackVoice);
58
+ if (res.name)
59
+ setName(res.name);
60
+ for (const [key, value] of Object.entries(res.vocalstackVoice)) {
61
+ dispatchFields({ type: 'UPDATE', initialValue: value, path: `vocalstackVoice.${key}`, value });
62
+ }
63
+ }, [dispatchFields]);
64
+ const refresh = useCallback(async () => {
65
+ clearTimeout(timer.current);
66
+ try {
67
+ const res = await call(base);
68
+ apply(res);
69
+ setError(undefined);
70
+ if (res.vocalstackVoice.state === 'training')
71
+ timer.current = setTimeout(refresh, POLL_MS);
72
+ }
73
+ catch (err) {
74
+ setError(err.message);
75
+ // Unavailable for now: keep checking on a training voice, more slowly.
76
+ if (voice?.state === 'training')
77
+ timer.current = setTimeout(refresh, POLL_MS * 3);
78
+ }
79
+ }, [apply, base, call, voice?.state]);
80
+ useEffect(() => {
81
+ if (id && connection?.connected)
82
+ void refresh();
83
+ return () => clearTimeout(timer.current);
84
+ // Once per document; `refresh` re-arms itself while training.
85
+ // eslint-disable-next-line react-hooks/exhaustive-deps
86
+ }, [id, connection?.connected]);
87
+ const remove = async () => {
88
+ if (!window.confirm(`Delete ${name || 'this'} voice? Readings already made with it stay as they are.`))
89
+ return;
90
+ setBusy(true);
91
+ try {
92
+ apply(await call(base, { method: 'DELETE' }));
93
+ toast.success('Voice deleted.');
94
+ }
95
+ catch (err) {
96
+ setError(err.message);
97
+ }
98
+ finally {
99
+ setBusy(false);
100
+ }
101
+ };
102
+ const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
103
+ const state = voice?.state ?? 'none';
104
+ return (_jsxs("div", { className: "field-type vs-brand vs-voice", style: { marginBottom: 'var(--base)' }, children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsxs("div", { className: "field-label", style: { alignItems: 'center', display: 'flex', gap: 8, marginBottom: 'calc(var(--base) / 2)' }, children: [_jsx(Logo, { height: 14 }), " ", _jsx("span", { children: "Voice" })] }), !id ? (_jsx("p", { style: muted, children: "Save first, then create a voice." })) : connection && !connection.connected ? (_jsx("p", { style: muted, children: "Connect VocalStack (Settings \u2192 VocalStack) to create a voice." })) : !voice ? (_jsx("p", { style: muted, children: error ?? 'Checking…' })) : creating || state === 'none' || state === 'failed' ? (creating ? (_jsx(CreateVoice, { base: base, name: name, onCancel: () => setCreating(false), onCreated: (res) => {
105
+ apply(res);
106
+ setCreating(false);
107
+ timer.current = setTimeout(refresh, POLL_MS);
108
+ } })) : (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [state === 'failed' ? (_jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["The voice could not be made: ", voice.error ?? 'VocalStack gave no reason', "."] })) : (_jsxs("p", { style: muted, children: ["Clone ", name || 'their', " voice to read translations aloud in it."] })), _jsx("div", { children: _jsx(Button, { margin: false, onClick: () => setCreating(true), size: "small", children: state === 'failed' ? 'Try again' : 'Create a voice' }) })] }))) : state === 'training' ? (_jsxs("div", { children: [_jsxs("p", { style: muted, children: ["Training the voice", voice.progress ? ` · ${voice.progress}%` : '…'] }), _jsx("div", { style: { background: 'var(--theme-elevation-100)', borderRadius: 2, height: 4, marginTop: 4, overflow: 'hidden' }, children: _jsx("div", { style: { background: 'var(--vs-accent)', height: '100%', transition: 'width .4s', width: `${Math.max(2, voice.progress ?? 0)}%` } }) })] })) : (_jsx(ReadyVoice, { base: base, busy: busy, onDelete: remove, voice: voice })), error && voice && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)', marginTop: 8 }, children: error })] }));
109
+ };
110
+ const ReadyVoice = ({ base, busy, onDelete, voice }) => {
111
+ const call = useAPI();
112
+ const [langs, setLangs] = useState();
113
+ const [lang, setLang] = useState('en');
114
+ const [src, setSrc] = useState();
115
+ const [waiting, setWaiting] = useState(false);
116
+ const [error, setError] = useState();
117
+ const audio = useRef(null);
118
+ const { serverURL, api } = useAPIBase();
119
+ useEffect(() => {
120
+ call('/vocalstack/languages').then(setLangs, (err) => setError(err.message));
121
+ }, [call]);
122
+ /** The preview is made on first ask (202): ask until it is there, then play it. */
123
+ const play = async () => {
124
+ setError(undefined);
125
+ setWaiting(true);
126
+ const url = `${serverURL}${api}${base}/preview?${new URLSearchParams({ format: previewFormat(), lang })}`;
127
+ try {
128
+ for (let i = 0; i < 20; i++) {
129
+ const res = await fetch(url, { credentials: 'include' });
130
+ if (res.status === 202) {
131
+ await new Promise((r) => setTimeout(r, 2000));
132
+ continue;
133
+ }
134
+ if (!res.ok)
135
+ throw new Error((await res.json().catch(() => ({}))).error ?? `Preview failed (${res.status})`);
136
+ setSrc(URL.createObjectURL(await res.blob()));
137
+ requestAnimationFrame(() => void audio.current?.play().catch(() => undefined));
138
+ return;
139
+ }
140
+ throw new Error('The preview is taking a while; try again in a minute.');
141
+ }
142
+ catch (err) {
143
+ setError(err.message);
144
+ }
145
+ finally {
146
+ setWaiting(false);
147
+ }
148
+ };
149
+ const names = new Map(langs?.languages.map((l) => [l.code, l.name]));
150
+ const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
151
+ return (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [_jsxs("p", { style: muted, children: ["Ready", voice.sampleS ? `, cloned from ${Math.round(voice.sampleS)} s of speech` : '', ". Translations are read in this voice."] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx("select", { "aria-label": "Preview language", onChange: (e) => setLang(e.target.value), value: lang, children: (langs?.voice ?? ['en']).map((code) => (_jsx("option", { value: code, children: names.get(code) ?? code }, code))) }), _jsx(Button, { buttonStyle: "secondary", disabled: waiting, margin: false, onClick: play, size: "small", children: waiting ? 'Making…' : '▶ Hear' })] }), src && _jsx("audio", { controls: true, ref: audio, src: src, style: { width: '100%' } }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsx("div", { children: _jsx(Button, { buttonStyle: "error", disabled: busy, margin: false, onClick: onDelete, size: "small", children: "Delete voice" }) })] }));
152
+ };
153
+ const CreateVoice = ({ base, name, onCancel, onCreated }) => {
154
+ const call = useAPI();
155
+ const { serverURL, api } = useAPIBase();
156
+ const [tab, setTab] = useState('recording');
157
+ const [sources, setSources] = useState();
158
+ const [sourceIdx, setSourceIdx] = useState(0);
159
+ const [start, setStart] = useState();
160
+ const [file, setFile] = useState();
161
+ const [fileS, setFileS] = useState();
162
+ const [consent, setConsent] = useState(false);
163
+ const [busy, setBusy] = useState(false);
164
+ const [error, setError] = useState();
165
+ useEffect(() => {
166
+ call(`${base}/sources`).then((r) => {
167
+ setSources(r.sources);
168
+ if (!r.sources.length)
169
+ setTab('file');
170
+ }, (err) => setError(err.message));
171
+ }, [base, call]);
172
+ const source = sources?.[sourceIdx];
173
+ const sentences = useMemo(() => source?.sentences ?? [], [source]);
174
+ const stretch = start !== undefined && sentences[start] ? stretchFrom(sentences, start) : undefined;
175
+ const length = stretch ? stretch.endS - stretch.startS : tab === 'file' ? fileS : undefined;
176
+ const longEnough = (length ?? 0) >= MIN_S - 1.5;
177
+ const pick = (f) => {
178
+ setFile(f);
179
+ setFileS(undefined);
180
+ if (!f)
181
+ return;
182
+ // Measure it: VocalStack needs at least 30 s.
183
+ const a = new Audio(URL.createObjectURL(f));
184
+ a.onloadedmetadata = () => setFileS(a.duration);
185
+ };
186
+ const create = async () => {
187
+ setBusy(true);
188
+ setError(undefined);
189
+ try {
190
+ let res;
191
+ if (tab === 'recording' && source && stretch) {
192
+ res = await call(base, { body: JSON.stringify({ consent, endS: stretch.endS, recordingId: source.recordingId, startS: stretch.startS }), method: 'POST' });
193
+ }
194
+ else if (file) {
195
+ const form = new FormData();
196
+ form.append('file', file);
197
+ form.append('_payload', JSON.stringify({ consent }));
198
+ const r = await fetch(`${serverURL}${api}${base}`, { body: form, credentials: 'include', method: 'POST' });
199
+ const body = await r.json().catch(() => ({}));
200
+ if (!r.ok)
201
+ throw new Error(body.error ?? (r.status === 413 ? 'The sample is too large; use a shorter or compressed file.' : `Request failed (${r.status})`));
202
+ res = body;
203
+ }
204
+ else
205
+ return;
206
+ toast.success('Voice created. It is training now.');
207
+ onCreated(res);
208
+ }
209
+ catch (err) {
210
+ setError(err.message);
211
+ }
212
+ finally {
213
+ setBusy(false);
214
+ }
215
+ };
216
+ const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
217
+ const clipURL = stretch && source ? `${serverURL}${api}${base}/clip?${new URLSearchParams({ endS: String(stretch.endS), recording: source.recordingId, startS: String(stretch.startS) })}` : undefined;
218
+ return (_jsxs("div", { style: { display: 'grid', gap: 10 }, children: [_jsxs("div", { className: "vs-voice-tabs", children: [_jsx(Button, { buttonStyle: tab === 'recording' ? 'primary' : 'secondary', margin: false, onClick: () => setTab('recording'), size: "small", children: "From a recording" }), _jsx(Button, { buttonStyle: tab === 'file' ? 'primary' : 'secondary', margin: false, onClick: () => setTab('file'), size: "small", children: "Upload a sample" })] }), tab === 'recording' ? (!sources ? (_jsx("p", { style: muted, children: error ? '' : 'Looking for transcribed recordings…' })) : !sources.length ? (_jsxs("p", { style: muted, children: ["No transcribed recordings of ", name || 'them', " yet. Transcribe one, or upload a sample."] })) : (_jsxs(_Fragment, { children: [sources.length > 1 && (_jsx("select", { "aria-label": "Recording", onChange: (e) => {
219
+ setSourceIdx(Number(e.target.value));
220
+ setStart(undefined);
221
+ }, value: sourceIdx, children: sources.map((s, i) => (_jsx("option", { value: i, children: s.label }, s.recordingId))) })), _jsxs("p", { style: muted, children: ["Click where ", name || 'they', " start speaking alone, with no music or other voices. About a minute is taken from there."] }), _jsx("div", { className: "vs-voice-list", children: sentences.map((s, i) => (_jsxs("button", { className: `vs-voice-line${stretch?.ids.has(s.id) ? ' vs-voice-line--in' : ''}${i === start ? ' vs-voice-line--start' : ''}`, onClick: () => setStart(i), type: "button", children: [_jsx("span", { className: "vs-voice-time", children: clock(s.start) }), _jsx("span", { children: s.text })] }, s.id ?? i))) }), stretch && (_jsxs(_Fragment, { children: [_jsxs("p", { style: muted, children: [clock(stretch.startS), "\u2013", clock(stretch.endS), " \u00B7 ", Math.round(stretch.endS - stretch.startS), " s", longEnough ? '' : ` (at least ${MIN_S} s needed)`] }), _jsx("audio", { controls: true, preload: "none", src: clipURL, style: { width: '100%' } }, clipURL)] }))] }))) : (_jsxs(_Fragment, { children: [_jsxs("p", { style: muted, children: [MIN_S, " s to 2 min of ", name || 'them', " speaking alone, clearly, with no music. An MP3 or M4A of about a minute is ideal."] }), _jsx("input", { accept: "audio/*", onChange: (e) => pick(e.target.files?.[0]), type: "file" }), file && fileS !== undefined && !longEnough && _jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["That is ", Math.round(fileS), " s; at least ", MIN_S, " s is needed."] })] })), _jsxs("label", { style: { alignItems: 'flex-start', display: 'flex', fontSize: 13, gap: 8 }, children: [_jsx("input", { checked: consent, onChange: (e) => setConsent(e.target.checked), style: { marginTop: 3 }, type: "checkbox" }), _jsxs("span", { children: ["I have ", name || 'their', "\u2019s permission to clone their voice."] })] }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx(Button, { disabled: busy || !consent || !longEnough || (tab === 'file' ? !file : !stretch), margin: false, onClick: create, size: "small", children: busy ? 'Creating…' : 'Create voice' }), _jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: onCancel, size: "small", children: "Cancel" })] })] }));
222
+ };
223
+ function useAPIBase() {
224
+ const { config: { routes: { api }, serverURL, }, } = useConfig();
225
+ return { api, serverURL };
226
+ }
@@ -0,0 +1,12 @@
1
+ import type { CollectionSlug, Endpoint } from 'payload';
2
+ import type { AudioFieldConfig, VocalStackPluginOptions } from '../types.js';
3
+ /**
4
+ * Translations of a transcript, and spoken readings of them, on the same document or
5
+ * row as the transcript (`?field=&row=` as for transcribing):
6
+ * POST /:id/vocalstack/translate { langs } translate (call again while `more`)
7
+ * DELETE /:id/vocalstack/translate?lang= drop a language, spoken reading too
8
+ * POST /:id/vocalstack/speak { langs, voice? } read translations aloud
9
+ * GET /:id/vocalstack/speak where the readings stand
10
+ * GET /:id/vocalstack/audio?lang= public: the audio, or its reading in `lang`
11
+ */
12
+ export declare function speechEndpoints(collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[]): Endpoint[];
@@ -0,0 +1,392 @@
1
+ import { DEFAULT_API_URL, UNAVAILABLE, VocalStackAPI, VocalStackAPIError } from '../api.js';
2
+ import { readingsSlug } from '../readings.js';
3
+ import { resolveAPIKey } from '../settings.js';
4
+ import { spokenSentences } from '../text.js';
5
+ import { apiError, canUpdate, locate } from './transcribe.js';
6
+ const json = (body, status = 200) => Response.json(body, { status });
7
+ // Translating is slow (an hour-long recording takes minutes): batches run side by side, and a call
8
+ // 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.
10
+ const BATCH = 30;
11
+ const PARALLEL = 4;
12
+ const BUDGET_MS = 150_000;
13
+ const LANG = /^[a-z]{2,3}(-[a-z0-9]+)?$/i;
14
+ /** The transcript's sentences that can be translated: settled, numbered, with text. */
15
+ const translatable = (data) => (Array.isArray(data.sentences) ? data.sentences : []).filter((s) => !s.draft && s.id !== undefined && s.text.trim());
16
+ /** Translate what is still missing in `lang`, within the time budget, and save it. Whether some is left, and the field as saved. */
17
+ async function translate(api, target, lang, deadline) {
18
+ const sentences = translatable(target.data);
19
+ const have = new Map((target.data.translations?.[lang]?.sentences ?? []).map((s) => [s.id, s.text]));
20
+ const missing = sentences.filter((s) => !have.get(s.id)).map((s) => s.id);
21
+ const batches = [];
22
+ const got = new Map();
23
+ let failure;
24
+ // What VocalStack translated before (for anyone) costs nothing to read back; only the rest is translated.
25
+ if (missing.length) {
26
+ try {
27
+ const stored = await api.storedTranslations(target.data.recordingId, lang);
28
+ for (const id of missing)
29
+ if (stored[String(id)]?.trim())
30
+ got.set(id, stored[String(id)].trim());
31
+ }
32
+ catch {
33
+ // Not readable just now: translate them all instead.
34
+ }
35
+ const left = missing.filter((id) => !got.has(id));
36
+ for (let i = 0; i < left.length; i += BATCH)
37
+ batches.push(left.slice(i, i + BATCH));
38
+ }
39
+ const worker = async () => {
40
+ for (let batch = batches.shift(); batch; batch = batches.shift()) {
41
+ if (Date.now() > deadline || failure)
42
+ return;
43
+ try {
44
+ const { translations } = await api.translation(target.data.recordingId, lang, batch);
45
+ for (const [id, text] of Object.entries(translations))
46
+ if (text?.trim())
47
+ got.set(Number(id), text.trim());
48
+ }
49
+ catch (err) {
50
+ failure ??= err;
51
+ }
52
+ }
53
+ };
54
+ 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.
72
+ if (failure && !got.size)
73
+ throw failure;
74
+ const ranOut = Date.now() > deadline;
75
+ if (missing.length && !got.size && !have.size && !ranOut)
76
+ 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 };
80
+ }
81
+ /** A file name from the recording's name: `episode-12-ro.mp3`. */
82
+ 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`;
83
+ /**
84
+ * Download a finished reading's MP3 from VocalStack, once, and keep it as an upload in
85
+ * the readings collection, so listeners are served from the site's storage from then on.
86
+ */
87
+ async function keepReading(req, api, slug, target, lang, speech) {
88
+ if (speech.audio || speech.state !== 'sealed')
89
+ 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)
93
+ throw new VocalStackAPIError(502, 'unavailable', UNAVAILABLE);
94
+ const data = Buffer.from(await res.arrayBuffer());
95
+ const doc = (await req.payload.create({
96
+ collection: slug,
97
+ data: { lang, recordingId: target.data.recordingId, voice: speech.voice ?? '' },
98
+ file: { data, mimetype: 'audio/mpeg', name: readingName(target, lang, speech.voice), size: data.length },
99
+ overrideAccess: true,
100
+ req,
101
+ }));
102
+ return { ...speech, audio: { filename: doc.filename ?? null, id: doc.id, url: doc.url ?? '' } };
103
+ }
104
+ /** Readings being downloaded right now, so overlapping status checks fetch each one once. */
105
+ const keeping = new Set();
106
+ /** Remove a reading's kept file (it is being replaced, or its language dropped). */
107
+ async function dropReading(req, slug, speech) {
108
+ if (!slug || !speech?.audio)
109
+ return;
110
+ await req.payload.delete({ collection: slug, id: speech.audio.id, overrideAccess: true, req }).catch(() => { });
111
+ }
112
+ /** Delete kept readings of this recording, in these languages, that the field does not point to. */
113
+ async function sweepReadings(req, slug, data, langs) {
114
+ if (!data.recordingId || !langs.length)
115
+ return;
116
+ const found = await req.payload.find({
117
+ collection: slug,
118
+ depth: 0,
119
+ limit: 50,
120
+ overrideAccess: true,
121
+ pagination: false,
122
+ req,
123
+ where: { and: [{ recordingId: { equals: data.recordingId } }, { lang: { in: langs } }] },
124
+ });
125
+ const keep = new Set(langs.map((l) => data.speech?.[l]?.audio?.id).filter((id) => id !== undefined).map(String));
126
+ for (const doc of found.docs)
127
+ if (!keep.has(String(doc.id)))
128
+ await req.payload.delete({ collection: slug, id: doc.id, overrideAccess: true, req }).catch(() => { });
129
+ }
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 ?? ''));
132
+ /** A spoken translation brought up to date from VocalStack's track. */
133
+ function settle(speech, track, translation) {
134
+ if (!track) {
135
+ // Asked for but not listed (yet): a job is created with the request, so give it a little while.
136
+ const age = Date.now() - new Date(speech.requestedAt).getTime();
137
+ return age < 120_000 ? speech : { ...speech, error: 'VocalStack has no reading of this language. Try again.', state: 'failed' };
138
+ }
139
+ if (track.state === 'failed')
140
+ return { ...speech, error: track.error ?? 'The reading failed.', state: 'failed' };
141
+ if (track.state !== 'sealed')
142
+ return { ...speech, error: null, state: track.state === 'queued' ? 'queued' : 'running' };
143
+ return {
144
+ ...speech,
145
+ durationS: track.durationS ?? null,
146
+ error: null,
147
+ renderedAt: new Date().toISOString(),
148
+ sentences: spokenSentences(translation?.sentences ?? [], track.clipDur ?? {}, track.wordTimes ?? {}),
149
+ state: 'sealed',
150
+ };
151
+ }
152
+ /**
153
+ * Translations of a transcript, and spoken readings of them, on the same document or
154
+ * 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`
160
+ */
161
+ export function speechEndpoints(collection, options, rowFields) {
162
+ const apiURL = options.apiURL ?? DEFAULT_API_URL;
163
+ const readings = readingsSlug(options);
164
+ /** An editor's target with a finished transcript, and the API to work on it. */
165
+ const editable = async (req, verb) => {
166
+ const id = req.routeParams?.id;
167
+ if (!(await canUpdate(req, collection, id)))
168
+ return json({ error: `You may not ${verb} this transcript.` }, 403);
169
+ if (options.access && !(await options.access({ req })))
170
+ return json({ error: `You may not ${verb} this transcript.` }, 403);
171
+ const apiKey = await resolveAPIKey(req, options);
172
+ if (!apiKey)
173
+ return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
174
+ const target = await locate(req, collection, options, rowFields, 'admin');
175
+ if (target instanceof Response)
176
+ return target;
177
+ if (target.data.status !== 'done' || !target.data.recordingId)
178
+ return json({ error: 'Transcribe the audio first.' }, 409);
179
+ return { api: new VocalStackAPI(apiKey, apiURL), target };
180
+ };
181
+ /** The body's languages (none of them the spoken one) and voice. */
182
+ const bodyOf = async (req, spoken) => {
183
+ const body = (await req.json?.().catch(() => ({})));
184
+ const langs = Array.isArray(body.langs) ? [...new Set(body.langs.map(String).map((l) => l.toLowerCase()))] : [];
185
+ if (!langs.length || langs.some((l) => !LANG.test(l) || l === spoken))
186
+ return undefined;
187
+ return { langs, voice: typeof body.voice === 'string' && body.voice.trim() ? body.voice.trim() : undefined };
188
+ };
189
+ const defaultVoice = async (req, target) => (await options.speechVoice?.({ collection, doc: target.doc, req, row: target.row })) ?? null;
190
+ return [
191
+ {
192
+ method: 'post',
193
+ path: '/:id/vocalstack/translate',
194
+ handler: async (req) => {
195
+ const found = await editable(req, 'translate');
196
+ if (found instanceof Response)
197
+ return found;
198
+ const { api, target } = found;
199
+ const asked = await bodyOf(req, target.data.language);
200
+ if (!asked)
201
+ return json({ error: 'Name the languages to translate into.' }, 400);
202
+ const deadline = Date.now() + BUDGET_MS;
203
+ try {
204
+ let more = false;
205
+ let data = target.data;
206
+ for (const lang of asked.langs) {
207
+ if (Date.now() > deadline) {
208
+ more = true;
209
+ continue;
210
+ }
211
+ const done = await translate(api, { ...target, data }, lang, deadline);
212
+ data = done.data;
213
+ more ||= done.more;
214
+ }
215
+ return json({ more, vocalstack: data });
216
+ }
217
+ catch (err) {
218
+ return apiError(err);
219
+ }
220
+ },
221
+ },
222
+ {
223
+ method: 'delete',
224
+ path: '/:id/vocalstack/translate',
225
+ handler: async (req) => {
226
+ const found = await editable(req, 'change');
227
+ if (found instanceof Response)
228
+ return found;
229
+ const lang = req.searchParams.get('lang') ?? '';
230
+ await dropReading(req, readings, found.target.data.speech?.[lang]);
231
+ const vocalstack = await found.target.save((current) => {
232
+ const { [lang]: _t, ...translations } = current.translations ?? {};
233
+ const { [lang]: _s, ...speech } = current.speech ?? {};
234
+ return { speech, translations };
235
+ });
236
+ return json({ vocalstack });
237
+ },
238
+ },
239
+ {
240
+ method: 'post',
241
+ path: '/:id/vocalstack/speak',
242
+ handler: async (req) => {
243
+ const found = await editable(req, 'read out');
244
+ if (found instanceof Response)
245
+ return found;
246
+ const { api, target } = found;
247
+ const asked = await bodyOf(req, target.data.language);
248
+ if (!asked)
249
+ return json({ error: 'Name the languages to read out.' }, 400);
250
+ const { langs } = asked;
251
+ const voice = asked.voice ?? (await defaultVoice(req, target)) ?? undefined;
252
+ try {
253
+ // A reading speaks the translation, so every language needs one first.
254
+ const deadline = Date.now() + BUDGET_MS;
255
+ 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);
263
+ }
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);
272
+ }
273
+ catch (err) {
274
+ return apiError(err);
275
+ }
276
+ },
277
+ },
278
+ {
279
+ method: 'get',
280
+ path: '/:id/vocalstack/speak',
281
+ handler: async (req) => {
282
+ if (!req.user)
283
+ return json({ error: 'Sign in first.' }, 401);
284
+ const target = await locate(req, collection, options, rowFields, 'user');
285
+ if (target instanceof Response)
286
+ 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)
293
+ return answer(target.data);
294
+ const apiKey = await resolveAPIKey(req, options);
295
+ if (!apiKey)
296
+ return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
297
+ 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);
351
+ }
352
+ catch (err) {
353
+ return apiError(err);
354
+ }
355
+ },
356
+ },
357
+ {
358
+ method: 'get',
359
+ path: '/:id/vocalstack/audio',
360
+ handler: async (req) => {
361
+ // Public: whoever may read the document may listen, signed in or not.
362
+ const target = await locate(req, collection, options, rowFields, 'user');
363
+ if (target instanceof Response)
364
+ return target;
365
+ const { language, recordingId, speech } = target.data;
366
+ if (!recordingId)
367
+ return json({ error: 'No audio.' }, 404);
368
+ const lang = req.searchParams.get('lang')?.toLowerCase();
369
+ const spoken = !lang || lang === language;
370
+ const reading = spoken ? undefined : speech?.[lang];
371
+ if (!spoken && reading?.state !== 'sealed')
372
+ return json({ error: 'There is no reading in that language.' }, 404);
373
+ // Kept files are served from the site's own storage: no VocalStack request.
374
+ const own = spoken ? await target.url().catch(() => undefined) : reading?.audio?.url;
375
+ if (own) {
376
+ 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 });
377
+ }
378
+ const apiKey = await resolveAPIKey(req, options);
379
+ if (!apiKey)
380
+ return json({ error: 'Not available.' }, 404);
381
+ try {
382
+ 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.
384
+ return new Response(null, { headers: { 'cache-control': 'public, max-age=300, s-maxage=300', location: url }, status: 302 });
385
+ }
386
+ catch (err) {
387
+ return apiError(err);
388
+ }
389
+ },
390
+ },
391
+ ];
392
+ }