@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,268 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
3
|
+
import { fetchFile, isPublicURL, resolveFileURL } from '../fileSource.js';
|
|
4
|
+
import { attachWords, transcriptText } from '../text.js';
|
|
5
|
+
import { resolveAPIKey } from '../settings.js';
|
|
6
|
+
const json = (body, status = 200) => Response.json(body, { status });
|
|
7
|
+
/**
|
|
8
|
+
* Saves to one document, one at a time. Payload writes array fields by deleting and
|
|
9
|
+
* re-inserting every row (of every array), so two overlapping saves collide in the database.
|
|
10
|
+
*/
|
|
11
|
+
const queues = new Map();
|
|
12
|
+
function serially(key, run) {
|
|
13
|
+
const next = (queues.get(key) ?? Promise.resolve()).then(run, run);
|
|
14
|
+
const settled = next.catch(() => undefined);
|
|
15
|
+
queues.set(key, settled);
|
|
16
|
+
void settled.then(() => queues.get(key) === settled && queues.delete(key));
|
|
17
|
+
return next;
|
|
18
|
+
}
|
|
19
|
+
/** Finished jobs being saved, so that every "done" signal for one job shares a single save. */
|
|
20
|
+
const finishing = new Map();
|
|
21
|
+
/** Whether the signed-in user may update this document, by the collection's own `access.update`. */
|
|
22
|
+
export async function canUpdate(req, collection, id) {
|
|
23
|
+
if (!req.user)
|
|
24
|
+
return false;
|
|
25
|
+
const access = req.payload.collections[collection]?.config.access.update;
|
|
26
|
+
if (!access)
|
|
27
|
+
return true;
|
|
28
|
+
const result = await access({ id, req });
|
|
29
|
+
if (typeof result !== 'object')
|
|
30
|
+
return Boolean(result);
|
|
31
|
+
const { totalDocs } = await req.payload.count({ collection, overrideAccess: true, req, where: { and: [{ id: { equals: id } }, result] } });
|
|
32
|
+
return totalDocs > 0;
|
|
33
|
+
}
|
|
34
|
+
const merge = (current, patch) => ({
|
|
35
|
+
...current,
|
|
36
|
+
...(typeof patch === 'function' ? patch(current ?? {}) : patch),
|
|
37
|
+
});
|
|
38
|
+
export async function locate(req, collection, options, rowFields, readAs) {
|
|
39
|
+
const id = req.routeParams?.id;
|
|
40
|
+
const find = (overrideAccess) => req.payload.findByID({ id, collection, depth: 0, overrideAccess, req, user: req.user }).catch(() => null);
|
|
41
|
+
const doc = await find(readAs === 'admin');
|
|
42
|
+
if (!doc)
|
|
43
|
+
return json({ error: 'Not found.' }, 404);
|
|
44
|
+
const field = req.searchParams.get('field');
|
|
45
|
+
if (!field) {
|
|
46
|
+
const upload = doc;
|
|
47
|
+
if (!req.payload.collections[collection]?.config.upload)
|
|
48
|
+
return json({ error: 'Not an upload collection.' }, 400);
|
|
49
|
+
if (!upload.mimeType?.startsWith('audio/'))
|
|
50
|
+
return json({ error: 'Only audio files can be transcribed.' }, 400);
|
|
51
|
+
return {
|
|
52
|
+
data: upload.vocalstack ?? {},
|
|
53
|
+
doc,
|
|
54
|
+
fileName: upload.filename ?? 'audio',
|
|
55
|
+
name: upload.filename ?? `${collection} ${id}`,
|
|
56
|
+
save: (patch) => serially(`${collection}:${id}`, async () => {
|
|
57
|
+
const fresh = (typeof patch === 'function' ? (await find(true)) : null) ?? upload;
|
|
58
|
+
const vocalstack = merge(fresh.vocalstack, patch);
|
|
59
|
+
await req.payload.update({ id, collection, data: { vocalstack }, depth: 0, overrideAccess: true, req });
|
|
60
|
+
return vocalstack;
|
|
61
|
+
}),
|
|
62
|
+
url: () => resolveFileURL(req, collection, upload, options),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const config = rowFields.find((f) => f.field === field);
|
|
66
|
+
if (!config)
|
|
67
|
+
return json({ error: `${field} is not a VocalStack audio field.` }, 400);
|
|
68
|
+
const rowId = req.searchParams.get('row');
|
|
69
|
+
const row = (doc[field] ?? []).find((r) => r.id === rowId);
|
|
70
|
+
if (!row)
|
|
71
|
+
return json({ error: 'Save the document first, then transcribe.' }, 404);
|
|
72
|
+
const base = req.payload.config.serverURL || req.origin;
|
|
73
|
+
return {
|
|
74
|
+
data: row.vocalstack ?? {},
|
|
75
|
+
doc,
|
|
76
|
+
fileName: 'audio',
|
|
77
|
+
name: config.name?.({ doc, row }) ?? (typeof doc.title === 'string' && doc.title ? doc.title : `${collection} ${id}`),
|
|
78
|
+
row,
|
|
79
|
+
save: (patch) => serially(`${collection}:${id}`, async () => {
|
|
80
|
+
// Re-read so edits saved to other rows meanwhile are kept; arrays are written whole.
|
|
81
|
+
const fresh = (await find(true)) ?? doc;
|
|
82
|
+
let saved;
|
|
83
|
+
const rows = (fresh[field] ?? []).map((r) => {
|
|
84
|
+
if (r.id !== rowId)
|
|
85
|
+
return r;
|
|
86
|
+
saved = merge(r.vocalstack, patch);
|
|
87
|
+
return { ...r, vocalstack: saved };
|
|
88
|
+
});
|
|
89
|
+
if (!saved)
|
|
90
|
+
throw new Error('That row was removed.');
|
|
91
|
+
await req.payload.update({ id, collection, data: { [field]: rows }, depth: 0, overrideAccess: true, req });
|
|
92
|
+
return saved;
|
|
93
|
+
}),
|
|
94
|
+
url: async () => {
|
|
95
|
+
const url = await config.audioURL({ doc, req, row });
|
|
96
|
+
return url ? new URL(url, base).toString() : undefined;
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** A transcript's sentences, each with its words. */
|
|
101
|
+
export function toSentences(t) {
|
|
102
|
+
const sentences = t.sentences
|
|
103
|
+
.filter((s) => !s.suppressed && s.text.trim())
|
|
104
|
+
.map(({ end, sentenceId, speaker, start, text }) => ({ id: sentenceId, end, speaker, start, text: text.trim() }));
|
|
105
|
+
return attachWords(sentences, (t.segments ?? []).filter((g) => !g.suppressed).flatMap((g) => g.words ?? []));
|
|
106
|
+
}
|
|
107
|
+
export function apiError(err) {
|
|
108
|
+
if (err instanceof VocalStackAPIError) {
|
|
109
|
+
const status = err.status === 401 ? 409 : err.status >= 500 ? 502 : err.status;
|
|
110
|
+
const code = err.status === 401 ? 'not_connected' : err.code;
|
|
111
|
+
const message = err.status === 401 ? 'The VocalStack API key was refused. Reconnect VocalStack.' : err.message;
|
|
112
|
+
return json({ code, error: message }, status);
|
|
113
|
+
}
|
|
114
|
+
return json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Where a job stands, saving the outcome on the document once it is over: the
|
|
118
|
+
* whole transcript when done, the reason when it failed.
|
|
119
|
+
*/
|
|
120
|
+
export async function checkJob(api, target, recordingId) {
|
|
121
|
+
const job = await api.job(recordingId);
|
|
122
|
+
if (job.state === 'stopped' || (job.state === 'failed' && job.errorCode === 'stopped'))
|
|
123
|
+
return restore(target);
|
|
124
|
+
if (job.state === 'failed' || job.state === 'cropping') {
|
|
125
|
+
const error = job.state === 'cropping' ? 'VocalStack is waiting for a crop window; open the transcription in VocalStack.' : (job.error ?? 'The transcription failed.');
|
|
126
|
+
return { error, status: 'failed', vocalstack: await target.save({ error, status: 'failed' }) };
|
|
127
|
+
}
|
|
128
|
+
if (job.state !== 'done') {
|
|
129
|
+
const progress = job.state === 'fetching' ? (job.progress.phasePct ?? 0) : job.progress.pct;
|
|
130
|
+
if (job.state !== 'transcribing')
|
|
131
|
+
return { phase: job.progress.phase ?? job.state, progress, status: 'processing' };
|
|
132
|
+
// Sentences are readable while the job runs; send what is there so far.
|
|
133
|
+
const partial = await api.transcript(recordingId).then(toSentences, () => undefined);
|
|
134
|
+
return { audio: { processedS: job.progress.processedS ?? 0, totalS: job.progress.totalS ?? undefined }, partial, phase: 'transcribing', progress, status: 'processing' };
|
|
135
|
+
}
|
|
136
|
+
let saving = finishing.get(recordingId);
|
|
137
|
+
if (!saving) {
|
|
138
|
+
saving = saveTranscript(api, target, recordingId);
|
|
139
|
+
finishing.set(recordingId, saving);
|
|
140
|
+
void saving.catch(() => undefined).then(() => finishing.delete(recordingId));
|
|
141
|
+
}
|
|
142
|
+
return saving;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* A stopped job leaves the field as it was before Transcribe: the earlier transcript, if
|
|
146
|
+
* there was one (a new job only replaces it once done), or none. The job's partial
|
|
147
|
+
* transcript stays in VocalStack.
|
|
148
|
+
*/
|
|
149
|
+
async function restore(target) {
|
|
150
|
+
const status = target.data.transcript ? 'done' : 'idle';
|
|
151
|
+
return { status, stopped: true, vocalstack: await target.save({ error: null, status }) };
|
|
152
|
+
}
|
|
153
|
+
async function saveTranscript(api, target, recordingId) {
|
|
154
|
+
const transcript = await api.transcript(recordingId);
|
|
155
|
+
const sentences = toSentences(transcript);
|
|
156
|
+
const vocalstack = await target.save({
|
|
157
|
+
error: null,
|
|
158
|
+
language: transcript.lang ?? transcript.sentences.find((s) => s.language)?.language ?? null,
|
|
159
|
+
sentences,
|
|
160
|
+
// A new recording: translations and readings of the old one no longer match it.
|
|
161
|
+
speech: null,
|
|
162
|
+
status: 'done',
|
|
163
|
+
transcribedAt: new Date().toISOString(),
|
|
164
|
+
transcript: transcriptText(sentences),
|
|
165
|
+
translations: null,
|
|
166
|
+
});
|
|
167
|
+
return { progress: 100, status: 'done', vocalstack };
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* POST /:id/vocalstack/transcribe and GET /:id/vocalstack/status. With no query
|
|
171
|
+
* they act on the upload document itself; with `?field=<array>&row=<row id>` on one row.
|
|
172
|
+
*/
|
|
173
|
+
export function transcribeEndpoints(collection, options, rowFields) {
|
|
174
|
+
const apiURL = options.apiURL ?? DEFAULT_API_URL;
|
|
175
|
+
return [
|
|
176
|
+
{
|
|
177
|
+
method: 'post',
|
|
178
|
+
path: '/:id/vocalstack/transcribe',
|
|
179
|
+
handler: async (req) => {
|
|
180
|
+
const id = req.routeParams?.id;
|
|
181
|
+
if (!(await canUpdate(req, collection, id)))
|
|
182
|
+
return json({ error: 'You may not transcribe this file.' }, 403);
|
|
183
|
+
if (options.access && !(await options.access({ req })))
|
|
184
|
+
return json({ error: 'You may not transcribe this file.' }, 403);
|
|
185
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
186
|
+
if (!apiKey)
|
|
187
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
188
|
+
const target = await locate(req, collection, options, rowFields, 'admin');
|
|
189
|
+
if (target instanceof Response)
|
|
190
|
+
return target;
|
|
191
|
+
if (target.data.status === 'processing')
|
|
192
|
+
return json({ status: 'processing', vocalstack: target.data });
|
|
193
|
+
const url = await target.url();
|
|
194
|
+
if (!url)
|
|
195
|
+
return json({ error: 'There is no audio file here.' }, 400);
|
|
196
|
+
const api = new VocalStackAPI(apiKey, apiURL);
|
|
197
|
+
const call = { idempotencyKey: `payload:${collection}:${id}:${randomUUID()}`, name: target.name, spokenLanguage: options.spokenLanguage };
|
|
198
|
+
try {
|
|
199
|
+
const tx = isPublicURL(url)
|
|
200
|
+
? await api.transcribeURL(url, call)
|
|
201
|
+
: await api.transcribeFile(await fetchFile(req, url), decodeURIComponent(new URL(url).pathname.split('/').pop() || target.fileName), call);
|
|
202
|
+
if (!tx.job)
|
|
203
|
+
throw new Error('VocalStack did not start a job for this file.');
|
|
204
|
+
const vocalstack = await target.save({ error: null, recordingId: tx.job.recordingId, status: 'processing', transcriptionId: tx.id });
|
|
205
|
+
return json({ phase: tx.job.state, progress: 0, status: 'processing', vocalstack }, 202);
|
|
206
|
+
}
|
|
207
|
+
catch (err) {
|
|
208
|
+
return apiError(err);
|
|
209
|
+
}
|
|
210
|
+
},
|
|
211
|
+
},
|
|
212
|
+
{
|
|
213
|
+
method: 'get',
|
|
214
|
+
path: '/:id/vocalstack/status',
|
|
215
|
+
handler: async (req) => {
|
|
216
|
+
if (!req.user)
|
|
217
|
+
return json({ error: 'Sign in first.' }, 401);
|
|
218
|
+
// Read through access control: only someone who can see the document sees its status.
|
|
219
|
+
const target = await locate(req, collection, options, rowFields, 'user');
|
|
220
|
+
if (target instanceof Response)
|
|
221
|
+
return target;
|
|
222
|
+
const field = target.data;
|
|
223
|
+
if (field.status !== 'processing' || !field.recordingId)
|
|
224
|
+
return json({ status: field.status ?? 'idle', vocalstack: field });
|
|
225
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
226
|
+
if (!apiKey)
|
|
227
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
228
|
+
try {
|
|
229
|
+
return json(await checkJob(new VocalStackAPI(apiKey, apiURL), target, field.recordingId));
|
|
230
|
+
}
|
|
231
|
+
catch (err) {
|
|
232
|
+
return apiError(err);
|
|
233
|
+
}
|
|
234
|
+
},
|
|
235
|
+
},
|
|
236
|
+
{
|
|
237
|
+
method: 'post',
|
|
238
|
+
path: '/:id/vocalstack/stop',
|
|
239
|
+
handler: async (req) => {
|
|
240
|
+
const id = req.routeParams?.id;
|
|
241
|
+
if (!(await canUpdate(req, collection, id)))
|
|
242
|
+
return json({ error: 'You may not stop this transcription.' }, 403);
|
|
243
|
+
if (options.access && !(await options.access({ req })))
|
|
244
|
+
return json({ error: 'You may not stop this transcription.' }, 403);
|
|
245
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
246
|
+
if (!apiKey)
|
|
247
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
248
|
+
const target = await locate(req, collection, options, rowFields, 'admin');
|
|
249
|
+
if (target instanceof Response)
|
|
250
|
+
return target;
|
|
251
|
+
const { recordingId, status } = target.data;
|
|
252
|
+
if (status !== 'processing' || !recordingId)
|
|
253
|
+
return json({ status: status ?? 'idle', vocalstack: target.data });
|
|
254
|
+
const api = new VocalStackAPI(apiKey, apiURL);
|
|
255
|
+
try {
|
|
256
|
+
await api.stop(recordingId, 'Stopped from Payload');
|
|
257
|
+
return json(await restore(target));
|
|
258
|
+
}
|
|
259
|
+
catch (err) {
|
|
260
|
+
// Too late to stop: the job ended meanwhile, so take its outcome instead.
|
|
261
|
+
if (err instanceof VocalStackAPIError && err.status === 409)
|
|
262
|
+
return json(await checkJob(api, target, recordingId).catch(() => restore(target)));
|
|
263
|
+
return apiError(err);
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
},
|
|
267
|
+
];
|
|
268
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Endpoint } from 'payload';
|
|
2
|
+
import type { VoiceCollectionConfig, VocalStackPluginOptions } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* A person's cloned voice, kept in the `vocalstackVoice` group of their document:
|
|
5
|
+
* GET /:id/vocalstack/voice where its training stands
|
|
6
|
+
* POST /:id/vocalstack/voice clone it: JSON { recordingId, startS, endS, consent },
|
|
7
|
+
* or multipart with a `file` sample and `_payload` { consent }
|
|
8
|
+
* DELETE /:id/vocalstack/voice delete it, in VocalStack too
|
|
9
|
+
* GET /:id/vocalstack/voice/sources recordings to take the sample from
|
|
10
|
+
* GET /:id/vocalstack/voice/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
|
|
11
|
+
* GET /:id/vocalstack/voice/preview the voice speaking (?lang=&format=ogg|caf)
|
|
12
|
+
* A sample is only ever taken from the recordings `config.recordings` offers for that document.
|
|
13
|
+
*/
|
|
14
|
+
export declare function voiceEndpoints(config: VoiceCollectionConfig, options: VocalStackPluginOptions): Endpoint[];
|
|
15
|
+
/**
|
|
16
|
+
* Shared admin lookups (signed in, and `options.access` when set):
|
|
17
|
+
* GET /vocalstack/languages what can be translated and spoken
|
|
18
|
+
* GET /vocalstack/voices?lang=&recording= voices that can speak a language
|
|
19
|
+
*/
|
|
20
|
+
export declare function lookupEndpoints(options: VocalStackPluginOptions): Endpoint[];
|
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { addDataAndFileToRequest } from 'payload';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
4
|
+
import { resolveAPIKey } from '../settings.js';
|
|
5
|
+
import { apiError, canUpdate } from './transcribe.js';
|
|
6
|
+
const json = (body, status = 200) => Response.json(body, { status });
|
|
7
|
+
// VocalStack clones from 30 s to 120 s of speech (a clip is at most 120 s).
|
|
8
|
+
const MIN_SAMPLE_S = 30;
|
|
9
|
+
const MAX_SAMPLE_S = 120;
|
|
10
|
+
const STATES = new Set(['failed', 'ready', 'training']);
|
|
11
|
+
/** VocalStack's voice as the document keeps it. */
|
|
12
|
+
const fieldData = (v) => ({
|
|
13
|
+
createdAt: v.createdAt,
|
|
14
|
+
error: v.error ?? null,
|
|
15
|
+
progress: v.progress,
|
|
16
|
+
sampleS: v.sampleS,
|
|
17
|
+
state: STATES.has(v.state) ? v.state : 'training',
|
|
18
|
+
voiceId: v.id,
|
|
19
|
+
});
|
|
20
|
+
const EMPTY = { consentAt: null, createdAt: null, error: null, progress: null, sampleS: null, state: 'none', voiceId: null };
|
|
21
|
+
/**
|
|
22
|
+
* A person's cloned voice, kept in the `vocalstackVoice` group of their document:
|
|
23
|
+
* GET /:id/vocalstack/voice where its training stands
|
|
24
|
+
* POST /:id/vocalstack/voice clone it: JSON { recordingId, startS, endS, consent },
|
|
25
|
+
* or multipart with a `file` sample and `_payload` { consent }
|
|
26
|
+
* DELETE /:id/vocalstack/voice delete it, in VocalStack too
|
|
27
|
+
* GET /:id/vocalstack/voice/sources recordings to take the sample from
|
|
28
|
+
* GET /:id/vocalstack/voice/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
|
|
29
|
+
* GET /:id/vocalstack/voice/preview the voice speaking (?lang=&format=ogg|caf)
|
|
30
|
+
* A sample is only ever taken from the recordings `config.recordings` offers for that document.
|
|
31
|
+
*/
|
|
32
|
+
export function voiceEndpoints(config, options) {
|
|
33
|
+
const { collection } = config;
|
|
34
|
+
const apiURL = options.apiURL ?? DEFAULT_API_URL;
|
|
35
|
+
const open = async (req, verb) => {
|
|
36
|
+
const id = req.routeParams?.id;
|
|
37
|
+
if (!(await canUpdate(req, collection, id)))
|
|
38
|
+
return json({ error: `You may not ${verb} this voice.` }, 403);
|
|
39
|
+
if (options.access && !(await options.access({ req })))
|
|
40
|
+
return json({ error: `You may not ${verb} this voice.` }, 403);
|
|
41
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
42
|
+
if (!apiKey)
|
|
43
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
44
|
+
const doc = (await req.payload.findByID({ id, collection, depth: 0, overrideAccess: true, req }).catch(() => null));
|
|
45
|
+
if (!doc)
|
|
46
|
+
return json({ error: 'Not found.' }, 404);
|
|
47
|
+
return { api: new VocalStackAPI(apiKey, apiURL), doc, id };
|
|
48
|
+
};
|
|
49
|
+
/** Whether the recording is one the host offers for this person (`config.recordings`). */
|
|
50
|
+
const ownRecording = async (req, doc, recordingId) => ((await config.recordings?.({ doc, req })) ?? []).some((s) => s.recordingId === recordingId);
|
|
51
|
+
const save = async (req, id, data) => {
|
|
52
|
+
await req.payload.update({ id, collection, data: { vocalstackVoice: data }, depth: 0, overrideAccess: true, req });
|
|
53
|
+
return data;
|
|
54
|
+
};
|
|
55
|
+
const nameOf = (req, doc) => {
|
|
56
|
+
const title = req.payload.collections[collection]?.config.admin?.useAsTitle;
|
|
57
|
+
const name = config.name?.({ doc }) ?? (title && typeof doc[title] === 'string' ? doc[title] : typeof doc.name === 'string' ? doc.name : `${collection} ${doc.id}`);
|
|
58
|
+
// VocalStack takes 1–60 characters.
|
|
59
|
+
return name.trim().slice(0, 60) || `${collection} ${doc.id}`;
|
|
60
|
+
};
|
|
61
|
+
return [
|
|
62
|
+
{
|
|
63
|
+
method: 'get',
|
|
64
|
+
path: '/:id/vocalstack/voice',
|
|
65
|
+
handler: async (req) => {
|
|
66
|
+
const found = await open(req, 'see');
|
|
67
|
+
if (found instanceof Response)
|
|
68
|
+
return found;
|
|
69
|
+
const { api, doc, id } = found;
|
|
70
|
+
const current = (doc.vocalstackVoice ?? {});
|
|
71
|
+
if (!current.voiceId || current.state === 'ready')
|
|
72
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: current });
|
|
73
|
+
try {
|
|
74
|
+
const next = { ...current, ...fieldData(await api.voice(current.voiceId)) };
|
|
75
|
+
const changed = next.state !== current.state || next.progress !== current.progress || next.error !== current.error;
|
|
76
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: changed ? await save(req, id, next) : current });
|
|
77
|
+
}
|
|
78
|
+
catch (err) {
|
|
79
|
+
// Deleted in the VocalStack dashboard: there is no voice any more.
|
|
80
|
+
if (err instanceof VocalStackAPIError && err.status === 404)
|
|
81
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: await save(req, id, EMPTY) });
|
|
82
|
+
return apiError(err);
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
method: 'post',
|
|
88
|
+
path: '/:id/vocalstack/voice',
|
|
89
|
+
handler: async (req) => {
|
|
90
|
+
const found = await open(req, 'create');
|
|
91
|
+
if (found instanceof Response)
|
|
92
|
+
return found;
|
|
93
|
+
const { api, doc, id } = found;
|
|
94
|
+
let sample;
|
|
95
|
+
let consent;
|
|
96
|
+
const multipart = req.headers.get('content-type')?.includes('multipart/');
|
|
97
|
+
try {
|
|
98
|
+
if (multipart) {
|
|
99
|
+
await addDataAndFileToRequest(req);
|
|
100
|
+
consent = req.data?.consent === true;
|
|
101
|
+
if (!req.file)
|
|
102
|
+
return json({ error: 'Add an audio sample.' }, 400);
|
|
103
|
+
sample = { blob: new Blob([new Uint8Array(req.file.data)], { type: req.file.mimetype }), name: req.file.name };
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
const body = (await req.json?.().catch(() => ({})));
|
|
107
|
+
consent = body.consent === true;
|
|
108
|
+
const [startS, endS] = [Number(body.startS), Number(body.endS)];
|
|
109
|
+
if (typeof body.recordingId !== 'string' || !(endS - startS >= MIN_SAMPLE_S - 1.5 && endS - startS <= MAX_SAMPLE_S)) {
|
|
110
|
+
return json({ error: `Pick ${MIN_SAMPLE_S} to ${MAX_SAMPLE_S} seconds of a recording.` }, 400);
|
|
111
|
+
}
|
|
112
|
+
if (!consent)
|
|
113
|
+
return json({ error: 'Confirm you have their permission to clone their voice.' }, 400);
|
|
114
|
+
if (!(await ownRecording(req, doc, body.recordingId)))
|
|
115
|
+
return json({ error: 'That recording is not one of theirs.' }, 403);
|
|
116
|
+
const clip = await api.clip(body.recordingId, startS, endS);
|
|
117
|
+
sample = { blob: await clip.blob(), name: 'sample.wav' };
|
|
118
|
+
}
|
|
119
|
+
if (!consent)
|
|
120
|
+
return json({ error: 'Confirm you have their permission to clone their voice.' }, 400);
|
|
121
|
+
const previous = doc.vocalstackVoice?.voiceId;
|
|
122
|
+
const voice = await api.createVoice(sample.blob, sample.name, { consent: true, name: nameOf(req, doc) }, `payload:${collection}:${id}:voice:${randomUUID()}`);
|
|
123
|
+
const data = await save(req, id, { ...fieldData(voice), consentAt: new Date().toISOString() });
|
|
124
|
+
// One voice per person: the old one goes once the new one exists.
|
|
125
|
+
if (previous && previous !== voice.id)
|
|
126
|
+
await api.deleteVoice(previous).catch(() => undefined);
|
|
127
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: data }, 201);
|
|
128
|
+
}
|
|
129
|
+
catch (err) {
|
|
130
|
+
return apiError(err);
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
method: 'delete',
|
|
136
|
+
path: '/:id/vocalstack/voice',
|
|
137
|
+
handler: async (req) => {
|
|
138
|
+
const found = await open(req, 'delete');
|
|
139
|
+
if (found instanceof Response)
|
|
140
|
+
return found;
|
|
141
|
+
const { api, doc, id } = found;
|
|
142
|
+
const voiceId = doc.vocalstackVoice?.voiceId;
|
|
143
|
+
try {
|
|
144
|
+
if (voiceId)
|
|
145
|
+
await api.deleteVoice(voiceId);
|
|
146
|
+
}
|
|
147
|
+
catch (err) {
|
|
148
|
+
if (!(err instanceof VocalStackAPIError && err.status === 404))
|
|
149
|
+
return apiError(err);
|
|
150
|
+
}
|
|
151
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: await save(req, id, EMPTY) });
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
method: 'get',
|
|
156
|
+
path: '/:id/vocalstack/voice/sources',
|
|
157
|
+
handler: async (req) => {
|
|
158
|
+
const found = await open(req, 'create');
|
|
159
|
+
if (found instanceof Response)
|
|
160
|
+
return found;
|
|
161
|
+
const sources = (await config.recordings?.({ doc: found.doc, req })) ?? [];
|
|
162
|
+
return json({
|
|
163
|
+
sources: sources.map(({ label, recordingId, sentences }) => ({
|
|
164
|
+
label,
|
|
165
|
+
recordingId,
|
|
166
|
+
sentences: (sentences ?? []).filter((s) => !s.draft).map(({ end, id, speaker, start, text }) => ({ end, id, speaker, start, text })),
|
|
167
|
+
})),
|
|
168
|
+
});
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
method: 'get',
|
|
173
|
+
path: '/:id/vocalstack/voice/clip',
|
|
174
|
+
handler: async (req) => {
|
|
175
|
+
const found = await open(req, 'create');
|
|
176
|
+
if (found instanceof Response)
|
|
177
|
+
return found;
|
|
178
|
+
const recording = req.searchParams.get('recording');
|
|
179
|
+
const [startS, endS] = [Number(req.searchParams.get('startS')), Number(req.searchParams.get('endS'))];
|
|
180
|
+
if (!recording || !(endS > startS) || endS - startS > MAX_SAMPLE_S)
|
|
181
|
+
return json({ error: `At most ${MAX_SAMPLE_S} seconds.` }, 400);
|
|
182
|
+
if (!(await ownRecording(req, found.doc, recording)))
|
|
183
|
+
return json({ error: 'That recording is not one of theirs.' }, 403);
|
|
184
|
+
try {
|
|
185
|
+
const res = await found.api.clip(recording, startS, endS);
|
|
186
|
+
return new Response(res.body, { headers: { 'cache-control': 'private, max-age=3600', 'content-type': 'audio/wav' } });
|
|
187
|
+
}
|
|
188
|
+
catch (err) {
|
|
189
|
+
return apiError(err);
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
},
|
|
193
|
+
{
|
|
194
|
+
method: 'get',
|
|
195
|
+
path: '/:id/vocalstack/voice/preview',
|
|
196
|
+
handler: async (req) => {
|
|
197
|
+
const found = await open(req, 'hear');
|
|
198
|
+
if (found instanceof Response)
|
|
199
|
+
return found;
|
|
200
|
+
const voiceId = found.doc.vocalstackVoice?.voiceId;
|
|
201
|
+
if (!voiceId)
|
|
202
|
+
return json({ error: 'There is no voice yet.' }, 404);
|
|
203
|
+
const format = req.searchParams.get('format') === 'caf' ? 'caf' : 'ogg';
|
|
204
|
+
try {
|
|
205
|
+
const res = await found.api.voicePreview(voiceId, req.searchParams.get('lang') ?? undefined, format);
|
|
206
|
+
// 202: being rendered; the client asks again.
|
|
207
|
+
if (res.status === 202)
|
|
208
|
+
return json({ pending: true }, 202);
|
|
209
|
+
if (!res.ok)
|
|
210
|
+
return json({ error: `VocalStack answered ${res.status}` }, res.status >= 500 ? 502 : res.status);
|
|
211
|
+
return new Response(res.body, { headers: { 'cache-control': 'private, max-age=3600', 'content-type': res.headers.get('content-type') ?? 'audio/ogg' } });
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
return apiError(err);
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
];
|
|
219
|
+
}
|
|
220
|
+
let languages;
|
|
221
|
+
/**
|
|
222
|
+
* Shared admin lookups (signed in, and `options.access` when set):
|
|
223
|
+
* GET /vocalstack/languages what can be translated and spoken
|
|
224
|
+
* GET /vocalstack/voices?lang=&recording= voices that can speak a language
|
|
225
|
+
*/
|
|
226
|
+
export function lookupEndpoints(options) {
|
|
227
|
+
const apiURL = options.apiURL ?? DEFAULT_API_URL;
|
|
228
|
+
const api = async (req) => {
|
|
229
|
+
if (!req.user)
|
|
230
|
+
return json({ error: 'Sign in first.' }, 401);
|
|
231
|
+
if (options.access && !(await options.access({ req })))
|
|
232
|
+
return json({ error: 'You may not use VocalStack here.' }, 403);
|
|
233
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
234
|
+
if (!apiKey)
|
|
235
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
236
|
+
return new VocalStackAPI(apiKey, apiURL);
|
|
237
|
+
};
|
|
238
|
+
return [
|
|
239
|
+
{
|
|
240
|
+
method: 'get',
|
|
241
|
+
path: '/vocalstack/languages',
|
|
242
|
+
handler: async (req) => {
|
|
243
|
+
const client = await api(req);
|
|
244
|
+
if (client instanceof Response)
|
|
245
|
+
return client;
|
|
246
|
+
try {
|
|
247
|
+
if (!languages || Date.now() - languages.at > 3600_000)
|
|
248
|
+
languages = { at: Date.now(), value: await client.languages() };
|
|
249
|
+
return json(languages.value);
|
|
250
|
+
}
|
|
251
|
+
catch (err) {
|
|
252
|
+
return apiError(err);
|
|
253
|
+
}
|
|
254
|
+
},
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
method: 'get',
|
|
258
|
+
path: '/vocalstack/voices',
|
|
259
|
+
handler: async (req) => {
|
|
260
|
+
const client = await api(req);
|
|
261
|
+
if (client instanceof Response)
|
|
262
|
+
return client;
|
|
263
|
+
const lang = req.searchParams.get('lang');
|
|
264
|
+
if (!lang)
|
|
265
|
+
return json({ error: 'Which language?' }, 400);
|
|
266
|
+
try {
|
|
267
|
+
return json(await client.availableVoices(lang, req.searchParams.get('recording') ?? undefined));
|
|
268
|
+
}
|
|
269
|
+
catch (err) {
|
|
270
|
+
return apiError(err);
|
|
271
|
+
}
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
];
|
|
275
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { ConnectionPanel } from '../components/ConnectionPanel.js';
|
|
2
|
+
export { SpeechField } from '../components/SpeechField.js';
|
|
3
|
+
export { TranscribeButton } from '../components/TranscribeButton.js';
|
|
4
|
+
export { TranscriptField } from '../components/TranscriptField.js';
|
|
5
|
+
export { VoiceField } from '../components/VoiceField.js';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
export { ConnectionPanel } from '../components/ConnectionPanel.js';
|
|
3
|
+
export { SpeechField } from '../components/SpeechField.js';
|
|
4
|
+
export { TranscribeButton } from '../components/TranscribeButton.js';
|
|
5
|
+
export { TranscriptField } from '../components/TranscriptField.js';
|
|
6
|
+
export { VoiceField } from '../components/VoiceField.js';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { CollectionSlug, PayloadRequest } from 'payload';
|
|
2
|
+
import type { UploadDoc, VocalStackPluginOptions } from './types.js';
|
|
3
|
+
/** The absolute address of an upload's file. */
|
|
4
|
+
export declare function resolveFileURL(req: PayloadRequest, collection: CollectionSlug, doc: UploadDoc, options: VocalStackPluginOptions): Promise<string | undefined>;
|
|
5
|
+
/**
|
|
6
|
+
* Whether VocalStack can fetch this address itself. The API refuses loopback,
|
|
7
|
+
* private and link-local hosts, so for those (local development, an intranet)
|
|
8
|
+
* the plugin sends the bytes instead.
|
|
9
|
+
*/
|
|
10
|
+
export declare function isPublicURL(url: string): boolean;
|
|
11
|
+
/** The file's bytes, for an upload VocalStack cannot reach by link. */
|
|
12
|
+
export declare function fetchFile(req: PayloadRequest, url: string): Promise<Blob>;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** The absolute address of an upload's file. */
|
|
2
|
+
export async function resolveFileURL(req, collection, doc, options) {
|
|
3
|
+
const custom = await options.fileURL?.({ collection, doc, req });
|
|
4
|
+
const url = custom ?? doc.url;
|
|
5
|
+
if (!url)
|
|
6
|
+
return undefined;
|
|
7
|
+
const base = req.payload.config.serverURL || req.origin;
|
|
8
|
+
return new URL(url, base).toString();
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Whether VocalStack can fetch this address itself. The API refuses loopback,
|
|
12
|
+
* private and link-local hosts, so for those (local development, an intranet)
|
|
13
|
+
* the plugin sends the bytes instead.
|
|
14
|
+
*/
|
|
15
|
+
export function isPublicURL(url) {
|
|
16
|
+
const { hostname, protocol } = new URL(url);
|
|
17
|
+
if (protocol !== 'https:' && protocol !== 'http:')
|
|
18
|
+
return false;
|
|
19
|
+
const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
20
|
+
if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') || host.endsWith('.internal'))
|
|
21
|
+
return false;
|
|
22
|
+
const v4 = host.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
|
|
23
|
+
if (v4) {
|
|
24
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
25
|
+
return !(a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127));
|
|
26
|
+
}
|
|
27
|
+
if (host.includes(':'))
|
|
28
|
+
return !(host === '::1' || host.startsWith('fc') || host.startsWith('fd') || host.startsWith('fe80'));
|
|
29
|
+
return true;
|
|
30
|
+
}
|
|
31
|
+
/** The file's bytes, for an upload VocalStack cannot reach by link. */
|
|
32
|
+
export async function fetchFile(req, url) {
|
|
33
|
+
// Same-origin files go through Payload's access control: pass the editor's cookie along.
|
|
34
|
+
const sameOrigin = new URL(url).origin === req.origin;
|
|
35
|
+
const cookie = req.headers.get('cookie');
|
|
36
|
+
const res = await fetch(url, { headers: sameOrigin && cookie ? { cookie } : {} });
|
|
37
|
+
if (!res.ok)
|
|
38
|
+
throw new Error(`Could not read the file (${res.status} from ${url})`);
|
|
39
|
+
return res.blob();
|
|
40
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Plugin } from 'payload';
|
|
2
|
+
import type { VocalStackPluginOptions, VoiceFieldData } from './types.js';
|
|
3
|
+
export type * from './types.js';
|
|
4
|
+
export { spokenSentences, timedTokens, transcriptText } from './text.js';
|
|
5
|
+
/** The voice to read translations in (`clone:<id>`), once a person's cloned voice is ready. */
|
|
6
|
+
export declare const clonedVoiceKey: (data?: null | VoiceFieldData) => string | undefined;
|
|
7
|
+
export declare const vocalstackPlugin: (options?: VocalStackPluginOptions) => Plugin;
|