@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.
- package/README.md +48 -4
- package/dist/api.d.ts +93 -0
- package/dist/api.js +111 -7
- package/dist/components/SpeechField.d.ts +7 -0
- package/dist/components/SpeechField.js +177 -0
- package/dist/components/TranscriptField.js +1 -1
- package/dist/components/VoiceField.d.ts +1 -0
- package/dist/components/VoiceField.js +226 -0
- package/dist/endpoints/speech.d.ts +12 -0
- package/dist/endpoints/speech.js +392 -0
- package/dist/endpoints/transcribe.d.ts +10 -2
- package/dist/endpoints/transcribe.js +14 -3
- package/dist/endpoints/voices.d.ts +20 -0
- package/dist/endpoints/voices.js +275 -0
- package/dist/exports/client.d.ts +2 -0
- package/dist/exports/client.js +2 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.js +76 -5
- package/dist/readings.d.ts +6 -0
- package/dist/readings.js +24 -0
- package/dist/text.d.ts +7 -0
- package/dist/text.js +26 -0
- package/dist/types.d.ts +96 -1
- package/package.json +1 -1
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
import type { CollectionSlug, Endpoint, PayloadRequest } from 'payload';
|
|
2
|
-
import type { AudioFieldConfig, StatusResponse, TranscriptSentence, VocalStackFieldData, VocalStackPluginOptions } from '../types.js';
|
|
2
|
+
import type { ArrayRow, AudioFieldConfig, StatusResponse, TranscriptSentence, VocalStackFieldData, VocalStackPluginOptions } from '../types.js';
|
|
3
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;
|
|
4
7
|
/** One transcribable thing: an upload document, or one row of an array field. */
|
|
5
8
|
export type Target = {
|
|
6
9
|
data: VocalStackFieldData;
|
|
10
|
+
doc: Record<string, unknown>;
|
|
7
11
|
fileName: string;
|
|
8
12
|
name: string;
|
|
9
|
-
|
|
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>;
|
|
10
17
|
url: () => Promise<string | undefined>;
|
|
11
18
|
};
|
|
12
19
|
export declare function locate(req: PayloadRequest, collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[], readAs: 'admin' | 'user'): Promise<Response | Target>;
|
|
@@ -23,3 +30,4 @@ export declare function checkJob(api: VocalStackAPI, target: Target, recordingId
|
|
|
23
30
|
* they act on the upload document itself; with `?field=<array>&row=<row id>` on one row.
|
|
24
31
|
*/
|
|
25
32
|
export declare function transcribeEndpoints(collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[]): Endpoint[];
|
|
33
|
+
export {};
|
|
@@ -19,7 +19,7 @@ function serially(key, run) {
|
|
|
19
19
|
/** Finished jobs being saved, so that every "done" signal for one job shares a single save. */
|
|
20
20
|
const finishing = new Map();
|
|
21
21
|
/** Whether the signed-in user may update this document, by the collection's own `access.update`. */
|
|
22
|
-
async function canUpdate(req, collection, id) {
|
|
22
|
+
export async function canUpdate(req, collection, id) {
|
|
23
23
|
if (!req.user)
|
|
24
24
|
return false;
|
|
25
25
|
const access = req.payload.collections[collection]?.config.access.update;
|
|
@@ -31,6 +31,10 @@ async function canUpdate(req, collection, id) {
|
|
|
31
31
|
const { totalDocs } = await req.payload.count({ collection, overrideAccess: true, req, where: { and: [{ id: { equals: id } }, result] } });
|
|
32
32
|
return totalDocs > 0;
|
|
33
33
|
}
|
|
34
|
+
const merge = (current, patch) => ({
|
|
35
|
+
...current,
|
|
36
|
+
...(typeof patch === 'function' ? patch(current ?? {}) : patch),
|
|
37
|
+
});
|
|
34
38
|
export async function locate(req, collection, options, rowFields, readAs) {
|
|
35
39
|
const id = req.routeParams?.id;
|
|
36
40
|
const find = (overrideAccess) => req.payload.findByID({ id, collection, depth: 0, overrideAccess, req, user: req.user }).catch(() => null);
|
|
@@ -46,10 +50,12 @@ export async function locate(req, collection, options, rowFields, readAs) {
|
|
|
46
50
|
return json({ error: 'Only audio files can be transcribed.' }, 400);
|
|
47
51
|
return {
|
|
48
52
|
data: upload.vocalstack ?? {},
|
|
53
|
+
doc,
|
|
49
54
|
fileName: upload.filename ?? 'audio',
|
|
50
55
|
name: upload.filename ?? `${collection} ${id}`,
|
|
51
56
|
save: (patch) => serially(`${collection}:${id}`, async () => {
|
|
52
|
-
const
|
|
57
|
+
const fresh = (typeof patch === 'function' ? (await find(true)) : null) ?? upload;
|
|
58
|
+
const vocalstack = merge(fresh.vocalstack, patch);
|
|
53
59
|
await req.payload.update({ id, collection, data: { vocalstack }, depth: 0, overrideAccess: true, req });
|
|
54
60
|
return vocalstack;
|
|
55
61
|
}),
|
|
@@ -66,8 +72,10 @@ export async function locate(req, collection, options, rowFields, readAs) {
|
|
|
66
72
|
const base = req.payload.config.serverURL || req.origin;
|
|
67
73
|
return {
|
|
68
74
|
data: row.vocalstack ?? {},
|
|
75
|
+
doc,
|
|
69
76
|
fileName: 'audio',
|
|
70
77
|
name: config.name?.({ doc, row }) ?? (typeof doc.title === 'string' && doc.title ? doc.title : `${collection} ${id}`),
|
|
78
|
+
row,
|
|
71
79
|
save: (patch) => serially(`${collection}:${id}`, async () => {
|
|
72
80
|
// Re-read so edits saved to other rows meanwhile are kept; arrays are written whole.
|
|
73
81
|
const fresh = (await find(true)) ?? doc;
|
|
@@ -75,7 +83,7 @@ export async function locate(req, collection, options, rowFields, readAs) {
|
|
|
75
83
|
const rows = (fresh[field] ?? []).map((r) => {
|
|
76
84
|
if (r.id !== rowId)
|
|
77
85
|
return r;
|
|
78
|
-
saved =
|
|
86
|
+
saved = merge(r.vocalstack, patch);
|
|
79
87
|
return { ...r, vocalstack: saved };
|
|
80
88
|
});
|
|
81
89
|
if (!saved)
|
|
@@ -149,9 +157,12 @@ async function saveTranscript(api, target, recordingId) {
|
|
|
149
157
|
error: null,
|
|
150
158
|
language: transcript.lang ?? transcript.sentences.find((s) => s.language)?.language ?? null,
|
|
151
159
|
sentences,
|
|
160
|
+
// A new recording: translations and readings of the old one no longer match it.
|
|
161
|
+
speech: null,
|
|
152
162
|
status: 'done',
|
|
153
163
|
transcribedAt: new Date().toISOString(),
|
|
154
164
|
transcript: transcriptText(sentences),
|
|
165
|
+
translations: null,
|
|
155
166
|
});
|
|
156
167
|
return { progress: 100, status: 'done', vocalstack };
|
|
157
168
|
}
|
|
@@ -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
|
+
}
|
package/dist/exports/client.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
export { ConnectionPanel } from '../components/ConnectionPanel.js';
|
|
2
|
+
export { SpeechField } from '../components/SpeechField.js';
|
|
2
3
|
export { TranscribeButton } from '../components/TranscribeButton.js';
|
|
3
4
|
export { TranscriptField } from '../components/TranscriptField.js';
|
|
5
|
+
export { VoiceField } from '../components/VoiceField.js';
|
package/dist/exports/client.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
export { ConnectionPanel } from '../components/ConnectionPanel.js';
|
|
3
|
+
export { SpeechField } from '../components/SpeechField.js';
|
|
3
4
|
export { TranscribeButton } from '../components/TranscribeButton.js';
|
|
4
5
|
export { TranscriptField } from '../components/TranscriptField.js';
|
|
6
|
+
export { VoiceField } from '../components/VoiceField.js';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { Plugin } from 'payload';
|
|
2
|
-
import type { VocalStackPluginOptions } from './types.js';
|
|
2
|
+
import type { VocalStackPluginOptions, VoiceFieldData } from './types.js';
|
|
3
3
|
export type * from './types.js';
|
|
4
|
-
export { timedTokens, transcriptText } from './text.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;
|
|
5
7
|
export declare const vocalstackPlugin: (options?: VocalStackPluginOptions) => Plugin;
|
package/dist/index.js
CHANGED
|
@@ -1,8 +1,13 @@
|
|
|
1
1
|
import { connectionEndpoints } from './endpoints/connection.js';
|
|
2
|
+
import { speechEndpoints } from './endpoints/speech.js';
|
|
2
3
|
import { streamEndpoint } from './endpoints/stream.js';
|
|
3
4
|
import { transcribeEndpoints } from './endpoints/transcribe.js';
|
|
5
|
+
import { lookupEndpoints, voiceEndpoints } from './endpoints/voices.js';
|
|
6
|
+
import { readingsCollection, readingsSlug } from './readings.js';
|
|
4
7
|
import { settingsGlobal } from './settings.js';
|
|
5
|
-
export { timedTokens, transcriptText } from './text.js';
|
|
8
|
+
export { spokenSentences, timedTokens, transcriptText } from './text.js';
|
|
9
|
+
/** The voice to read translations in (`clone:<id>`), once a person's cloned voice is ready. */
|
|
10
|
+
export const clonedVoiceKey = (data) => data?.state === 'ready' && data.voiceId ? `clone:${data.voiceId}` : undefined;
|
|
6
11
|
const isAudioDoc = (data) => typeof data?.mimeType === 'string' && data.mimeType.startsWith('audio/');
|
|
7
12
|
/** An upload collection that can hold audio: `audio/*`, a wildcard, or no restriction at all. */
|
|
8
13
|
function acceptsAudio(collection) {
|
|
@@ -59,6 +64,51 @@ function transcriptionFields(enabled, options, target) {
|
|
|
59
64
|
{ name: 'transcribedAt', type: 'date', ...hidden },
|
|
60
65
|
// [{ start, end, speaker, text }] in seconds, for captions or a synced player.
|
|
61
66
|
{ name: 'sentences', type: 'json', ...hidden },
|
|
67
|
+
// { [lang]: { translatedAt, sentences } }: the sentences above, translated.
|
|
68
|
+
{ name: 'translations', type: 'json', ...hidden },
|
|
69
|
+
// { [lang]: { voice, state, …, sentences } }: translations read aloud, in the reading's timing.
|
|
70
|
+
{ name: 'speech', type: 'json', ...hidden },
|
|
71
|
+
...(enabled
|
|
72
|
+
? [
|
|
73
|
+
{
|
|
74
|
+
name: 'vocalstackSpeech',
|
|
75
|
+
type: 'ui',
|
|
76
|
+
admin: {
|
|
77
|
+
components: { Field: { clientProps: { field: target.field }, path: '@vocalstack/payload/client#SpeechField' } },
|
|
78
|
+
condition: (_, siblingData) => siblingData?.status === 'done',
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
]
|
|
82
|
+
: []),
|
|
83
|
+
],
|
|
84
|
+
},
|
|
85
|
+
];
|
|
86
|
+
}
|
|
87
|
+
/** A person's cloned voice: the panel, and what VocalStack says about the voice. */
|
|
88
|
+
function voiceFields(enabled) {
|
|
89
|
+
return [
|
|
90
|
+
...(enabled
|
|
91
|
+
? [
|
|
92
|
+
{
|
|
93
|
+
name: 'vocalstackVoicePanel',
|
|
94
|
+
type: 'ui',
|
|
95
|
+
admin: { components: { Field: '@vocalstack/payload/client#VoiceField' }, position: 'sidebar' },
|
|
96
|
+
},
|
|
97
|
+
]
|
|
98
|
+
: []),
|
|
99
|
+
{
|
|
100
|
+
name: 'vocalstackVoice',
|
|
101
|
+
type: 'group',
|
|
102
|
+
label: 'Voice',
|
|
103
|
+
admin: { hidden: true },
|
|
104
|
+
fields: [
|
|
105
|
+
{ name: 'voiceId', type: 'text', ...hidden },
|
|
106
|
+
{ name: 'state', type: 'select', defaultValue: 'none', options: ['none', 'training', 'ready', 'failed'], ...hidden },
|
|
107
|
+
{ name: 'progress', type: 'number', ...hidden },
|
|
108
|
+
{ name: 'error', type: 'text', ...hidden },
|
|
109
|
+
{ name: 'sampleS', type: 'number', ...hidden },
|
|
110
|
+
{ name: 'consentAt', type: 'date', ...hidden },
|
|
111
|
+
{ name: 'createdAt', type: 'date', ...hidden },
|
|
62
112
|
],
|
|
63
113
|
},
|
|
64
114
|
];
|
|
@@ -84,11 +134,25 @@ function addToArray(fields, name, extra) {
|
|
|
84
134
|
export const vocalstackPlugin = (options = {}) => (config) => {
|
|
85
135
|
const enabled = options.enabled !== false;
|
|
86
136
|
const collections = config.collections ?? [];
|
|
87
|
-
const
|
|
137
|
+
const readings = readingsSlug(options);
|
|
138
|
+
const uploads = new Set(options.collections ?? collections.filter((c) => c.slug !== readings && acceptsAudio(c)).map((c) => c.slug));
|
|
88
139
|
const audioFields = options.audioFields ?? [];
|
|
140
|
+
const voices = options.voices ?? [];
|
|
141
|
+
for (const v of voices) {
|
|
142
|
+
if (!collections.some((c) => c.slug === v.collection))
|
|
143
|
+
throw new Error(`vocalstackPlugin: no collection "${v.collection}" for voices`);
|
|
144
|
+
}
|
|
89
145
|
return {
|
|
90
146
|
...config,
|
|
91
|
-
collections: collections.map((
|
|
147
|
+
collections: [...collections, ...(readings && !collections.some((c) => c.slug === readings) ? [(options.readings && options.readings.overrides ? options.readings.overrides : (c) => c)(readingsCollection(readings))] : [])].map((original) => {
|
|
148
|
+
const voice = voices.find((v) => v.collection === original.slug);
|
|
149
|
+
const collection = voice
|
|
150
|
+
? {
|
|
151
|
+
...original,
|
|
152
|
+
endpoints: enabled ? [...(original.endpoints || []), ...voiceEndpoints(voice, options)] : original.endpoints,
|
|
153
|
+
fields: [...original.fields, ...voiceFields(enabled)],
|
|
154
|
+
}
|
|
155
|
+
: original;
|
|
92
156
|
const rowFields = audioFields.filter((f) => f.collection === collection.slug);
|
|
93
157
|
const isUpload = uploads.has(collection.slug);
|
|
94
158
|
if (!isUpload && !rowFields.length)
|
|
@@ -103,11 +167,18 @@ export const vocalstackPlugin = (options = {}) => (config) => {
|
|
|
103
167
|
}
|
|
104
168
|
return {
|
|
105
169
|
...collection,
|
|
106
|
-
endpoints: enabled
|
|
170
|
+
endpoints: enabled
|
|
171
|
+
? [
|
|
172
|
+
...(collection.endpoints || []),
|
|
173
|
+
...transcribeEndpoints(collection.slug, options, rowFields),
|
|
174
|
+
streamEndpoint(collection.slug, options, rowFields),
|
|
175
|
+
...speechEndpoints(collection.slug, options, rowFields),
|
|
176
|
+
]
|
|
177
|
+
: collection.endpoints,
|
|
107
178
|
fields,
|
|
108
179
|
};
|
|
109
180
|
}),
|
|
110
|
-
endpoints: enabled ? [...(config.endpoints ?? []), ...connectionEndpoints(options)] : config.endpoints,
|
|
181
|
+
endpoints: enabled ? [...(config.endpoints ?? []), ...connectionEndpoints(options), ...lookupEndpoints(options)] : config.endpoints,
|
|
111
182
|
globals: [...(config.globals ?? []), settingsGlobal(options)],
|
|
112
183
|
};
|
|
113
184
|
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CollectionConfig, CollectionSlug } from 'payload';
|
|
2
|
+
import type { VocalStackPluginOptions } from './types.js';
|
|
3
|
+
/** The upload collection finished readings are saved in, or none. */
|
|
4
|
+
export declare const readingsSlug: (options: VocalStackPluginOptions) => CollectionSlug | undefined;
|
|
5
|
+
/** Spoken readings, kept as MP3 uploads so they are served from the site's own storage. */
|
|
6
|
+
export declare const readingsCollection: (slug: CollectionSlug) => CollectionConfig;
|
package/dist/readings.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** The upload collection finished readings are saved in, or none. */
|
|
2
|
+
export const readingsSlug = (options) => options.readings === false ? undefined : (options.readings?.slug ?? 'vocalstack-readings');
|
|
3
|
+
/** Spoken readings, kept as MP3 uploads so they are served from the site's own storage. */
|
|
4
|
+
export const readingsCollection = (slug) => ({
|
|
5
|
+
slug,
|
|
6
|
+
labels: { plural: 'Readings', singular: 'Reading' },
|
|
7
|
+
admin: {
|
|
8
|
+
description: 'Translations read aloud, saved from VocalStack once they are ready. Made and removed from the transcript.',
|
|
9
|
+
group: 'VocalStack',
|
|
10
|
+
useAsTitle: 'filename',
|
|
11
|
+
},
|
|
12
|
+
access: {
|
|
13
|
+
create: ({ req }) => Boolean(req.user),
|
|
14
|
+
delete: ({ req }) => Boolean(req.user),
|
|
15
|
+
read: () => true,
|
|
16
|
+
update: ({ req }) => Boolean(req.user),
|
|
17
|
+
},
|
|
18
|
+
upload: { mimeTypes: ['audio/mpeg'] },
|
|
19
|
+
fields: [
|
|
20
|
+
{ name: 'lang', type: 'text', admin: { readOnly: true } },
|
|
21
|
+
{ name: 'recordingId', type: 'text', admin: { readOnly: true } },
|
|
22
|
+
{ name: 'voice', type: 'text', admin: { readOnly: true } },
|
|
23
|
+
],
|
|
24
|
+
});
|
package/dist/text.d.ts
CHANGED
|
@@ -20,3 +20,10 @@ export declare function attachWords<T extends TranscriptSentence>(sentences: T[]
|
|
|
20
20
|
* differ, the times are spread evenly across the sentence.
|
|
21
21
|
*/
|
|
22
22
|
export declare function timedTokens(s: TranscriptSentence): TranscriptWord[];
|
|
23
|
+
/**
|
|
24
|
+
* Translated sentences in the timing of their spoken track. The track keeps each
|
|
25
|
+
* sentence where it was said, unless the one before still runs: then it follows it
|
|
26
|
+
* after a short pause. Each sentence's words come from the clip's word times, paired
|
|
27
|
+
* with the translated text; when they do not pair up, they are spread evenly.
|
|
28
|
+
*/
|
|
29
|
+
export declare function spokenSentences(translated: TranscriptSentence[], clipDur: Record<string, number>, wordTimes?: Record<string, [number, number][]>): TranscriptSentence[];
|
package/dist/text.js
CHANGED
|
@@ -50,3 +50,29 @@ export function timedTokens(s) {
|
|
|
50
50
|
const span = (s.end - s.start) / tokens.length;
|
|
51
51
|
return tokens.map((t, i) => [round(s.start + i * span), round(s.start + (i + 1) * span), t]);
|
|
52
52
|
}
|
|
53
|
+
/** The pause VocalStack leaves between two spoken sentences, at least. */
|
|
54
|
+
const SPOKEN_GAP_S = 0.15;
|
|
55
|
+
/**
|
|
56
|
+
* Translated sentences in the timing of their spoken track. The track keeps each
|
|
57
|
+
* sentence where it was said, unless the one before still runs: then it follows it
|
|
58
|
+
* after a short pause. Each sentence's words come from the clip's word times, paired
|
|
59
|
+
* with the translated text; when they do not pair up, they are spread evenly.
|
|
60
|
+
*/
|
|
61
|
+
export function spokenSentences(translated, clipDur, wordTimes = {}) {
|
|
62
|
+
let cursor = 0;
|
|
63
|
+
const out = [];
|
|
64
|
+
for (const s of [...translated].sort((a, b) => (a.id ?? 0) - (b.id ?? 0))) {
|
|
65
|
+
const dur = s.id === undefined ? undefined : clipDur[String(s.id)];
|
|
66
|
+
if (!dur)
|
|
67
|
+
continue;
|
|
68
|
+
const at = Math.max(s.start, cursor);
|
|
69
|
+
cursor = at + dur + SPOKEN_GAP_S;
|
|
70
|
+
const tokens = s.text.trim().split(/\s+/).filter(Boolean);
|
|
71
|
+
const times = wordTimes[String(s.id)] ?? [];
|
|
72
|
+
const words = times.length === tokens.length
|
|
73
|
+
? tokens.map((t, i) => [round(at + times[i][0]), round(at + times[i][1]), t])
|
|
74
|
+
: tokens.map((t, i) => [round(at + (i * dur) / tokens.length), round(at + ((i + 1) * dur) / tokens.length), t]);
|
|
75
|
+
out.push({ ...s, end: round(at + dur), start: round(at), words });
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|