@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,177 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
+
import { Button, toast, useConfig, useDocumentInfo, useForm, useFormFields } from '@payloadcms/ui';
|
|
4
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
5
|
+
import { BrandStyles } from './Brand.js';
|
|
6
|
+
import { useAPI } from './useConnection.js';
|
|
7
|
+
const POLL_MS = 5000;
|
|
8
|
+
const styles = `
|
|
9
|
+
.vs-speech { border: 1px solid var(--theme-elevation-150); border-radius: var(--style-radius-s, 4px); padding: 12px 16px; margin-top: 12px; }
|
|
10
|
+
.vs-speech h4 { margin: 0 0 8px; font-size: 14px; }
|
|
11
|
+
.vs-speech-row { display: grid; grid-template-columns: minmax(110px, 1fr) minmax(0, 2.4fr) auto; gap: 10px; align-items: center; padding: 8px 0;
|
|
12
|
+
border-top: 1px solid var(--theme-elevation-100); font-size: 13px; }
|
|
13
|
+
.vs-speech-row:first-of-type { border-top: 0; }
|
|
14
|
+
.vs-speech-muted { color: var(--theme-elevation-500); font-size: 13px; margin: 0; }
|
|
15
|
+
.vs-speech-error { color: var(--theme-error-500); font-size: 13px; margin: 0; }
|
|
16
|
+
.vs-speech select, .vs-speech input[type=search] { font: inherit; font-size: 13px; padding: 4px 6px; border: 1px solid var(--theme-elevation-150);
|
|
17
|
+
border-radius: var(--style-radius-s, 4px); background: var(--theme-input-bg, var(--theme-elevation-0)); color: var(--theme-text); max-width: 100%; }
|
|
18
|
+
.vs-speech audio { height: 32px; width: 100%; }
|
|
19
|
+
.vs-speech-langs { columns: 3 160px; max-height: 200px; overflow-y: auto; margin: 8px 0; font-size: 13px; }
|
|
20
|
+
.vs-speech-langs label { display: flex; gap: 6px; align-items: center; break-inside: avoid; padding: 2px 0; }
|
|
21
|
+
.vs-spin { display: inline-block; width: 10px; height: 10px; border: 2px solid var(--theme-elevation-200); border-top-color: var(--vs-accent);
|
|
22
|
+
border-radius: 50%; animation: vs-spin .8s linear infinite; margin-right: 6px; vertical-align: -1px; }
|
|
23
|
+
@keyframes vs-spin { to { transform: rotate(360deg); } }
|
|
24
|
+
`;
|
|
25
|
+
/** Translations of the transcript, and readings of them aloud: under the transcript once it is done. */
|
|
26
|
+
export const SpeechField = ({ field, path = '' }) => {
|
|
27
|
+
const { id, collectionSlug } = useDocumentInfo();
|
|
28
|
+
const { config: { routes: { api }, serverURL, }, } = useConfig();
|
|
29
|
+
const call = useAPI();
|
|
30
|
+
const { dispatchFields } = useForm();
|
|
31
|
+
// `attachments.3.vocalstack.vocalstackSpeech` → the group, and the row it is in.
|
|
32
|
+
const group = path.replace(/vocalstackSpeech$/, '');
|
|
33
|
+
const rowPrefix = group.replace(/vocalstack\.$/, '');
|
|
34
|
+
const rowId = useFormFields(([fields]) => (field ? fields[`${rowPrefix}id`]?.value : undefined));
|
|
35
|
+
const query = field ? `?${new URLSearchParams({ field, row: rowId ?? '' })}` : '';
|
|
36
|
+
const withQuery = (extra) => `?${new URLSearchParams({ ...(field ? { field, row: rowId ?? '' } : {}), ...extra })}`;
|
|
37
|
+
const translations = (useFormFields(([fields]) => fields[`${group}translations`]?.value) ?? {});
|
|
38
|
+
const speech = (useFormFields(([fields]) => fields[`${group}speech`]?.value) ?? {});
|
|
39
|
+
const spoken = useFormFields(([fields]) => fields[`${group}language`]?.value);
|
|
40
|
+
const recordingId = useFormFields(([fields]) => fields[`${group}recordingId`]?.value);
|
|
41
|
+
const [langs, setLangs] = useState();
|
|
42
|
+
const [defaultVoice, setDefaultVoice] = useState(null);
|
|
43
|
+
const [voices, setVoices] = useState({});
|
|
44
|
+
const [picked, setPicked] = useState({});
|
|
45
|
+
const [working, setWorking] = useState({});
|
|
46
|
+
const [error, setError] = useState();
|
|
47
|
+
const timer = useRef(undefined);
|
|
48
|
+
const base = `/${collectionSlug}/${id}/vocalstack`;
|
|
49
|
+
// The server saved these; make them the form's saved state too, so Save keeps them.
|
|
50
|
+
const apply = useCallback((data) => {
|
|
51
|
+
for (const key of ['translations', 'speech']) {
|
|
52
|
+
if (data && key in data)
|
|
53
|
+
dispatchFields({ type: 'UPDATE', initialValue: data[key], path: `${group}${key}`, value: data[key] });
|
|
54
|
+
}
|
|
55
|
+
}, [dispatchFields, group]);
|
|
56
|
+
const busySpeech = Object.values(speech).some((s) => s.state === 'queued' || s.state === 'running');
|
|
57
|
+
const check = useCallback(async () => {
|
|
58
|
+
clearTimeout(timer.current);
|
|
59
|
+
try {
|
|
60
|
+
const res = await call(`${base}/speak${query}`);
|
|
61
|
+
setDefaultVoice(res.defaultVoice ?? null);
|
|
62
|
+
apply(res.vocalstack);
|
|
63
|
+
const before = speech;
|
|
64
|
+
for (const [lang, s] of Object.entries(res.vocalstack.speech ?? {})) {
|
|
65
|
+
if (s.state === 'sealed' && before[lang]?.state !== 'sealed')
|
|
66
|
+
toast.success(`The ${lang.toUpperCase()} reading is ready.`);
|
|
67
|
+
}
|
|
68
|
+
setError(undefined);
|
|
69
|
+
}
|
|
70
|
+
catch (err) {
|
|
71
|
+
setError(err.message);
|
|
72
|
+
}
|
|
73
|
+
}, [apply, base, call, query, speech]);
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
if (!id)
|
|
76
|
+
return;
|
|
77
|
+
call('/vocalstack/languages').then(setLangs, (err) => setError(err.message));
|
|
78
|
+
void check();
|
|
79
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
80
|
+
}, [id, rowId]);
|
|
81
|
+
// Poll while a reading is being made.
|
|
82
|
+
useEffect(() => {
|
|
83
|
+
if (busySpeech)
|
|
84
|
+
timer.current = setTimeout(check, POLL_MS);
|
|
85
|
+
return () => clearTimeout(timer.current);
|
|
86
|
+
}, [busySpeech, check, speech]);
|
|
87
|
+
const loadVoices = useCallback((lang) => {
|
|
88
|
+
if (voices[lang])
|
|
89
|
+
return;
|
|
90
|
+
setVoices((v) => ({ ...v, [lang]: [] }));
|
|
91
|
+
call(`/vocalstack/voices?${new URLSearchParams({ lang, ...(recordingId ? { recording: recordingId } : {}) })}`).then((r) => setVoices((v) => ({ ...v, [lang]: r.voices })), () => undefined);
|
|
92
|
+
}, [call, recordingId, voices]);
|
|
93
|
+
const names = useMemo(() => new Map(langs?.languages.map((l) => [l.code, l.name])), [langs]);
|
|
94
|
+
const canSpeak = useMemo(() => new Set(langs?.voice), [langs]);
|
|
95
|
+
const shown = [...new Set([...Object.keys(translations), ...Object.keys(speech)])].sort((a, b) => (names.get(a) ?? a).localeCompare(names.get(b) ?? b));
|
|
96
|
+
const speakable = shown.filter((l) => canSpeak.has(l)).join();
|
|
97
|
+
useEffect(() => {
|
|
98
|
+
for (const l of speakable.split(','))
|
|
99
|
+
if (l)
|
|
100
|
+
loadVoices(l);
|
|
101
|
+
}, [loadVoices, speakable]);
|
|
102
|
+
/** Translate until done (each call stops after a while and says whether there is more). */
|
|
103
|
+
const translate = async (list) => {
|
|
104
|
+
if (!list.length)
|
|
105
|
+
return;
|
|
106
|
+
for (;;) {
|
|
107
|
+
const res = await call(`${base}/translate${query}`, { body: JSON.stringify({ langs: list }), method: 'POST' });
|
|
108
|
+
apply(res.vocalstack);
|
|
109
|
+
if (!res.more)
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
const run = async (list, label, job) => {
|
|
114
|
+
if (!list.length)
|
|
115
|
+
return;
|
|
116
|
+
setError(undefined);
|
|
117
|
+
setWorking((w) => ({ ...w, ...Object.fromEntries(list.map((l) => [l, label])) }));
|
|
118
|
+
try {
|
|
119
|
+
await job();
|
|
120
|
+
}
|
|
121
|
+
catch (err) {
|
|
122
|
+
setError(err.message);
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
setWorking((w) => Object.fromEntries(Object.entries(w).filter(([l]) => !list.includes(l))));
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
const speak = (list, voice) => run(list, 'Translating…', async () => {
|
|
129
|
+
await translate(list.filter((l) => !translations[l]));
|
|
130
|
+
const res = await call(`${base}/speak${query}`, { body: JSON.stringify({ langs: list, voice: voice || undefined }), method: 'POST' });
|
|
131
|
+
apply(res.vocalstack);
|
|
132
|
+
setDefaultVoice(res.defaultVoice ?? null);
|
|
133
|
+
});
|
|
134
|
+
const remove = (lang) => window.confirm(`Remove the ${names.get(lang) ?? lang} translation${speech[lang] ? ' and its reading' : ''}?`) &&
|
|
135
|
+
run([lang], 'Removing…', async () => {
|
|
136
|
+
apply((await call(`${base}/translate${withQuery({ lang })}`, { method: 'DELETE' })).vocalstack);
|
|
137
|
+
});
|
|
138
|
+
const voiceName = (lang, key) => {
|
|
139
|
+
if (!key)
|
|
140
|
+
return 'VocalStack’s default voice';
|
|
141
|
+
return voices[lang]?.find((v) => v.id === key)?.name ?? (key.startsWith('clone:') ? 'a cloned voice' : key);
|
|
142
|
+
};
|
|
143
|
+
if (!id)
|
|
144
|
+
return null;
|
|
145
|
+
return (_jsxs("div", { className: "vs-brand vs-speech", children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsx("h4", { children: "Translations and readings" }), !shown.length && _jsx("p", { className: "vs-speech-muted", children: "Translate the transcript so listeners can read along, or hear it read aloud, in their language." }), shown.map((lang) => {
|
|
146
|
+
const t = translations[lang];
|
|
147
|
+
const s = speech[lang];
|
|
148
|
+
const busy = working[lang];
|
|
149
|
+
const voicesHere = voices[lang] ?? [];
|
|
150
|
+
return (_jsxs("div", { className: "vs-speech-row", children: [_jsxs("div", { children: [_jsx("strong", { children: names.get(lang) ?? lang }), _jsx("p", { className: "vs-speech-muted", children: t ? `${t.sentences.length} sentences translated` : 'Not translated' })] }), _jsxs("div", { style: { display: 'grid', gap: 6 }, children: [busy ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), busy] })) : s?.state === 'queued' || s?.state === 'running' ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), s.state === 'queued' ? 'Waiting to be read aloud…' : 'Being read aloud…', " (", voiceName(lang, s.voice), ")"] })) : s?.state === 'sealed' ? (_jsxs(_Fragment, { children: [_jsx("audio", { controls: true, preload: "none", src: `${serverURL}${api}${base}/audio${withQuery({ lang, v: s.renderedAt ?? '' })}` }, s.renderedAt ?? ''), _jsxs("span", { className: "vs-speech-muted", children: ["Read by ", voiceName(lang, s.voice)] })] })) : s?.state === 'failed' ? (_jsxs("p", { className: "vs-speech-error", children: ["Reading failed: ", s.error ?? 'no reason given'] })) : !canSpeak.has(lang) ? (_jsxs("span", { className: "vs-speech-muted", children: ["VocalStack cannot read ", names.get(lang) ?? lang, " aloud yet."] })) : null, canSpeak.has(lang) && !busy && s?.state !== 'queued' && s?.state !== 'running' && (_jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, children: [_jsxs("select", { "aria-label": "Voice", onChange: (e) => setPicked((p) => ({ ...p, [lang]: e.target.value })), value: picked[lang] ?? '', children: [_jsxs("option", { value: "", children: ["Default for this recording (", voiceName(lang, defaultVoice), ")"] }), voicesHere.map((v) => (_jsxs("option", { disabled: v.ready === false && v.cloned, value: v.id, children: [v.name, v.cloned ? ' (cloned)' : ''] }, v.id)))] }), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => speak([lang], picked[lang]), size: "small", children: s ? 'Read again' : 'Read aloud' })] }))] }), _jsx(Button, { buttonStyle: "secondary", disabled: Boolean(busy), margin: false, onClick: () => remove(lang), size: "small", children: "Remove" })] }, lang));
|
|
151
|
+
}), _jsx(AddLanguages, { busy: Object.keys(working).length > 0, canSpeak: canSpeak, exclude: new Set([...shown, ...(spoken ? [spoken] : [])]), langs: langs, onSpeak: (list) => speak(list), onTranslate: (list) => run(list, 'Translating…', () => translate(list)) }), error && _jsx("p", { className: "vs-speech-error", children: error })] }));
|
|
152
|
+
};
|
|
153
|
+
const AddLanguages = ({ busy, canSpeak, exclude, langs, onSpeak, onTranslate }) => {
|
|
154
|
+
const [open, setOpen] = useState(false);
|
|
155
|
+
const [filter, setFilter] = useState('');
|
|
156
|
+
const [chosen, setChosen] = useState([]);
|
|
157
|
+
if (!langs)
|
|
158
|
+
return null;
|
|
159
|
+
const options = langs.languages
|
|
160
|
+
.filter((l) => l.translation && !exclude.has(l.code))
|
|
161
|
+
.filter((l) => !filter || `${l.name} ${l.native} ${l.code}`.toLowerCase().includes(filter.toLowerCase()));
|
|
162
|
+
const go = async (fn) => {
|
|
163
|
+
const list = chosen;
|
|
164
|
+
setChosen([]);
|
|
165
|
+
setOpen(false);
|
|
166
|
+
await fn(list);
|
|
167
|
+
};
|
|
168
|
+
if (!open) {
|
|
169
|
+
return (_jsx("div", { style: { marginTop: 10 }, children: _jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setOpen(true), size: "small", children: "Add languages" }) }));
|
|
170
|
+
}
|
|
171
|
+
// A reading is at most a few languages at a time.
|
|
172
|
+
const speakable = chosen.filter((l) => canSpeak.has(l));
|
|
173
|
+
return (_jsxs("div", { style: { borderTop: '1px solid var(--theme-elevation-100)', marginTop: 10, paddingTop: 10 }, children: [_jsx("input", { onChange: (e) => setFilter(e.target.value), placeholder: "Find a language", type: "search", value: filter }), _jsx("div", { className: "vs-speech-langs", children: options.map((l) => (_jsxs("label", { children: [_jsx("input", { checked: chosen.includes(l.code), onChange: (e) => setChosen((c) => (e.target.checked ? [...c, l.code] : c.filter((x) => x !== l.code))), type: "checkbox" }), l.name, canSpeak.has(l.code) ? ' 🔊' : ''] }, l.code))) }), _jsx("p", { className: "vs-speech-muted", style: { marginBottom: 8 }, children: "\uD83D\uDD0A can also be read aloud. Translating a long recording takes a few minutes." }), _jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, children: [_jsx(Button, { disabled: busy || !chosen.length, margin: false, onClick: () => go(onTranslate), size: "small", children: "Translate" }), _jsx(Button, { disabled: busy || !speakable.length || speakable.length > 3, margin: false, onClick: () => go(async (list) => {
|
|
174
|
+
await onTranslate(list.filter((l) => !canSpeak.has(l)));
|
|
175
|
+
await onSpeak(list.filter((l) => canSpeak.has(l)));
|
|
176
|
+
}), size: "small", children: speakable.length > 3 ? 'Read aloud: 3 at a time' : 'Translate and read aloud' }), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setOpen(false), size: "small", children: "Cancel" })] })] }));
|
|
177
|
+
};
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Button, toast, useConfig, useDocumentInfo, useForm, useFormFields } from '@payloadcms/ui';
|
|
4
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
5
|
+
import { BrandStyles, Logo } from './Brand.js';
|
|
6
|
+
import { useConnection } from './useConnection.js';
|
|
7
|
+
// Only when the live stream is unavailable.
|
|
8
|
+
const POLL_MS = 3000;
|
|
9
|
+
/** 2433.0 → "40:33", 4000 → "1:06:40". */
|
|
10
|
+
const clock = (s) => {
|
|
11
|
+
const t = Math.floor(s);
|
|
12
|
+
const [h, m, sec] = [Math.floor(t / 3600), Math.floor((t % 3600) / 60), t % 60];
|
|
13
|
+
return `${h ? `${h}:${String(m).padStart(2, '0')}` : m}:${String(sec).padStart(2, '0')}`;
|
|
14
|
+
};
|
|
15
|
+
const PHASES = {
|
|
16
|
+
extracting: 'Extracting audio',
|
|
17
|
+
fetching: 'Fetching the file',
|
|
18
|
+
queued: 'Queued',
|
|
19
|
+
transcribing: 'Transcribing',
|
|
20
|
+
};
|
|
21
|
+
export const TranscribeButton = ({ field, oneClickConnect, path = '' }) => {
|
|
22
|
+
const { id, collectionSlug } = useDocumentInfo();
|
|
23
|
+
// `attachments.3.vocalstackTranscribe` → `attachments.3.`; on an upload document, nothing.
|
|
24
|
+
const prefix = path.replace(/vocalstackTranscribe$/, '');
|
|
25
|
+
const rowId = useFormFields(([fields]) => (field ? fields[`${prefix}id`]?.value : undefined));
|
|
26
|
+
const query = field ? `?${new URLSearchParams({ field, row: rowId ?? '' })}` : '';
|
|
27
|
+
const { config: { routes: { admin, api }, serverURL, }, } = useConfig();
|
|
28
|
+
const { dispatchFields } = useForm();
|
|
29
|
+
const status = useFormFields(([fields]) => fields[`${prefix}vocalstack.status`]?.value);
|
|
30
|
+
const savedError = useFormFields(([fields]) => fields[`${prefix}vocalstack.error`]?.value);
|
|
31
|
+
const language = useFormFields(([fields]) => fields[`${prefix}vocalstack.language`]?.value);
|
|
32
|
+
const { call, connect, connecting, connection } = useConnection();
|
|
33
|
+
const [busy, setBusy] = useState(false);
|
|
34
|
+
const [progress, setProgress] = useState({});
|
|
35
|
+
const [error, setError] = useState();
|
|
36
|
+
const timer = useRef(undefined);
|
|
37
|
+
const source = useRef(undefined);
|
|
38
|
+
// The job as it is heard: settled sentences by id, and the words after them.
|
|
39
|
+
const live = useRef({ draft: [], sentences: new Map() });
|
|
40
|
+
const frame = useRef(undefined);
|
|
41
|
+
// Write the server's copy into the form as its saved state, so a later Save keeps it.
|
|
42
|
+
const apply = useCallback((data) => {
|
|
43
|
+
for (const [key, value] of Object.entries(data ?? {})) {
|
|
44
|
+
dispatchFields({ type: 'UPDATE', initialValue: value, path: `${prefix}vocalstack.${key}`, value });
|
|
45
|
+
}
|
|
46
|
+
}, [dispatchFields, prefix]);
|
|
47
|
+
// Hand the live sentences to the transcript view, at most once a frame, as the field's
|
|
48
|
+
// saved value so the form stays clean. Unchanged sentences keep their identity.
|
|
49
|
+
const publish = useCallback(() => {
|
|
50
|
+
frame.current ??= requestAnimationFrame(() => {
|
|
51
|
+
frame.current = undefined;
|
|
52
|
+
const { draft, sentences } = live.current;
|
|
53
|
+
const list = [...sentences.values()].sort((a, b) => a.start - b.start);
|
|
54
|
+
if (draft.length) {
|
|
55
|
+
list.push({ draft: true, end: draft[draft.length - 1][1], speaker: list.at(-1)?.speaker ?? 0, start: draft[0][0], text: draft.map((w) => w[2]).join(' '), words: draft });
|
|
56
|
+
}
|
|
57
|
+
dispatchFields({ type: 'UPDATE', initialValue: list, path: `${prefix}vocalstack.sentences`, value: list });
|
|
58
|
+
});
|
|
59
|
+
}, [dispatchFields, prefix]);
|
|
60
|
+
const resetLive = useCallback((sentences = []) => {
|
|
61
|
+
live.current = { draft: [], sentences: new Map(sentences.map((s, i) => [s.id ?? -1 - i, s])) };
|
|
62
|
+
publish();
|
|
63
|
+
}, [publish]);
|
|
64
|
+
const finish = useCallback((res) => {
|
|
65
|
+
// A live update still waiting for its frame must not land on top of the result.
|
|
66
|
+
if (frame.current)
|
|
67
|
+
cancelAnimationFrame(frame.current);
|
|
68
|
+
frame.current = undefined;
|
|
69
|
+
apply(res.vocalstack);
|
|
70
|
+
setBusy(false);
|
|
71
|
+
if (res.stopped)
|
|
72
|
+
toast.info('Transcription stopped.');
|
|
73
|
+
else if (res.status === 'done')
|
|
74
|
+
toast.success('Transcript ready.');
|
|
75
|
+
if (res.status === 'failed')
|
|
76
|
+
setError(res.error);
|
|
77
|
+
}, [apply]);
|
|
78
|
+
const poll = useCallback(async () => {
|
|
79
|
+
clearTimeout(timer.current);
|
|
80
|
+
try {
|
|
81
|
+
const res = await call(`/${collectionSlug}/${id}/vocalstack/status${query}`);
|
|
82
|
+
if (res.status === 'processing') {
|
|
83
|
+
setProgress({ audio: res.audio, pct: res.progress, phase: res.phase });
|
|
84
|
+
if (res.partial)
|
|
85
|
+
resetLive(res.partial);
|
|
86
|
+
timer.current = setTimeout(poll, POLL_MS);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
finish(res);
|
|
90
|
+
}
|
|
91
|
+
catch (err) {
|
|
92
|
+
// A network blip should not end the wait; anything VocalStack refused should.
|
|
93
|
+
if (err.code) {
|
|
94
|
+
setBusy(false);
|
|
95
|
+
setError(err.message);
|
|
96
|
+
}
|
|
97
|
+
else
|
|
98
|
+
timer.current = setTimeout(poll, POLL_MS * 2);
|
|
99
|
+
}
|
|
100
|
+
}, [call, collectionSlug, finish, id, query, resetLive]);
|
|
101
|
+
/** Follow the job live: progress, then the words as they are recognized, then the saved result. */
|
|
102
|
+
const follow = useCallback(() => {
|
|
103
|
+
source.current?.close();
|
|
104
|
+
const es = new EventSource(`${serverURL}${api}/${collectionSlug}/${id}/vocalstack/stream${query}`, { withCredentials: true });
|
|
105
|
+
source.current = es;
|
|
106
|
+
es.addEventListener('progress', (e) => {
|
|
107
|
+
const res = JSON.parse(e.data);
|
|
108
|
+
setProgress({ audio: res.audio, pct: res.progress, phase: res.phase });
|
|
109
|
+
});
|
|
110
|
+
es.addEventListener('snapshot', (e) => resetLive(JSON.parse(e.data).sentences));
|
|
111
|
+
es.addEventListener('sentence', (e) => {
|
|
112
|
+
const data = JSON.parse(e.data);
|
|
113
|
+
if (data.removed && data.id !== undefined)
|
|
114
|
+
live.current.sentences.delete(data.id);
|
|
115
|
+
else if (data.sentence?.id !== undefined)
|
|
116
|
+
live.current.sentences.set(data.sentence.id, data.sentence);
|
|
117
|
+
publish();
|
|
118
|
+
});
|
|
119
|
+
es.addEventListener('draft', (e) => {
|
|
120
|
+
live.current.draft = JSON.parse(e.data).words;
|
|
121
|
+
publish();
|
|
122
|
+
});
|
|
123
|
+
for (const outcome of ['done', 'failed', 'stopped']) {
|
|
124
|
+
es.addEventListener(outcome, (e) => {
|
|
125
|
+
es.close();
|
|
126
|
+
source.current = undefined;
|
|
127
|
+
finish(JSON.parse(e.data));
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
// EventSource retries dropped connections itself; it gives up only when the answer was not a
|
|
131
|
+
// stream (the job is already over, or VocalStack refused): ask once, then poll if need be.
|
|
132
|
+
es.onerror = () => {
|
|
133
|
+
if (es.readyState !== EventSource.CLOSED)
|
|
134
|
+
return;
|
|
135
|
+
source.current = undefined;
|
|
136
|
+
void poll();
|
|
137
|
+
};
|
|
138
|
+
}, [api, collectionSlug, finish, id, poll, publish, query, resetLive, serverURL]);
|
|
139
|
+
// Pick a running job back up after a reload. The saved sentences are the previous
|
|
140
|
+
// transcript, not this job's, so start blank until the stream catches up.
|
|
141
|
+
useEffect(() => {
|
|
142
|
+
if (status === 'processing' && id && !source.current && !timer.current) {
|
|
143
|
+
setBusy(true);
|
|
144
|
+
resetLive();
|
|
145
|
+
follow();
|
|
146
|
+
}
|
|
147
|
+
}, [follow, id, resetLive, status]);
|
|
148
|
+
useEffect(() => () => {
|
|
149
|
+
clearTimeout(timer.current);
|
|
150
|
+
source.current?.close();
|
|
151
|
+
if (frame.current)
|
|
152
|
+
cancelAnimationFrame(frame.current);
|
|
153
|
+
}, []);
|
|
154
|
+
const transcribe = async () => {
|
|
155
|
+
setError(undefined);
|
|
156
|
+
setBusy(true);
|
|
157
|
+
setProgress({});
|
|
158
|
+
resetLive();
|
|
159
|
+
try {
|
|
160
|
+
const res = await call(`/${collectionSlug}/${id}/vocalstack/transcribe${query}`, { method: 'POST' });
|
|
161
|
+
// The server still holds the previous transcript (it is replaced once this job is
|
|
162
|
+
// done); take only the job's fields, or the old text flashes up until the stream starts.
|
|
163
|
+
const { sentences: _previous, transcript: _text, ...job } = res.vocalstack ?? {};
|
|
164
|
+
apply(job);
|
|
165
|
+
follow();
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
setBusy(false);
|
|
169
|
+
setError(err.message);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
const [stopping, setStopping] = useState(false);
|
|
173
|
+
/** Stop the job. The field goes back to how it was; VocalStack keeps what it heard so far. */
|
|
174
|
+
const stop = async () => {
|
|
175
|
+
if (!window.confirm('Stop transcribing? What VocalStack has transcribed so far stays in your VocalStack dashboard.'))
|
|
176
|
+
return;
|
|
177
|
+
setStopping(true);
|
|
178
|
+
try {
|
|
179
|
+
const res = await call(`/${collectionSlug}/${id}/vocalstack/stop${query}`, { method: 'POST' });
|
|
180
|
+
if (res.status === 'processing')
|
|
181
|
+
return;
|
|
182
|
+
source.current?.close();
|
|
183
|
+
source.current = undefined;
|
|
184
|
+
clearTimeout(timer.current);
|
|
185
|
+
timer.current = undefined;
|
|
186
|
+
finish(res);
|
|
187
|
+
}
|
|
188
|
+
catch (err) {
|
|
189
|
+
toast.error(err.message);
|
|
190
|
+
}
|
|
191
|
+
finally {
|
|
192
|
+
setStopping(false);
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
const shownError = error ?? (status === 'failed' ? savedError : undefined);
|
|
196
|
+
return (_jsxs("div", { className: "field-type vs-brand", style: { marginBottom: 'var(--base)' }, children: [_jsx(BrandStyles, {}), _jsx("div", { className: "field-label", style: { marginBottom: 'calc(var(--base) / 2)' }, children: _jsx(Logo, { height: 14 }) }), !id ? (_jsx("p", { style: { color: 'var(--theme-elevation-500)', margin: 0 }, children: "Save first, then transcribe." })) : connection && !connection.connected ? (oneClickConnect ? (_jsx(Button, { buttonStyle: "secondary", disabled: connecting, margin: false, onClick: () => connect().catch((e) => setError(e.message)), size: "medium", children: connecting ? 'Waiting for VocalStack…' : 'Connect VocalStack' })) : (_jsx(Button, { buttonStyle: "secondary", el: "link", margin: false, size: "medium", to: `${admin}/globals/vocalstack`, children: "Connect VocalStack" }))) : (_jsx(Button, { disabled: busy || !connection, margin: false, onClick: transcribe, size: "medium", children: busy ? 'Transcribing…' : status === 'done' ? 'Transcribe again' : 'Transcribe' })), busy && (_jsxs("div", { style: { marginTop: 'calc(var(--base) / 2)' }, children: [_jsxs("div", { style: { color: 'var(--theme-elevation-500)', fontSize: 13 }, children: [PHASES[progress.phase ?? 'queued'] ?? progress.phase, progress.pct ? ` · ${progress.pct}%` : '…', progress.audio?.totalS ? ` · ${clock(progress.audio.processedS)} of ${clock(progress.audio.totalS)}` : ''] }), _jsx("div", { style: { background: 'var(--theme-elevation-100)', borderRadius: 2, height: 4, marginTop: 4, overflow: 'hidden' }, children: _jsx("div", { style: { background: 'var(--vs-accent)', height: '100%', transition: 'width .4s', width: `${progress.pct ?? 2}%` } }) }), _jsx("div", { style: { marginTop: 'calc(var(--base) / 2)' }, children: _jsx(Button, { buttonStyle: "secondary", disabled: stopping, margin: false, onClick: stop, size: "small", children: stopping ? 'Stopping…' : 'Stop' }) })] })), !busy && status === 'done' && !shownError && (_jsxs("p", { style: { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 'calc(var(--base) / 2) 0 0' }, children: ["Transcribed", language ? ` (${language})` : '', ". Play the audio to follow along in the transcript."] })), shownError && _jsx("p", { style: { color: 'var(--theme-error-500)', fontSize: 13, margin: 'calc(var(--base) / 2) 0 0' }, children: shownError })] }));
|
|
197
|
+
};
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
+
import { Button, TextareaInput, useField, useForm, useFormFields } from '@payloadcms/ui';
|
|
4
|
+
import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
|
5
|
+
import { paragraphs, timedTokens, transcriptText } from '../text.js';
|
|
6
|
+
import { BrandStyles } from './Brand.js';
|
|
7
|
+
const styles = `
|
|
8
|
+
.vs-transcript { position: relative; max-height: 440px; overflow-y: auto; padding: 12px 16px; border: 1px solid var(--theme-elevation-150);
|
|
9
|
+
border-radius: var(--style-radius-s, 4px); background: var(--theme-input-bg, var(--theme-elevation-0)); font-size: 15px; line-height: 1.75; }
|
|
10
|
+
.vs-transcript p { margin: 0 0 .9em; }
|
|
11
|
+
.vs-transcript p:last-child { margin-bottom: 0; }
|
|
12
|
+
.vs-w { border-radius: 3px; margin: 0 -2px; padding: 0 2px; transition: background-color .12s, color .12s; }
|
|
13
|
+
.vs-transcript--seekable .vs-w { cursor: pointer; }
|
|
14
|
+
.vs-transcript--seekable .vs-w:hover { background: color-mix(in srgb, var(--vs-accent) 16%, transparent); }
|
|
15
|
+
.vs-w--draft { color: var(--theme-elevation-500); }
|
|
16
|
+
.vs-w--new { animation: vs-arrive 1.6s ease-out backwards; }
|
|
17
|
+
.vs-w.vs-w--now { background: var(--vs-accent); color: #fff; }
|
|
18
|
+
@keyframes vs-arrive {
|
|
19
|
+
0% { opacity: 0; background: color-mix(in srgb, var(--vs-accent) 55%, transparent); }
|
|
20
|
+
12% { opacity: 1; }
|
|
21
|
+
100% { background: transparent; }
|
|
22
|
+
}
|
|
23
|
+
.vs-transcript-bar { align-items: center; display: flex; gap: 12px; justify-content: space-between; margin-bottom: 8px; min-height: 28px; }
|
|
24
|
+
.vs-transcript-hint { color: var(--theme-elevation-500); font-size: 13px; }
|
|
25
|
+
.vs-live-dot { background: var(--vs-coral); border-radius: 50%; display: inline-block; height: 7px; margin-right: 6px; width: 7px; animation: vs-pulse 1.2s ease-in-out infinite; }
|
|
26
|
+
@keyframes vs-pulse { 50% { opacity: .3; } }
|
|
27
|
+
@media (prefers-reduced-motion: reduce) { .vs-w--new, .vs-live-dot { animation: none; } }
|
|
28
|
+
`;
|
|
29
|
+
/** One sentence as clickable, timed words. Re-renders only when VocalStack changes the sentence. */
|
|
30
|
+
const Sentence = memo(function Sentence({ freshAfter, sentence }) {
|
|
31
|
+
let fresh = 0;
|
|
32
|
+
return (_jsx(_Fragment, { children: timedTokens(sentence).map(([start, end, text], i) => {
|
|
33
|
+
const isNew = start >= freshAfter;
|
|
34
|
+
// New words arrive one after another, like they are being typed.
|
|
35
|
+
const delay = isNew ? Math.min(fresh++ * 35, 700) : 0;
|
|
36
|
+
return (_jsxs("span", { children: [_jsx("span", { className: `vs-w${sentence.draft ? ' vs-w--draft' : ''}${isNew ? ' vs-w--new' : ''}`, "data-e": end, "data-s": start, style: delay ? { animationDelay: `${delay}ms` } : undefined, children: text }), ' '] }, i));
|
|
37
|
+
}) }));
|
|
38
|
+
}, (a, b) => a.sentence === b.sentence);
|
|
39
|
+
/** The audio this transcript belongs to: the player in the same array row, else our own. */
|
|
40
|
+
function findAudio(box, own) {
|
|
41
|
+
return own ?? box.closest('.array-field__row')?.querySelector('audio') ?? null;
|
|
42
|
+
}
|
|
43
|
+
export const TranscriptField = ({ path }) => {
|
|
44
|
+
const base = path.replace(/transcript$/, '');
|
|
45
|
+
const { setValue, value } = useField({ path });
|
|
46
|
+
const { dispatchFields } = useForm();
|
|
47
|
+
const sentences = useFormFields(([fields]) => fields[`${base}sentences`]?.value);
|
|
48
|
+
const status = useFormFields(([fields]) => fields[`${base}status`]?.value);
|
|
49
|
+
// On an upload document the file is the audio; rows bring their own player.
|
|
50
|
+
const inRow = /\.\d+\./.test(path);
|
|
51
|
+
const fileURL = useFormFields(([fields]) => (inRow ? undefined : fields.url?.value));
|
|
52
|
+
const [editing, setEditing] = useState(false);
|
|
53
|
+
const [seekable, setSeekable] = useState(false);
|
|
54
|
+
const box = useRef(null);
|
|
55
|
+
const ownAudio = useRef(null);
|
|
56
|
+
const words = useRef([]);
|
|
57
|
+
const seenTo = useRef(null);
|
|
58
|
+
const userScrolledAt = useRef(0);
|
|
59
|
+
const processing = status === 'processing';
|
|
60
|
+
const list = sentences ?? [];
|
|
61
|
+
const generated = useMemo(() => transcriptText((sentences ?? []).filter((s) => !s.draft)), [sentences]);
|
|
62
|
+
// Edited by hand: the words no longer match the timings, so show the text as written.
|
|
63
|
+
const edited = !processing && Boolean(value) && value !== generated;
|
|
64
|
+
const timed = list.length > 0 && (processing || !edited);
|
|
65
|
+
// Words count as new (and animate) only past what was already on screen. On first
|
|
66
|
+
// render everything is old; at the start of a transcription the slate is clean.
|
|
67
|
+
if (!list.length)
|
|
68
|
+
seenTo.current = 0;
|
|
69
|
+
const freshAfter = seenTo.current ?? Number.POSITIVE_INFINITY;
|
|
70
|
+
const lastEnd = list.length ? list[list.length - 1].end : 0;
|
|
71
|
+
// Index the rendered words for the playhead, and keep a live transcript scrolled to its end.
|
|
72
|
+
useLayoutEffect(() => {
|
|
73
|
+
seenTo.current = Math.max(seenTo.current ?? 0, lastEnd);
|
|
74
|
+
const el = box.current;
|
|
75
|
+
if (!el)
|
|
76
|
+
return;
|
|
77
|
+
words.current = Array.from(el.querySelectorAll('.vs-w')).map((w) => ({ el: w, end: Number(w.dataset.e), start: Number(w.dataset.s) }));
|
|
78
|
+
if (processing && Date.now() - userScrolledAt.current > 4000)
|
|
79
|
+
el.scrollTop = el.scrollHeight;
|
|
80
|
+
});
|
|
81
|
+
// Follow the audio: highlight the word being spoken, without re-rendering React.
|
|
82
|
+
useEffect(() => {
|
|
83
|
+
const el = box.current;
|
|
84
|
+
if (!el || !timed)
|
|
85
|
+
return;
|
|
86
|
+
const audio = findAudio(el, ownAudio.current);
|
|
87
|
+
setSeekable(Boolean(audio));
|
|
88
|
+
if (!audio)
|
|
89
|
+
return;
|
|
90
|
+
let raf = 0;
|
|
91
|
+
let current = null;
|
|
92
|
+
const at = (t) => {
|
|
93
|
+
const list = words.current;
|
|
94
|
+
let lo = 0;
|
|
95
|
+
let hi = list.length - 1;
|
|
96
|
+
let found = -1;
|
|
97
|
+
while (lo <= hi) {
|
|
98
|
+
const mid = (lo + hi) >> 1;
|
|
99
|
+
if (list[mid].start <= t) {
|
|
100
|
+
found = mid;
|
|
101
|
+
lo = mid + 1;
|
|
102
|
+
}
|
|
103
|
+
else
|
|
104
|
+
hi = mid - 1;
|
|
105
|
+
}
|
|
106
|
+
return found >= 0 && t <= list[found].end + 0.35 ? list[found].el : null;
|
|
107
|
+
};
|
|
108
|
+
const tick = () => {
|
|
109
|
+
const word = at(audio.currentTime);
|
|
110
|
+
if (word !== current) {
|
|
111
|
+
current?.classList.remove('vs-w--now');
|
|
112
|
+
word?.classList.add('vs-w--now');
|
|
113
|
+
current = word;
|
|
114
|
+
// Keep the spoken word in view, unless the editor is reading elsewhere.
|
|
115
|
+
if (word && Date.now() - userScrolledAt.current > 4000) {
|
|
116
|
+
const top = word.offsetTop - el.offsetTop;
|
|
117
|
+
if (top < el.scrollTop || top > el.scrollTop + el.clientHeight - 40)
|
|
118
|
+
el.scrollTo({ behavior: 'smooth', top: top - el.clientHeight / 3 });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (!audio.paused)
|
|
122
|
+
raf = requestAnimationFrame(tick);
|
|
123
|
+
};
|
|
124
|
+
const start = () => {
|
|
125
|
+
cancelAnimationFrame(raf);
|
|
126
|
+
raf = requestAnimationFrame(tick);
|
|
127
|
+
};
|
|
128
|
+
audio.addEventListener('play', start);
|
|
129
|
+
audio.addEventListener('seeked', tick);
|
|
130
|
+
audio.addEventListener('timeupdate', tick);
|
|
131
|
+
if (!audio.paused)
|
|
132
|
+
start();
|
|
133
|
+
return () => {
|
|
134
|
+
cancelAnimationFrame(raf);
|
|
135
|
+
current?.classList.remove('vs-w--now');
|
|
136
|
+
audio.removeEventListener('play', start);
|
|
137
|
+
audio.removeEventListener('seeked', tick);
|
|
138
|
+
audio.removeEventListener('timeupdate', tick);
|
|
139
|
+
};
|
|
140
|
+
}, [timed, editing, fileURL]);
|
|
141
|
+
/** Clear the transcript and its job, back to a fresh Transcribe. Saved with the document. */
|
|
142
|
+
const remove = () => {
|
|
143
|
+
if (!window.confirm('Delete this transcript? It is removed when you save.'))
|
|
144
|
+
return;
|
|
145
|
+
for (const name of ['sentences', 'language', 'error', 'recordingId', 'transcriptionId', 'transcribedAt', 'translations', 'speech']) {
|
|
146
|
+
dispatchFields({ type: 'UPDATE', path: `${base}${name}`, value: null });
|
|
147
|
+
}
|
|
148
|
+
dispatchFields({ type: 'UPDATE', path: `${base}status`, value: 'idle' });
|
|
149
|
+
setValue('');
|
|
150
|
+
setEditing(false);
|
|
151
|
+
};
|
|
152
|
+
const seek = (e) => {
|
|
153
|
+
const word = e.target.closest('.vs-w');
|
|
154
|
+
const audio = box.current && findAudio(box.current, ownAudio.current);
|
|
155
|
+
if (!word || !audio)
|
|
156
|
+
return;
|
|
157
|
+
audio.currentTime = Number(word.dataset.s);
|
|
158
|
+
void audio.play().catch(() => undefined);
|
|
159
|
+
};
|
|
160
|
+
const noteScroll = () => {
|
|
161
|
+
userScrolledAt.current = Date.now();
|
|
162
|
+
};
|
|
163
|
+
const hint = processing ? (_jsxs("span", { children: [_jsx("span", { className: "vs-live-dot" }), "Live from VocalStack"] })) : editing ? ('Editing. Transcribing again replaces your changes.') : edited ? ('Edited by hand, so words are no longer linked to the audio.') : timed && seekable ? ('Play the audio to follow along; click a word to jump there.') : null;
|
|
164
|
+
return (_jsxs("div", { className: "field-type vs-brand", children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), fileURL && _jsx("audio", { controls: true, preload: "none", ref: ownAudio, src: fileURL, style: { marginBottom: 8, width: '100%' } }), _jsxs("div", { className: "vs-transcript-bar", children: [_jsx("span", { className: "vs-transcript-hint", children: hint }), !processing && (_jsxs("span", { style: { display: 'flex', gap: 8 }, children: [editing && (value || list.length > 0) && (_jsx(Button, { buttonStyle: "error", margin: false, onClick: remove, size: "small", children: "Delete transcript" })), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setEditing(!editing), size: "small", children: editing ? 'Done' : value || list.length > 0 ? 'Edit' : 'Write transcript' })] }))] }), editing ? (_jsx(TextareaInput, { onChange: (e) => setValue(e.target.value), path: path, rows: 14, value: value ?? '' })) : timed ? (_jsx("div", { className: `vs-transcript${seekable ? ' vs-transcript--seekable' : ''}`, onClick: seek, onTouchMove: noteScroll, onWheel: noteScroll, ref: box, children: paragraphs(list).map((p) => (_jsx("p", { children: p.map((s) => (_jsx(Sentence, { freshAfter: freshAfter, sentence: s }, s.draft ? 'draft' : s.id))) }, `${p[0].id ?? 'draft'}`))) })) : processing ? (
|
|
165
|
+
// Not the previous transcript: that one is only replaced once this job is done.
|
|
166
|
+
_jsx("p", { className: "vs-transcript-hint", style: { margin: 0 }, children: "The transcript appears here as VocalStack hears it." })) : value ? (_jsx("div", { className: "vs-transcript", ref: box, children: value.split(/\n{2,}/).map((p, i) => (_jsx("p", { children: p }, i))) })) : (_jsx("p", { className: "vs-transcript-hint", style: { margin: 0 }, children: "No transcript yet. Transcribe the audio, or write one yourself." }))] }));
|
|
167
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const VoiceField: React.FC;
|