@vocalstack/payload 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +141 -2
- package/dist/api.d.ts +171 -0
- package/dist/api.js +178 -0
- package/dist/components/Brand.d.ts +13 -0
- package/dist/components/Brand.js +19 -0
- package/dist/components/ConnectionPanel.d.ts +3 -0
- package/dist/components/ConnectionPanel.js +41 -0
- package/dist/components/SpeechField.d.ts +7 -0
- package/dist/components/SpeechField.js +177 -0
- package/dist/components/TranscribeButton.d.ts +8 -0
- package/dist/components/TranscribeButton.js +197 -0
- package/dist/components/TranscriptField.d.ts +3 -0
- package/dist/components/TranscriptField.js +167 -0
- package/dist/components/VoiceField.d.ts +1 -0
- package/dist/components/VoiceField.js +226 -0
- package/dist/components/brandAssets.d.ts +11 -0
- package/dist/components/brandAssets.js +6 -0
- package/dist/components/useConnection.d.ts +11 -0
- package/dist/components/useConnection.js +59 -0
- package/dist/endpoints/connection.d.ts +14 -0
- package/dist/endpoints/connection.js +132 -0
- package/dist/endpoints/speech.d.ts +12 -0
- package/dist/endpoints/speech.js +392 -0
- package/dist/endpoints/stream.d.ts +14 -0
- package/dist/endpoints/stream.js +180 -0
- package/dist/endpoints/transcribe.d.ts +33 -0
- package/dist/endpoints/transcribe.js +268 -0
- package/dist/endpoints/voices.d.ts +20 -0
- package/dist/endpoints/voices.js +275 -0
- package/dist/exports/client.d.ts +5 -0
- package/dist/exports/client.js +6 -0
- package/dist/fileSource.d.ts +12 -0
- package/dist/fileSource.js +40 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +184 -0
- package/dist/readings.d.ts +6 -0
- package/dist/readings.js +24 -0
- package/dist/settings.d.ts +20 -0
- package/dist/settings.js +47 -0
- package/dist/text.d.ts +29 -0
- package/dist/text.js +78 -0
- package/dist/types.d.ts +218 -0
- package/dist/types.js +1 -0
- package/package.json +47 -4
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { CollectionSlug, Endpoint } from 'payload';
|
|
2
|
+
import type { AudioFieldConfig, VocalStackPluginOptions } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* GET /:id/vocalstack/stream: the job live, as Server-Sent Events. The server holds
|
|
5
|
+
* the VocalStack subscribe socket (the API key never reaches the browser) and sends
|
|
6
|
+
* progress { progress, phase, audio } as it changes
|
|
7
|
+
* snapshot { sentences } everything so far, once caught up
|
|
8
|
+
* sentence { sentence } | { id, removed } a settled sentence, new or rewritten
|
|
9
|
+
* draft { words } words heard after the last settled sentence
|
|
10
|
+
* done | failed | stopped (StatusResponse) once, saved on the document; then it closes
|
|
11
|
+
* Sentences carry their words as [start, end, text]. A dropped stream is resumed by
|
|
12
|
+
* EventSource: it reconnects and gets a fresh snapshot.
|
|
13
|
+
*/
|
|
14
|
+
export declare function streamEndpoint(collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[]): Endpoint;
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { DEFAULT_API_URL, VocalStackAPI } from '../api.js';
|
|
2
|
+
import { resolveAPIKey } from '../settings.js';
|
|
3
|
+
import { attachWords } from '../text.js';
|
|
4
|
+
import { apiError, checkJob, locate, toSentences } from './transcribe.js';
|
|
5
|
+
const OVER = new Set(['done', 'failed', 'cropping', 'ended', 'finalized']);
|
|
6
|
+
/**
|
|
7
|
+
* GET /:id/vocalstack/stream: the job live, as Server-Sent Events. The server holds
|
|
8
|
+
* the VocalStack subscribe socket (the API key never reaches the browser) and sends
|
|
9
|
+
* progress { progress, phase, audio } as it changes
|
|
10
|
+
* snapshot { sentences } everything so far, once caught up
|
|
11
|
+
* sentence { sentence } | { id, removed } a settled sentence, new or rewritten
|
|
12
|
+
* draft { words } words heard after the last settled sentence
|
|
13
|
+
* done | failed | stopped (StatusResponse) once, saved on the document; then it closes
|
|
14
|
+
* Sentences carry their words as [start, end, text]. A dropped stream is resumed by
|
|
15
|
+
* EventSource: it reconnects and gets a fresh snapshot.
|
|
16
|
+
*/
|
|
17
|
+
export function streamEndpoint(collection, options, rowFields) {
|
|
18
|
+
const apiURL = options.apiURL ?? DEFAULT_API_URL;
|
|
19
|
+
return {
|
|
20
|
+
method: 'get',
|
|
21
|
+
path: '/:id/vocalstack/stream',
|
|
22
|
+
handler: async (req) => {
|
|
23
|
+
if (!req.user)
|
|
24
|
+
return Response.json({ error: 'Sign in first.' }, { status: 401 });
|
|
25
|
+
const target = await locate(req, collection, options, rowFields, 'user');
|
|
26
|
+
if (target instanceof Response)
|
|
27
|
+
return target;
|
|
28
|
+
const recordingId = target.data.recordingId;
|
|
29
|
+
if (target.data.status !== 'processing' || !recordingId)
|
|
30
|
+
return Response.json({ status: target.data.status ?? 'idle', vocalstack: target.data });
|
|
31
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
32
|
+
if (!apiKey)
|
|
33
|
+
return Response.json({ code: 'not_connected', error: 'Connect VocalStack first.' }, { status: 409 });
|
|
34
|
+
const api = new VocalStackAPI(apiKey, apiURL);
|
|
35
|
+
const encoder = new TextEncoder();
|
|
36
|
+
let socket;
|
|
37
|
+
let heartbeat;
|
|
38
|
+
let draftTimer;
|
|
39
|
+
let closed = false;
|
|
40
|
+
const stream = new ReadableStream({
|
|
41
|
+
cancel() {
|
|
42
|
+
closed = true;
|
|
43
|
+
cleanup();
|
|
44
|
+
},
|
|
45
|
+
start(controller) {
|
|
46
|
+
const send = (event, data) => {
|
|
47
|
+
if (!closed)
|
|
48
|
+
controller.enqueue(encoder.encode(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`));
|
|
49
|
+
};
|
|
50
|
+
const finish = (result) => {
|
|
51
|
+
if (closed)
|
|
52
|
+
return;
|
|
53
|
+
send(result.stopped ? 'stopped' : result.status === 'processing' ? 'progress' : result.status, result);
|
|
54
|
+
closed = true;
|
|
55
|
+
cleanup();
|
|
56
|
+
controller.close();
|
|
57
|
+
};
|
|
58
|
+
// VocalStack signals the end several ways (progress, state, socket close); check once at a time.
|
|
59
|
+
let settling;
|
|
60
|
+
const settle = () => (settling ??= checkJob(api, target, recordingId)
|
|
61
|
+
.then((r) => (r.status === 'processing' ? undefined : finish(r)), (err) => finish({ error: err.message, status: 'failed' }))
|
|
62
|
+
.finally(() => (settling = undefined)));
|
|
63
|
+
// What the page has been told: settled sentences by id, the words of committed
|
|
64
|
+
// segments (sentences take theirs by time), and the words heard since.
|
|
65
|
+
const sentences = new Map();
|
|
66
|
+
const segmentWords = new Map();
|
|
67
|
+
let draft = [];
|
|
68
|
+
let caughtUp = false;
|
|
69
|
+
let lastProgress = '';
|
|
70
|
+
const withWords = (s, seqs) => {
|
|
71
|
+
const pool = seqs?.length ? seqs.flatMap((q) => segmentWords.get(q) ?? []) : [...segmentWords.values()].flat();
|
|
72
|
+
return attachWords([s], pool)[0];
|
|
73
|
+
};
|
|
74
|
+
const sendDraft = () => {
|
|
75
|
+
draftTimer = undefined;
|
|
76
|
+
const settledTo = Math.max(0, ...[...sentences.values()].map((s) => s.end));
|
|
77
|
+
draft = draft.filter((w) => w.end > settledTo);
|
|
78
|
+
send('draft', { words: draft.map((w) => [w.start, w.end, w.text.trim()]) });
|
|
79
|
+
};
|
|
80
|
+
const scheduleDraft = () => {
|
|
81
|
+
if (caughtUp)
|
|
82
|
+
draftTimer ??= setTimeout(sendDraft, 200);
|
|
83
|
+
};
|
|
84
|
+
controller.enqueue(encoder.encode('retry: 2000\n\n'));
|
|
85
|
+
heartbeat = setInterval(() => !closed && controller.enqueue(encoder.encode(': ping\n\n')), 15000);
|
|
86
|
+
const wsURL = `${apiURL.replace(/^http/, 'ws')}/v1/recordings/${encodeURIComponent(recordingId)}/subscribe`;
|
|
87
|
+
// Node's WebSocket (undici) takes headers, which the DOM type does not know about.
|
|
88
|
+
socket = new WebSocket(wsURL, { headers: { authorization: `Bearer ${apiKey}` } });
|
|
89
|
+
socket.onmessage = (message) => {
|
|
90
|
+
let frame;
|
|
91
|
+
try {
|
|
92
|
+
frame = JSON.parse(String(message.data));
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
switch (frame.type) {
|
|
98
|
+
case 'job.progress': {
|
|
99
|
+
if (frame.state && OVER.has(frame.state))
|
|
100
|
+
return void settle();
|
|
101
|
+
const progress = frame.state === 'fetching' ? (frame.phasePct ?? 0) : (frame.pct ?? 0);
|
|
102
|
+
const audio = frame.processedS !== undefined ? { processedS: frame.processedS, totalS: frame.totalS ?? undefined } : undefined;
|
|
103
|
+
const update = { audio, phase: frame.state === 'fetching' ? (frame.phase ?? 'fetching') : frame.state, progress, status: 'processing' };
|
|
104
|
+
// VocalStack repeats progress frames; pass on only what changed.
|
|
105
|
+
const key = JSON.stringify(update);
|
|
106
|
+
if (key === lastProgress)
|
|
107
|
+
return;
|
|
108
|
+
lastProgress = key;
|
|
109
|
+
return send('progress', update);
|
|
110
|
+
}
|
|
111
|
+
case 'recording.state':
|
|
112
|
+
case 'subscribe.ready':
|
|
113
|
+
if (frame.state && OVER.has(frame.state))
|
|
114
|
+
return void settle();
|
|
115
|
+
if (frame.type === 'subscribe.ready') {
|
|
116
|
+
// Catch up on everything said before the socket opened. Live frames that
|
|
117
|
+
// arrive meanwhile update the same maps by id, so the overlap is harmless.
|
|
118
|
+
void api.transcript(recordingId).then((t) => {
|
|
119
|
+
for (const g of t.segments ?? [])
|
|
120
|
+
if (!g.suppressed && g.words)
|
|
121
|
+
segmentWords.set(g.seq, g.words);
|
|
122
|
+
for (const s of toSentences(t))
|
|
123
|
+
if (s.id !== undefined && !sentences.has(s.id))
|
|
124
|
+
sentences.set(s.id, s);
|
|
125
|
+
caughtUp = true;
|
|
126
|
+
send('snapshot', { sentences: [...sentences.values()].sort((a, b) => a.start - b.start) });
|
|
127
|
+
scheduleDraft();
|
|
128
|
+
}, () => undefined);
|
|
129
|
+
}
|
|
130
|
+
return;
|
|
131
|
+
case 'transcript.committed':
|
|
132
|
+
if (frame.segment && !frame.segment.suppressed && frame.segment.words)
|
|
133
|
+
segmentWords.set(frame.segment.seq, frame.segment.words);
|
|
134
|
+
return;
|
|
135
|
+
case 'transcript.sentence': {
|
|
136
|
+
const s = frame.sentence;
|
|
137
|
+
if (!s)
|
|
138
|
+
return;
|
|
139
|
+
if (s.suppressed || !s.text.trim()) {
|
|
140
|
+
sentences.delete(s.sentenceId);
|
|
141
|
+
if (caughtUp)
|
|
142
|
+
send('sentence', { id: s.sentenceId, removed: true });
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
const sentence = withWords({ id: s.sentenceId, end: s.end, speaker: s.speaker, start: s.start, text: s.text.trim() }, s.seqs);
|
|
146
|
+
sentences.set(s.sentenceId, sentence);
|
|
147
|
+
if (caughtUp)
|
|
148
|
+
send('sentence', { sentence });
|
|
149
|
+
}
|
|
150
|
+
return scheduleDraft();
|
|
151
|
+
}
|
|
152
|
+
case 'transcript.words':
|
|
153
|
+
draft.push(...(frame.words ?? []));
|
|
154
|
+
return scheduleDraft();
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
// The socket ended without the job ending: say where it stands, then let EventSource reconnect.
|
|
158
|
+
socket.onclose = () => {
|
|
159
|
+
if (!closed)
|
|
160
|
+
void settle().then(() => !closed && (closed = true, cleanup(), controller.close()));
|
|
161
|
+
};
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
function cleanup() {
|
|
165
|
+
clearInterval(heartbeat);
|
|
166
|
+
clearTimeout(draftTimer);
|
|
167
|
+
if (socket && socket.readyState <= 1)
|
|
168
|
+
socket.close();
|
|
169
|
+
}
|
|
170
|
+
try {
|
|
171
|
+
return new Response(stream, {
|
|
172
|
+
headers: { 'cache-control': 'no-cache, no-transform', connection: 'keep-alive', 'content-type': 'text/event-stream; charset=utf-8', 'x-accel-buffering': 'no' },
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
catch (err) {
|
|
176
|
+
return apiError(err);
|
|
177
|
+
}
|
|
178
|
+
},
|
|
179
|
+
};
|
|
180
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { CollectionSlug, Endpoint, PayloadRequest } from 'payload';
|
|
2
|
+
import type { ArrayRow, AudioFieldConfig, StatusResponse, TranscriptSentence, VocalStackFieldData, VocalStackPluginOptions } from '../types.js';
|
|
3
|
+
import { type Transcript, VocalStackAPI } from '../api.js';
|
|
4
|
+
/** Whether the signed-in user may update this document, by the collection's own `access.update`. */
|
|
5
|
+
export declare function canUpdate(req: PayloadRequest, collection: CollectionSlug, id: number | string): Promise<boolean>;
|
|
6
|
+
type Patch = ((current: VocalStackFieldData) => VocalStackFieldData) | VocalStackFieldData;
|
|
7
|
+
/** One transcribable thing: an upload document, or one row of an array field. */
|
|
8
|
+
export type Target = {
|
|
9
|
+
data: VocalStackFieldData;
|
|
10
|
+
doc: Record<string, unknown>;
|
|
11
|
+
fileName: string;
|
|
12
|
+
name: string;
|
|
13
|
+
/** Set when the target is a row of an array field. */
|
|
14
|
+
row?: ArrayRow;
|
|
15
|
+
/** Merge into the saved field: a patch, or one made from the field as it is saved now. */
|
|
16
|
+
save: (patch: Patch) => Promise<VocalStackFieldData>;
|
|
17
|
+
url: () => Promise<string | undefined>;
|
|
18
|
+
};
|
|
19
|
+
export declare function locate(req: PayloadRequest, collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[], readAs: 'admin' | 'user'): Promise<Response | Target>;
|
|
20
|
+
/** A transcript's sentences, each with its words. */
|
|
21
|
+
export declare function toSentences(t: Pick<Transcript, 'segments' | 'sentences'>): TranscriptSentence[];
|
|
22
|
+
export declare function apiError(err: unknown): Response;
|
|
23
|
+
/**
|
|
24
|
+
* Where a job stands, saving the outcome on the document once it is over: the
|
|
25
|
+
* whole transcript when done, the reason when it failed.
|
|
26
|
+
*/
|
|
27
|
+
export declare function checkJob(api: VocalStackAPI, target: Target, recordingId: string): Promise<StatusResponse>;
|
|
28
|
+
/**
|
|
29
|
+
* POST /:id/vocalstack/transcribe and GET /:id/vocalstack/status. With no query
|
|
30
|
+
* they act on the upload document itself; with `?field=<array>&row=<row id>` on one row.
|
|
31
|
+
*/
|
|
32
|
+
export declare function transcribeEndpoints(collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[]): Endpoint[];
|
|
33
|
+
export {};
|