@vocalstack/payload 0.1.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -4
- package/dist/api.d.ts +114 -5
- package/dist/api.js +135 -31
- package/dist/components/SpeechField.d.ts +7 -0
- package/dist/components/SpeechField.js +212 -0
- package/dist/components/TranscriptField.js +1 -1
- package/dist/components/VoiceField.d.ts +1 -0
- package/dist/components/VoiceField.js +199 -0
- package/dist/components/VoiceSamples.d.ts +21 -0
- package/dist/components/VoiceSamples.js +341 -0
- package/dist/endpoints/speech.d.ts +27 -0
- package/dist/endpoints/speech.js +790 -0
- package/dist/endpoints/transcribe.d.ts +10 -2
- package/dist/endpoints/transcribe.js +14 -3
- package/dist/endpoints/voices.d.ts +25 -0
- package/dist/endpoints/voices.js +411 -0
- package/dist/exports/client.d.ts +2 -0
- package/dist/exports/client.js +2 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +93 -5
- package/dist/languages.d.ts +17 -0
- package/dist/languages.js +64 -0
- package/dist/languagesSnapshot.d.ts +2 -0
- package/dist/languagesSnapshot.js +112 -0
- 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 +159 -1
- package/package.json +6 -2
|
@@ -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,25 @@
|
|
|
1
|
+
import type { Endpoint } from 'payload';
|
|
2
|
+
import type { VoiceCollectionConfig, VocalStackPluginOptions } from '../types.js';
|
|
3
|
+
export declare const PICK_MIN_S = 5;
|
|
4
|
+
export declare const PICK_MAX_S = 60;
|
|
5
|
+
/**
|
|
6
|
+
* A person's cloned voice, kept in the `vocalstackVoice` group of their document:
|
|
7
|
+
* GET /:id/vocalstack/voice where its training stands
|
|
8
|
+
* POST /:id/vocalstack/voice clone it: JSON { recordingId, startS, endS, consent },
|
|
9
|
+
* or multipart with a `file` sample and `_payload` { consent }
|
|
10
|
+
* DELETE /:id/vocalstack/voice delete it, in VocalStack too
|
|
11
|
+
* GET /:id/vocalstack/voice/sources recordings to take the sample from
|
|
12
|
+
* GET /:id/vocalstack/voice/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
|
|
13
|
+
* GET /:id/vocalstack/voice/preview the voice speaking (?lang=&format=ogg|caf)
|
|
14
|
+
* POST /:id/vocalstack/voice/trial a trial voice from picked sentences { recordingId, speaker, spans, replace? }
|
|
15
|
+
* GET /:id/vocalstack/voice/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
|
|
16
|
+
* POST /:id/vocalstack/voice/trial/keep { voice, name, consent } keep it as their voice; DELETE …/trial?voice= drop it
|
|
17
|
+
* A sample is only ever taken from the recordings `config.recordings` offers for that document.
|
|
18
|
+
*/
|
|
19
|
+
export declare function voiceEndpoints(config: VoiceCollectionConfig, options: VocalStackPluginOptions): Endpoint[];
|
|
20
|
+
/**
|
|
21
|
+
* Shared lookups:
|
|
22
|
+
* GET /vocalstack/languages what can be translated and spoken (public with `listeners` on)
|
|
23
|
+
* GET /vocalstack/voices?lang=&recording= voices that can speak a language (signed in, and `options.access`)
|
|
24
|
+
*/
|
|
25
|
+
export declare function lookupEndpoints(options: VocalStackPluginOptions): Endpoint[];
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { addDataAndFileToRequest } from 'payload';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
4
|
+
import { forListeners, languageList, listenerOptions } from '../languages.js';
|
|
5
|
+
import { resolveAPIKey } from '../settings.js';
|
|
6
|
+
import { apiError, canUpdate } from './transcribe.js';
|
|
7
|
+
const json = (body, status = 200, headers) => Response.json(body, { headers, status });
|
|
8
|
+
// VocalStack clones from 30 s to 120 s of speech (a clip is at most 120 s).
|
|
9
|
+
const MIN_SAMPLE_S = 30;
|
|
10
|
+
const MAX_SAMPLE_S = 120;
|
|
11
|
+
const STATES = new Set(['failed', 'ready', 'training']);
|
|
12
|
+
/** VocalStack's voice as the document keeps it. */
|
|
13
|
+
const fieldData = (v) => ({
|
|
14
|
+
createdAt: v.createdAt,
|
|
15
|
+
error: v.error ?? null,
|
|
16
|
+
progress: v.progress,
|
|
17
|
+
sampleS: v.sampleS,
|
|
18
|
+
state: STATES.has(v.state) ? v.state : 'training',
|
|
19
|
+
voiceId: v.id,
|
|
20
|
+
});
|
|
21
|
+
/** A trial voice, as the panel follows it. */
|
|
22
|
+
const trialOf = (v) => ({ error: v.error ?? null, id: v.id, progress: v.progress, state: v.state });
|
|
23
|
+
/** Delete a trial voice; a kept one is never deleted this way. */
|
|
24
|
+
async function dropTrial(api, id) {
|
|
25
|
+
if (!id)
|
|
26
|
+
return;
|
|
27
|
+
const voice = await api.voice(id).catch(() => null);
|
|
28
|
+
if (voice?.draft)
|
|
29
|
+
await api.deleteVoice(id).catch(() => undefined);
|
|
30
|
+
}
|
|
31
|
+
// Picked from a recording, as in the VocalStack dashboard: at least 5 s makes a voice, at most 60 s.
|
|
32
|
+
export const PICK_MIN_S = 5;
|
|
33
|
+
export const PICK_MAX_S = 60;
|
|
34
|
+
const EMPTY = { consentAt: null, createdAt: null, error: null, progress: null, sampleS: null, state: 'none', voiceId: null };
|
|
35
|
+
/**
|
|
36
|
+
* A person's cloned voice, kept in the `vocalstackVoice` group of their document:
|
|
37
|
+
* GET /:id/vocalstack/voice where its training stands
|
|
38
|
+
* POST /:id/vocalstack/voice clone it: JSON { recordingId, startS, endS, consent },
|
|
39
|
+
* or multipart with a `file` sample and `_payload` { consent }
|
|
40
|
+
* DELETE /:id/vocalstack/voice delete it, in VocalStack too
|
|
41
|
+
* GET /:id/vocalstack/voice/sources recordings to take the sample from
|
|
42
|
+
* GET /:id/vocalstack/voice/clip a stretch of one of them, to hear before cloning (?recording=&startS=&endS=)
|
|
43
|
+
* GET /:id/vocalstack/voice/preview the voice speaking (?lang=&format=ogg|caf)
|
|
44
|
+
* POST /:id/vocalstack/voice/trial a trial voice from picked sentences { recordingId, speaker, spans, replace? }
|
|
45
|
+
* GET /:id/vocalstack/voice/trial ?voice= where it stands; …/trial/preview?voice=&lang=&format= hear it
|
|
46
|
+
* POST /:id/vocalstack/voice/trial/keep { voice, name, consent } keep it as their voice; DELETE …/trial?voice= drop it
|
|
47
|
+
* A sample is only ever taken from the recordings `config.recordings` offers for that document.
|
|
48
|
+
*/
|
|
49
|
+
export function voiceEndpoints(config, options) {
|
|
50
|
+
const { collection } = config;
|
|
51
|
+
const apiURL = options.apiURL ?? DEFAULT_API_URL;
|
|
52
|
+
const open = async (req, verb) => {
|
|
53
|
+
const id = req.routeParams?.id;
|
|
54
|
+
if (!(await canUpdate(req, collection, id)))
|
|
55
|
+
return json({ error: `You may not ${verb} this voice.` }, 403);
|
|
56
|
+
if (options.access && !(await options.access({ req })))
|
|
57
|
+
return json({ error: `You may not ${verb} this voice.` }, 403);
|
|
58
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
59
|
+
if (!apiKey)
|
|
60
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
61
|
+
const doc = (await req.payload.findByID({ id, collection, depth: 0, overrideAccess: true, req }).catch(() => null));
|
|
62
|
+
if (!doc)
|
|
63
|
+
return json({ error: 'Not found.' }, 404);
|
|
64
|
+
return { api: new VocalStackAPI(apiKey, apiURL), doc, id };
|
|
65
|
+
};
|
|
66
|
+
/** Whether the recording is one the host offers for this person (`config.recordings`). */
|
|
67
|
+
const ownRecording = async (req, doc, recordingId) => ((await config.recordings?.({ doc, req })) ?? []).some((s) => s.recordingId === recordingId);
|
|
68
|
+
const save = async (req, id, data) => {
|
|
69
|
+
await req.payload.update({ id, collection, data: { vocalstackVoice: data }, depth: 0, overrideAccess: true, req });
|
|
70
|
+
return data;
|
|
71
|
+
};
|
|
72
|
+
const nameOf = (req, doc) => {
|
|
73
|
+
const title = req.payload.collections[collection]?.config.admin?.useAsTitle;
|
|
74
|
+
const name = config.name?.({ doc }) ?? (title && typeof doc[title] === 'string' ? doc[title] : typeof doc.name === 'string' ? doc.name : `${collection} ${doc.id}`);
|
|
75
|
+
// VocalStack takes 1–60 characters.
|
|
76
|
+
return name.trim().slice(0, 60) || `${collection} ${doc.id}`;
|
|
77
|
+
};
|
|
78
|
+
return [
|
|
79
|
+
{
|
|
80
|
+
method: 'get',
|
|
81
|
+
path: '/:id/vocalstack/voice',
|
|
82
|
+
handler: async (req) => {
|
|
83
|
+
const found = await open(req, 'see');
|
|
84
|
+
if (found instanceof Response)
|
|
85
|
+
return found;
|
|
86
|
+
const { api, doc, id } = found;
|
|
87
|
+
const current = (doc.vocalstackVoice ?? {});
|
|
88
|
+
if (!current.voiceId || current.state === 'ready')
|
|
89
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: current });
|
|
90
|
+
try {
|
|
91
|
+
const next = { ...current, ...fieldData(await api.voice(current.voiceId)) };
|
|
92
|
+
const changed = next.state !== current.state || next.progress !== current.progress || next.error !== current.error;
|
|
93
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: changed ? await save(req, id, next) : current });
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
// Deleted in the VocalStack dashboard: there is no voice any more.
|
|
97
|
+
if (err instanceof VocalStackAPIError && err.status === 404)
|
|
98
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: await save(req, id, EMPTY) });
|
|
99
|
+
return apiError(err);
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
method: 'post',
|
|
105
|
+
path: '/:id/vocalstack/voice',
|
|
106
|
+
handler: async (req) => {
|
|
107
|
+
const found = await open(req, 'create');
|
|
108
|
+
if (found instanceof Response)
|
|
109
|
+
return found;
|
|
110
|
+
const { api, doc, id } = found;
|
|
111
|
+
let sample;
|
|
112
|
+
let consent;
|
|
113
|
+
const multipart = req.headers.get('content-type')?.includes('multipart/');
|
|
114
|
+
try {
|
|
115
|
+
if (multipart) {
|
|
116
|
+
await addDataAndFileToRequest(req);
|
|
117
|
+
consent = req.data?.consent === true;
|
|
118
|
+
if (!req.file)
|
|
119
|
+
return json({ error: 'Add an audio sample.' }, 400);
|
|
120
|
+
sample = { blob: new Blob([new Uint8Array(req.file.data)], { type: req.file.mimetype }), name: req.file.name };
|
|
121
|
+
}
|
|
122
|
+
else {
|
|
123
|
+
const body = (await req.json?.().catch(() => ({})));
|
|
124
|
+
consent = body.consent === true;
|
|
125
|
+
const [startS, endS] = [Number(body.startS), Number(body.endS)];
|
|
126
|
+
if (typeof body.recordingId !== 'string' || !(endS - startS >= MIN_SAMPLE_S - 1.5 && endS - startS <= MAX_SAMPLE_S)) {
|
|
127
|
+
return json({ error: `Pick ${MIN_SAMPLE_S} to ${MAX_SAMPLE_S} seconds of a recording.` }, 400);
|
|
128
|
+
}
|
|
129
|
+
if (!consent)
|
|
130
|
+
return json({ error: 'Confirm you have their permission to clone their voice.' }, 400);
|
|
131
|
+
if (!(await ownRecording(req, doc, body.recordingId)))
|
|
132
|
+
return json({ error: 'That recording is not one of theirs.' }, 403);
|
|
133
|
+
const clip = await api.clip(body.recordingId, startS, endS);
|
|
134
|
+
sample = { blob: await clip.blob(), name: 'sample.wav' };
|
|
135
|
+
}
|
|
136
|
+
if (!consent)
|
|
137
|
+
return json({ error: 'Confirm you have their permission to clone their voice.' }, 400);
|
|
138
|
+
const previous = doc.vocalstackVoice?.voiceId;
|
|
139
|
+
const voice = await api.createVoice(sample.blob, sample.name, { consent: true, name: nameOf(req, doc) }, `payload:${collection}:${id}:voice:${randomUUID()}`);
|
|
140
|
+
const data = await save(req, id, { ...fieldData(voice), consentAt: new Date().toISOString() });
|
|
141
|
+
// One voice per person: the old one goes once the new one exists.
|
|
142
|
+
if (previous && previous !== voice.id)
|
|
143
|
+
await api.deleteVoice(previous).catch(() => undefined);
|
|
144
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: data }, 201);
|
|
145
|
+
}
|
|
146
|
+
catch (err) {
|
|
147
|
+
return apiError(err);
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
method: 'delete',
|
|
153
|
+
path: '/:id/vocalstack/voice',
|
|
154
|
+
handler: async (req) => {
|
|
155
|
+
const found = await open(req, 'delete');
|
|
156
|
+
if (found instanceof Response)
|
|
157
|
+
return found;
|
|
158
|
+
const { api, doc, id } = found;
|
|
159
|
+
const voiceId = doc.vocalstackVoice?.voiceId;
|
|
160
|
+
try {
|
|
161
|
+
if (voiceId)
|
|
162
|
+
await api.deleteVoice(voiceId);
|
|
163
|
+
}
|
|
164
|
+
catch (err) {
|
|
165
|
+
if (!(err instanceof VocalStackAPIError && err.status === 404))
|
|
166
|
+
return apiError(err);
|
|
167
|
+
}
|
|
168
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: await save(req, id, EMPTY) });
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
method: 'get',
|
|
173
|
+
path: '/:id/vocalstack/voice/sources',
|
|
174
|
+
handler: async (req) => {
|
|
175
|
+
const found = await open(req, 'create');
|
|
176
|
+
if (found instanceof Response)
|
|
177
|
+
return found;
|
|
178
|
+
const sources = (await config.recordings?.({ doc: found.doc, req })) ?? [];
|
|
179
|
+
return json({
|
|
180
|
+
sources: sources.map(({ label, recordingId, sentences }) => ({
|
|
181
|
+
label,
|
|
182
|
+
recordingId,
|
|
183
|
+
sentences: (sentences ?? []).filter((s) => !s.draft).map(({ end, id, speaker, start, text }) => ({ end, id, speaker, start, text })),
|
|
184
|
+
})),
|
|
185
|
+
});
|
|
186
|
+
},
|
|
187
|
+
},
|
|
188
|
+
{
|
|
189
|
+
method: 'get',
|
|
190
|
+
path: '/:id/vocalstack/voice/clip',
|
|
191
|
+
handler: async (req) => {
|
|
192
|
+
const found = await open(req, 'create');
|
|
193
|
+
if (found instanceof Response)
|
|
194
|
+
return found;
|
|
195
|
+
const recording = req.searchParams.get('recording');
|
|
196
|
+
const [startS, endS] = [Number(req.searchParams.get('startS')), Number(req.searchParams.get('endS'))];
|
|
197
|
+
if (!recording || !(endS > startS) || endS - startS > MAX_SAMPLE_S)
|
|
198
|
+
return json({ error: `At most ${MAX_SAMPLE_S} seconds.` }, 400);
|
|
199
|
+
if (!(await ownRecording(req, found.doc, recording)))
|
|
200
|
+
return json({ error: 'That recording is not one of theirs.' }, 403);
|
|
201
|
+
try {
|
|
202
|
+
const res = await found.api.clip(recording, startS, endS);
|
|
203
|
+
return new Response(res.body, { headers: { 'cache-control': 'private, max-age=3600', 'content-type': 'audio/wav' } });
|
|
204
|
+
}
|
|
205
|
+
catch (err) {
|
|
206
|
+
return apiError(err);
|
|
207
|
+
}
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
// A trial voice from sentences of one of their recordings, to hear before keeping it.
|
|
212
|
+
method: 'post',
|
|
213
|
+
path: '/:id/vocalstack/voice/trial',
|
|
214
|
+
handler: async (req) => {
|
|
215
|
+
const found = await open(req, 'create');
|
|
216
|
+
if (found instanceof Response)
|
|
217
|
+
return found;
|
|
218
|
+
const { api, doc, id } = found;
|
|
219
|
+
const body = (await req.json?.().catch(() => ({})));
|
|
220
|
+
const spans = (Array.isArray(body.spans) ? body.spans : [])
|
|
221
|
+
.map((s) => ({ end: Number(s?.end), start: Number(s?.start) }))
|
|
222
|
+
.filter((s) => Number.isFinite(s.start) && s.end > s.start);
|
|
223
|
+
const total = spans.reduce((t, s) => t + (s.end - s.start), 0);
|
|
224
|
+
if (typeof body.recordingId !== 'string' || !Number.isInteger(body.speaker) || total < PICK_MIN_S - 0.05 || total > PICK_MAX_S + 0.5) {
|
|
225
|
+
return json({ error: `Pick ${PICK_MIN_S} to ${PICK_MAX_S} seconds of their speech.` }, 400);
|
|
226
|
+
}
|
|
227
|
+
if (!(await ownRecording(req, doc, body.recordingId)))
|
|
228
|
+
return json({ error: 'That recording is not one of theirs.' }, 403);
|
|
229
|
+
try {
|
|
230
|
+
const voice = await api.voiceFromSpeaker({ draft: true, name: nameOf(req, doc), recordingId: body.recordingId, spans, speaker: body.speaker }, `payload:${collection}:${id}:trial:${randomUUID()}`);
|
|
231
|
+
// The trial it replaces (other samples picked) is not wanted any more.
|
|
232
|
+
if (typeof body.replace === 'string' && body.replace !== voice.id)
|
|
233
|
+
await dropTrial(api, body.replace);
|
|
234
|
+
return json({ voice: trialOf(voice) }, 201);
|
|
235
|
+
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
return apiError(err);
|
|
238
|
+
}
|
|
239
|
+
},
|
|
240
|
+
},
|
|
241
|
+
{
|
|
242
|
+
method: 'get',
|
|
243
|
+
path: '/:id/vocalstack/voice/trial',
|
|
244
|
+
handler: async (req) => {
|
|
245
|
+
const found = await open(req, 'create');
|
|
246
|
+
if (found instanceof Response)
|
|
247
|
+
return found;
|
|
248
|
+
try {
|
|
249
|
+
const voice = await found.api.voice(req.searchParams.get('voice') ?? '');
|
|
250
|
+
if (!voice.draft)
|
|
251
|
+
return json({ error: 'Not a trial voice.' }, 404);
|
|
252
|
+
return json({ voice: trialOf(voice) });
|
|
253
|
+
}
|
|
254
|
+
catch (err) {
|
|
255
|
+
return apiError(err);
|
|
256
|
+
}
|
|
257
|
+
},
|
|
258
|
+
},
|
|
259
|
+
{
|
|
260
|
+
method: 'get',
|
|
261
|
+
path: '/:id/vocalstack/voice/trial/preview',
|
|
262
|
+
handler: async (req) => {
|
|
263
|
+
const found = await open(req, 'hear');
|
|
264
|
+
if (found instanceof Response)
|
|
265
|
+
return found;
|
|
266
|
+
const format = req.searchParams.get('format') === 'caf' ? 'caf' : 'ogg';
|
|
267
|
+
try {
|
|
268
|
+
const voice = await found.api.voice(req.searchParams.get('voice') ?? '');
|
|
269
|
+
if (!voice.draft)
|
|
270
|
+
return json({ error: 'Not a trial voice.' }, 404);
|
|
271
|
+
const res = await found.api.voicePreview(voice.id, req.searchParams.get('lang') ?? undefined, format);
|
|
272
|
+
if (res.status === 202)
|
|
273
|
+
return json({ pending: true }, 202);
|
|
274
|
+
if (!res.ok)
|
|
275
|
+
return json({ error: `VocalStack answered ${res.status}` }, res.status >= 500 ? 502 : res.status);
|
|
276
|
+
return new Response(res.body, { headers: { 'cache-control': 'private, max-age=600', 'content-type': res.headers.get('content-type') ?? 'audio/ogg' } });
|
|
277
|
+
}
|
|
278
|
+
catch (err) {
|
|
279
|
+
return apiError(err);
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
// Keep the trial as their voice (with their permission); the voice they had before goes.
|
|
285
|
+
method: 'post',
|
|
286
|
+
path: '/:id/vocalstack/voice/trial/keep',
|
|
287
|
+
handler: async (req) => {
|
|
288
|
+
const found = await open(req, 'create');
|
|
289
|
+
if (found instanceof Response)
|
|
290
|
+
return found;
|
|
291
|
+
const { api, doc, id } = found;
|
|
292
|
+
const body = (await req.json?.().catch(() => ({})));
|
|
293
|
+
if (body.consent !== true)
|
|
294
|
+
return json({ error: 'Confirm you have their permission to clone their voice.' }, 400);
|
|
295
|
+
if (typeof body.voice !== 'string')
|
|
296
|
+
return json({ error: 'Which voice?' }, 400);
|
|
297
|
+
const name = (typeof body.name === 'string' && body.name.trim() ? body.name.trim() : nameOf(req, doc)).slice(0, 60);
|
|
298
|
+
try {
|
|
299
|
+
const trial = await api.voice(body.voice);
|
|
300
|
+
if (!trial.draft)
|
|
301
|
+
return json({ error: 'Not a trial voice.' }, 404);
|
|
302
|
+
const voice = await api.keepVoice(trial.id, name);
|
|
303
|
+
const previous = doc.vocalstackVoice?.voiceId;
|
|
304
|
+
const data = await save(req, id, { ...fieldData(voice), consentAt: new Date().toISOString() });
|
|
305
|
+
if (previous && previous !== voice.id)
|
|
306
|
+
await api.deleteVoice(previous).catch(() => undefined);
|
|
307
|
+
return json({ name: nameOf(req, doc), vocalstackVoice: data });
|
|
308
|
+
}
|
|
309
|
+
catch (err) {
|
|
310
|
+
return apiError(err);
|
|
311
|
+
}
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
{
|
|
315
|
+
method: 'delete',
|
|
316
|
+
path: '/:id/vocalstack/voice/trial',
|
|
317
|
+
handler: async (req) => {
|
|
318
|
+
const found = await open(req, 'create');
|
|
319
|
+
if (found instanceof Response)
|
|
320
|
+
return found;
|
|
321
|
+
await dropTrial(found.api, req.searchParams.get('voice') ?? '');
|
|
322
|
+
return json({ ok: true });
|
|
323
|
+
},
|
|
324
|
+
},
|
|
325
|
+
{
|
|
326
|
+
method: 'get',
|
|
327
|
+
path: '/:id/vocalstack/voice/preview',
|
|
328
|
+
handler: async (req) => {
|
|
329
|
+
const found = await open(req, 'hear');
|
|
330
|
+
if (found instanceof Response)
|
|
331
|
+
return found;
|
|
332
|
+
const voiceId = found.doc.vocalstackVoice?.voiceId;
|
|
333
|
+
if (!voiceId)
|
|
334
|
+
return json({ error: 'There is no voice yet.' }, 404);
|
|
335
|
+
const format = req.searchParams.get('format') === 'caf' ? 'caf' : 'ogg';
|
|
336
|
+
try {
|
|
337
|
+
const res = await found.api.voicePreview(voiceId, req.searchParams.get('lang') ?? undefined, format);
|
|
338
|
+
// 202: being rendered; the client asks again.
|
|
339
|
+
if (res.status === 202)
|
|
340
|
+
return json({ pending: true }, 202);
|
|
341
|
+
if (!res.ok)
|
|
342
|
+
return json({ error: `VocalStack answered ${res.status}` }, res.status >= 500 ? 502 : res.status);
|
|
343
|
+
return new Response(res.body, { headers: { 'cache-control': 'private, max-age=3600', 'content-type': res.headers.get('content-type') ?? 'audio/ogg' } });
|
|
344
|
+
}
|
|
345
|
+
catch (err) {
|
|
346
|
+
return apiError(err);
|
|
347
|
+
}
|
|
348
|
+
},
|
|
349
|
+
},
|
|
350
|
+
];
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Shared lookups:
|
|
354
|
+
* GET /vocalstack/languages what can be translated and spoken (public with `listeners` on)
|
|
355
|
+
* GET /vocalstack/voices?lang=&recording= voices that can speak a language (signed in, and `options.access`)
|
|
356
|
+
*/
|
|
357
|
+
export function lookupEndpoints(options) {
|
|
358
|
+
const apiURL = options.apiURL ?? DEFAULT_API_URL;
|
|
359
|
+
const listeners = listenerOptions(options);
|
|
360
|
+
const allowed = async (req) => {
|
|
361
|
+
if (!req.user)
|
|
362
|
+
return json({ error: 'Sign in first.' }, 401);
|
|
363
|
+
if (options.access && !(await options.access({ req })))
|
|
364
|
+
return json({ error: 'You may not use VocalStack here.' }, 403);
|
|
365
|
+
};
|
|
366
|
+
const api = async (req) => {
|
|
367
|
+
const refused = await allowed(req);
|
|
368
|
+
if (refused)
|
|
369
|
+
return refused;
|
|
370
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
371
|
+
if (!apiKey)
|
|
372
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
373
|
+
return new VocalStackAPI(apiKey, apiURL);
|
|
374
|
+
};
|
|
375
|
+
return [
|
|
376
|
+
{
|
|
377
|
+
method: 'get',
|
|
378
|
+
path: '/vocalstack/languages',
|
|
379
|
+
handler: async (req) => {
|
|
380
|
+
// Listeners pick from the languages the site offers them; editors see all of VocalStack's.
|
|
381
|
+
if (!req.user && listeners) {
|
|
382
|
+
return json(forListeners(await languageList(req, options), listeners), 200, { 'cache-control': 'public, max-age=3600, s-maxage=3600' });
|
|
383
|
+
}
|
|
384
|
+
const refused = await allowed(req);
|
|
385
|
+
if (refused)
|
|
386
|
+
return refused;
|
|
387
|
+
if (!(await resolveAPIKey(req, options)))
|
|
388
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
389
|
+
return json(await languageList(req, options));
|
|
390
|
+
},
|
|
391
|
+
},
|
|
392
|
+
{
|
|
393
|
+
method: 'get',
|
|
394
|
+
path: '/vocalstack/voices',
|
|
395
|
+
handler: async (req) => {
|
|
396
|
+
const client = await api(req);
|
|
397
|
+
if (client instanceof Response)
|
|
398
|
+
return client;
|
|
399
|
+
const lang = req.searchParams.get('lang');
|
|
400
|
+
if (!lang)
|
|
401
|
+
return json({ error: 'Which language?' }, 400);
|
|
402
|
+
try {
|
|
403
|
+
return json(await client.availableVoices(lang, req.searchParams.get('recording') ?? undefined));
|
|
404
|
+
}
|
|
405
|
+
catch (err) {
|
|
406
|
+
return apiError(err);
|
|
407
|
+
}
|
|
408
|
+
},
|
|
409
|
+
},
|
|
410
|
+
];
|
|
411
|
+
}
|
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,5 @@
|
|
|
1
1
|
import type { Plugin } from 'payload';
|
|
2
2
|
import type { VocalStackPluginOptions } 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
5
|
export declare const vocalstackPlugin: (options?: VocalStackPluginOptions) => Plugin;
|