@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.
@@ -0,0 +1,212 @@
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-voices { display: flex; flex-wrap: wrap; gap: 14px; align-items: center; margin: 4px 0; font-size: 13px; }
16
+ .vs-speech-voices label { display: inline-flex; gap: 6px; align-items: center; cursor: pointer; }
17
+ .vs-speech-error { color: var(--theme-error-500); font-size: 13px; margin: 0; }
18
+ .vs-speech select, .vs-speech input[type=search] { font: inherit; font-size: 13px; padding: 4px 6px; border: 1px solid var(--theme-elevation-150);
19
+ border-radius: var(--style-radius-s, 4px); background: var(--theme-input-bg, var(--theme-elevation-0)); color: var(--theme-text); max-width: 100%; }
20
+ .vs-speech audio { height: 32px; width: 100%; }
21
+ .vs-speech-langs { columns: 3 160px; max-height: 200px; overflow-y: auto; margin: 8px 0; font-size: 13px; }
22
+ .vs-speech-langs label { display: flex; gap: 6px; align-items: center; break-inside: avoid; padding: 2px 0; }
23
+ .vs-spin { display: inline-block; width: 10px; height: 10px; border: 2px solid var(--theme-elevation-200); border-top-color: var(--vs-accent);
24
+ border-radius: 50%; animation: vs-spin .8s linear infinite; margin-right: 6px; vertical-align: -1px; }
25
+ @keyframes vs-spin { to { transform: rotate(360deg); } }
26
+ .vs-bar { position: relative; height: 4px; border-radius: 2px; overflow: hidden; background: var(--theme-elevation-100); }
27
+ .vs-bar span { position: absolute; inset: 0 auto 0 0; min-width: 6%; border-radius: 2px; background: var(--vs-accent); transition: width .6s ease-out; }
28
+ .vs-bar span::after { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, transparent, rgba(255,255,255,.45), transparent);
29
+ animation: vs-sweep 1.4s ease-in-out infinite; }
30
+ @keyframes vs-sweep { from { transform: translateX(-100%); } to { transform: translateX(100%); } }
31
+ @media (prefers-reduced-motion: reduce) { .vs-spin, .vs-bar span::after { animation: none; } }
32
+ `;
33
+ const TRANSLATING = 'Translating…';
34
+ /** The most languages one recording may have, besides its spoken one (VocalStack's limit). */
35
+ const LANGUAGE_LIMIT = 10;
36
+ /** Translations of the transcript, and readings of them aloud: under the transcript once it is done. */
37
+ export const SpeechField = ({ field, path = '' }) => {
38
+ const { id, collectionSlug } = useDocumentInfo();
39
+ const { config: { routes: { api }, serverURL, }, } = useConfig();
40
+ const call = useAPI();
41
+ const { dispatchFields } = useForm();
42
+ // `attachments.3.vocalstack.vocalstackSpeech` → the group, and the row it is in.
43
+ const group = path.replace(/vocalstackSpeech$/, '');
44
+ const rowPrefix = group.replace(/vocalstack\.$/, '');
45
+ const rowId = useFormFields(([fields]) => (field ? fields[`${rowPrefix}id`]?.value : undefined));
46
+ const query = field ? `?${new URLSearchParams({ field, row: rowId ?? '' })}` : '';
47
+ const withQuery = (extra) => `?${new URLSearchParams({ ...(field ? { field, row: rowId ?? '' } : {}), ...extra })}`;
48
+ const translations = (useFormFields(([fields]) => fields[`${group}translations`]?.value) ?? {});
49
+ const speech = (useFormFields(([fields]) => fields[`${group}speech`]?.value) ?? {});
50
+ const spoken = useFormFields(([fields]) => fields[`${group}language`]?.value);
51
+ const toggled = (useFormFields(([fields]) => fields[`${group}voices`]?.value) ?? 'synthetic');
52
+ // Decided by the site (e.g. the speaker's own setting), when the server says so.
53
+ const [decided, setDecided] = useState();
54
+ const voices = decided?.fixed ? decided.mode : toggled;
55
+ // As the server counts them: settled, numbered sentences with text.
56
+ const total = useFormFields(([fields]) => (fields[`${group}sentences`]?.value ?? []).filter((s) => !s.draft && s.id !== undefined && s.text.trim()).length);
57
+ const [langs, setLangs] = useState();
58
+ const [working, setWorking] = useState({});
59
+ const [error, setError] = useState();
60
+ const timer = useRef(undefined);
61
+ const base = `/${collectionSlug}/${id}/vocalstack`;
62
+ // The server saved these; make them the form's saved state too, so Save keeps them.
63
+ const apply = useCallback((data) => {
64
+ for (const key of ['translations', 'speech', 'voices']) {
65
+ if (data && key in data)
66
+ dispatchFields({ type: 'UPDATE', initialValue: data[key], path: `${group}${key}`, value: data[key] });
67
+ }
68
+ }, [dispatchFields, group]);
69
+ // Work the server carries on with: readings being made, and translations (and the readings waiting for them).
70
+ const busySpeech = Object.values(speech).some((s) => s.state === 'queued' || s.state === 'running' || s.state === 'translating') ||
71
+ Object.values(translations).some((t) => t.pending);
72
+ const check = useCallback(async () => {
73
+ clearTimeout(timer.current);
74
+ try {
75
+ const res = await call(`${base}/speak${query}`);
76
+ if (res.voiceMode)
77
+ setDecided(res.voiceMode);
78
+ apply(res.vocalstack);
79
+ const before = speech;
80
+ for (const [lang, s] of Object.entries(res.vocalstack.speech ?? {})) {
81
+ if (s.state === 'sealed' && before[lang]?.state !== 'sealed')
82
+ toast.success(`The ${lang.toUpperCase()} reading is ready.`);
83
+ }
84
+ for (const [lang, t] of Object.entries(res.vocalstack.translations ?? {})) {
85
+ if (!t.pending && translations[lang]?.pending && !t.error)
86
+ toast.success(`The ${lang.toUpperCase()} translation is ready.`);
87
+ }
88
+ setError(undefined);
89
+ }
90
+ catch (err) {
91
+ setError(err.message);
92
+ }
93
+ }, [apply, base, call, query, speech, translations]);
94
+ useEffect(() => {
95
+ if (!id)
96
+ return;
97
+ call('/vocalstack/languages').then(setLangs, (err) => setError(err.message));
98
+ void check();
99
+ // eslint-disable-next-line react-hooks/exhaustive-deps
100
+ }, [id, rowId]);
101
+ // Poll while a reading is being made.
102
+ useEffect(() => {
103
+ if (busySpeech)
104
+ timer.current = setTimeout(check, POLL_MS);
105
+ return () => clearTimeout(timer.current);
106
+ }, [busySpeech, check, speech]);
107
+ const names = useMemo(() => new Map(langs?.languages.map((l) => [l.code, l.name])), [langs]);
108
+ const canSpeak = useMemo(() => new Set(langs?.voice), [langs]);
109
+ // Languages being added show up straight away, with their progress.
110
+ const shown = [...new Set([...Object.keys(translations), ...Object.keys(speech), ...Object.keys(working)])].sort((a, b) => (names.get(a) ?? a).localeCompare(names.get(b) ?? b));
111
+ /** Add languages: the server translates them and, with `speak`, reads them aloud, with no one watching. */
112
+ const request = async (list, speak) => {
113
+ const res = await call(`${base}/request${query}`, { body: JSON.stringify({ langs: list, speak }), method: 'POST' });
114
+ apply(res.vocalstack);
115
+ };
116
+ const run = async (list, label, job) => {
117
+ if (!list.length)
118
+ return;
119
+ setError(undefined);
120
+ setWorking((w) => ({ ...w, ...Object.fromEntries(list.map((l) => [l, label])) }));
121
+ try {
122
+ await job();
123
+ }
124
+ catch (err) {
125
+ setError(err.message);
126
+ }
127
+ finally {
128
+ setWorking((w) => Object.fromEntries(Object.entries(w).filter(([l]) => !list.includes(l))));
129
+ }
130
+ };
131
+ // VocalStack picks the voice.
132
+ const speak = (list) => run(list, 'Asking VocalStack to read it aloud…', async () => {
133
+ const res = await call(`${base}/speak${query}`, { body: JSON.stringify({ langs: list }), method: 'POST' });
134
+ apply(res.vocalstack);
135
+ });
136
+ const [switching, setSwitching] = useState(false);
137
+ const setVoices = async (next) => {
138
+ if (next === voices)
139
+ return;
140
+ setSwitching(true);
141
+ setError(undefined);
142
+ try {
143
+ apply((await call(`${base}/voices${query}`, { body: JSON.stringify({ voices: next }), method: 'POST' })).vocalstack);
144
+ }
145
+ catch (err) {
146
+ setError(err.message);
147
+ }
148
+ finally {
149
+ setSwitching(false);
150
+ }
151
+ };
152
+ const remove = (lang) => window.confirm(`Remove the ${names.get(lang) ?? lang} translation${speech[lang] ? ' and its reading' : ''}?`) &&
153
+ run([lang], 'Removing…', async () => {
154
+ apply((await call(`${base}/translate${withQuery({ lang })}`, { method: 'DELETE' })).vocalstack);
155
+ });
156
+ if (!id)
157
+ return null;
158
+ return (_jsxs("div", { className: "vs-brand vs-speech", children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsx("h4", { children: "Translations and readings" }), decided?.fixed ? (_jsxs("p", { className: "vs-speech-muted", style: { marginBottom: 8 }, children: ["Read aloud in ", _jsx("strong", { children: voices === 'cloned' ? 'cloned voices' : 'synthetic voices' }), ", as set for the person speaking.", voices === 'cloned' ? ' Where they have no cloned voice yet, a synthetic one reads.' : ''] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "vs-speech-voices", role: "radiogroup", "aria-label": "Voices", children: [_jsx("span", { className: "vs-speech-muted", children: "Read aloud in" }), ['synthetic', 'cloned'].map((mode) => (_jsxs("label", { children: [_jsx("input", { checked: voices === mode, disabled: switching, name: `${group}voices-mode`, onChange: () => setVoices(mode), type: "radio" }), mode === 'synthetic' ? 'Synthetic voices' : 'Cloned voices'] }, mode)))] }), _jsxs("p", { className: "vs-speech-muted", style: { marginBottom: 8 }, children: [voices === 'cloned'
159
+ ? 'Each speaker is read in their own cloned voice where they have one (made with their permission), otherwise in a synthetic one.'
160
+ : 'Readings use VocalStack’s synthetic voices.', ' ', "Applies to readings made from now on; read a language again to change one already made."] })] })), !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) => {
161
+ const t = translations[lang];
162
+ const s = speech[lang];
163
+ const busy = working[lang];
164
+ 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?.pending
165
+ ? 'Translating…'
166
+ : t?.error && !t.sentences.length
167
+ ? 'Not translated'
168
+ : t && t.sentences.length < total
169
+ ? `${t.sentences.length} of ${total} sentences translated`
170
+ : t
171
+ ? `${t.sentences.length} sentences translated`
172
+ : 'Not translated' })] }), _jsxs("div", { style: { display: 'grid', gap: 6 }, children: [t?.pending ? (_jsxs(_Fragment, { children: [_jsx(Progress, { done: t.sentences.length, label: TRANSLATING, since: t.requestedAt ?? undefined, total: total }), s?.state === 'translating' && _jsx("span", { className: "vs-speech-muted", children: "Read aloud once translated." }), t.error && _jsxs("span", { className: "vs-speech-muted", children: [t.error, " Trying again shortly."] })] })) : busy ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), busy] })) : s?.state === 'queued' || s?.state === 'running' ? (_jsx(Progress, { done: s.done ?? 0, label: s.state === 'queued' ? 'Waiting to be read aloud…' : 'Being read aloud…', since: s.requestedAt, total: t?.sentences.length ?? 0 })) : s?.state === 'sealed' ? (_jsx("audio", { controls: true, preload: "none", src: `${serverURL}${api}${base}/audio${withQuery({ lang, v: s.renderedAt ?? '' })}` }, s.renderedAt ?? '')) : t?.error && !t.sentences.length ? (_jsxs("p", { className: "vs-speech-error", children: ["Translating failed: ", t.error] })) : s?.state === 'translating' ? (_jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), "Waiting for VocalStack to read it aloud\u2026"] })) : 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 && !t?.pending && (!s || s.state === 'failed' || (s.state === 'sealed' && (s.cast ?? 'synthetic') !== voices)) && (_jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => speak([lang]), size: "small", children: !s ? 'Read aloud' : s.state === 'failed' ? 'Try again' : `Read again in ${voices} voices` }) }))] }), _jsx(Button, { buttonStyle: "secondary", disabled: Boolean(busy), margin: false, onClick: () => remove(lang), size: "small", children: "Remove" })] }, lang));
173
+ }), _jsx(AddLanguages, { busy: Object.keys(working).length > 0, canSpeak: canSpeak, exclude: new Set([...shown, ...(spoken ? [spoken] : [])]), langs: langs, left: LANGUAGE_LIMIT - shown.filter((l) => l !== spoken).length, onAdd: (list, speakToo) => run(list, 'Starting…', () => request(list, speakToo)) }), error && _jsx("p", { className: "vs-speech-error", children: error })] }));
174
+ };
175
+ /** Work under way: the share of sentences done, counted up as each step is saved, and the time it has taken. */
176
+ const Progress = ({ done, label, since, total }) => {
177
+ const [started] = useState(() => (since ? new Date(since).getTime() : Date.now()));
178
+ const [, tick] = useState(0);
179
+ useEffect(() => {
180
+ const t = setInterval(() => tick((n) => n + 1), 1000);
181
+ return () => clearInterval(t);
182
+ }, []);
183
+ const s = Math.max(0, Math.floor((Date.now() - started) / 1000));
184
+ const elapsed = s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`;
185
+ done = Math.min(done, total);
186
+ const share = total ? done / total : 0;
187
+ return (_jsxs("div", { style: { display: 'grid', gap: 4 }, children: [_jsx("div", { "aria-valuemax": total, "aria-valuemin": 0, "aria-valuenow": done, className: "vs-bar", role: "progressbar", children: _jsx("span", { style: { width: `${share * 100}%` } }) }), _jsxs("span", { className: "vs-speech-muted", children: [_jsx("span", { className: "vs-spin" }), label, " ", total ? `${done} of ${total} sentences` : '', " \u00B7 ", elapsed] })] }));
188
+ };
189
+ const AddLanguages = ({ busy, canSpeak, exclude, langs, left, onAdd }) => {
190
+ const [open, setOpen] = useState(false);
191
+ const [filter, setFilter] = useState('');
192
+ const [chosen, setChosen] = useState([]);
193
+ if (!langs)
194
+ return null;
195
+ if (left <= 0) {
196
+ return (_jsxs("p", { className: "vs-speech-muted", style: { marginTop: 10 }, children: ["This recording has ", LANGUAGE_LIMIT, " languages, as many as one recording may have. Remove one to add another."] }));
197
+ }
198
+ const options = langs.languages
199
+ .filter((l) => l.translation && !exclude.has(l.code))
200
+ .filter((l) => !filter || `${l.name} ${l.native} ${l.code}`.toLowerCase().includes(filter.toLowerCase()));
201
+ const go = async (speak) => {
202
+ const list = chosen;
203
+ setChosen([]);
204
+ setOpen(false);
205
+ await onAdd(list, speak);
206
+ };
207
+ if (!open) {
208
+ return (_jsx("div", { style: { marginTop: 10 }, children: _jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: () => setOpen(true), size: "small", children: "Add languages" }) }));
209
+ }
210
+ const tooMany = chosen.length > left;
211
+ 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))) }), _jsxs("p", { className: tooMany ? 'vs-speech-error' : 'vs-speech-muted', style: { marginBottom: 8 }, children: ["\uD83D\uDD0A is read aloud too. ", left, " more language", left === 1 ? '' : 's', " can be added (", LANGUAGE_LIMIT, " at most per recording). VocalStack carries on translating and reading after you leave this page."] }), _jsxs("div", { style: { display: 'flex', flexWrap: 'wrap', gap: 6 }, children: [_jsx(Button, { disabled: busy || !chosen.length || tooMany, margin: false, onClick: () => go(true), size: "small", children: "Translate and read aloud" }), _jsx(Button, { buttonStyle: "secondary", disabled: busy || !chosen.length || tooMany, margin: false, onClick: () => go(false), size: "small", children: "Translate only" }), _jsx(Button, { buttonStyle: "secondary", margin: false, onClick: () => setOpen(false), size: "small", children: "Cancel" })] })] }));
212
+ };
@@ -142,7 +142,7 @@ export const TranscriptField = ({ path }) => {
142
142
  const remove = () => {
143
143
  if (!window.confirm('Delete this transcript? It is removed when you save.'))
144
144
  return;
145
- for (const name of ['sentences', 'language', 'error', 'recordingId', 'transcriptionId', 'transcribedAt']) {
145
+ for (const name of ['sentences', 'language', 'error', 'recordingId', 'transcriptionId', 'transcribedAt', 'translations', 'speech']) {
146
146
  dispatchFields({ type: 'UPDATE', path: `${base}${name}`, value: null });
147
147
  }
148
148
  dispatchFields({ type: 'UPDATE', path: `${base}status`, value: 'idle' });
@@ -0,0 +1 @@
1
+ export declare const VoiceField: React.FC;
@@ -0,0 +1,199 @@
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 } from '@payloadcms/ui';
4
+ import { useCallback, useEffect, useRef, useState } from 'react';
5
+ import { BrandStyles, Logo } from './Brand.js';
6
+ import { useAPI, useConnection } from './useConnection.js';
7
+ import { RecordSample, VoiceFromRecording } from './VoiceSamples.js';
8
+ const POLL_MS = 3000;
9
+ const MIN_S = 30;
10
+ const styles = `
11
+ .vs-voice-tabs { display: flex; gap: 4px; margin-bottom: 8px; }
12
+ .vs-voice select, .vs-voice input[type=file] { width: 100%; font: inherit; }
13
+ .vs-voice select { padding: 6px 8px; border: 1px solid var(--theme-elevation-150); border-radius: var(--style-radius-s, 4px);
14
+ background: var(--theme-input-bg, var(--theme-elevation-0)); color: var(--theme-text); }
15
+ `;
16
+ /** Ogg/Opus where the browser plays it, else CAF (Safari). */
17
+ const previewFormat = () => (typeof Audio !== 'undefined' && new Audio().canPlayType('audio/ogg; codecs=opus') ? 'ogg' : 'caf');
18
+ export const VoiceField = () => {
19
+ const { id, collectionSlug } = useDocumentInfo();
20
+ const { dispatchFields } = useForm();
21
+ const { connection } = useConnection();
22
+ const call = useAPI();
23
+ const base = `/${collectionSlug}/${id}/vocalstack/voice`;
24
+ const [voice, setVoice] = useState();
25
+ const [name, setName] = useState('');
26
+ const [error, setError] = useState();
27
+ const [busy, setBusy] = useState(false);
28
+ const [creating, setCreating] = useState(false);
29
+ const timer = useRef(undefined);
30
+ // Keep the form's copy in step with the server's, so saving the document keeps the voice.
31
+ const apply = useCallback((res) => {
32
+ setVoice(res.vocalstackVoice);
33
+ if (res.name)
34
+ setName(res.name);
35
+ for (const [key, value] of Object.entries(res.vocalstackVoice)) {
36
+ dispatchFields({ type: 'UPDATE', initialValue: value, path: `vocalstackVoice.${key}`, value });
37
+ }
38
+ }, [dispatchFields]);
39
+ const refresh = useCallback(async () => {
40
+ clearTimeout(timer.current);
41
+ try {
42
+ const res = await call(base);
43
+ apply(res);
44
+ setError(undefined);
45
+ if (res.vocalstackVoice.state === 'training')
46
+ timer.current = setTimeout(refresh, POLL_MS);
47
+ }
48
+ catch (err) {
49
+ setError(err.message);
50
+ // Unavailable for now: keep checking on a training voice, more slowly.
51
+ if (voice?.state === 'training')
52
+ timer.current = setTimeout(refresh, POLL_MS * 3);
53
+ }
54
+ }, [apply, base, call, voice?.state]);
55
+ useEffect(() => {
56
+ if (id && connection?.connected)
57
+ void refresh();
58
+ return () => clearTimeout(timer.current);
59
+ // Once per document; `refresh` re-arms itself while training.
60
+ // eslint-disable-next-line react-hooks/exhaustive-deps
61
+ }, [id, connection?.connected]);
62
+ const remove = async () => {
63
+ if (!window.confirm(`Delete ${name || 'this'} voice? Readings already made with it stay as they are.`))
64
+ return;
65
+ setBusy(true);
66
+ try {
67
+ apply(await call(base, { method: 'DELETE' }));
68
+ toast.success('Voice deleted.');
69
+ }
70
+ catch (err) {
71
+ setError(err.message);
72
+ }
73
+ finally {
74
+ setBusy(false);
75
+ }
76
+ };
77
+ const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
78
+ const state = voice?.state ?? 'none';
79
+ return (_jsxs("div", { className: "field-type vs-brand vs-voice", style: { marginBottom: 'var(--base)' }, children: [_jsx(BrandStyles, {}), _jsx("style", { children: styles }), _jsxs("div", { className: "field-label", style: { alignItems: 'center', display: 'flex', gap: 8, marginBottom: 'calc(var(--base) / 2)' }, children: [_jsx(Logo, { height: 14 }), " ", _jsx("span", { children: "Voice" })] }), !id ? (_jsx("p", { style: muted, children: "Save first, then create a voice." })) : connection && !connection.connected ? (_jsx("p", { style: muted, children: "Connect VocalStack (Settings \u2192 VocalStack) to create a voice." })) : !voice ? (_jsx("p", { style: muted, children: error ?? 'Checking…' })) : creating || state === 'none' || state === 'failed' ? (creating ? (_jsx(CreateVoice, { base: base, name: name, onCancel: () => setCreating(false), onCreated: (res) => {
80
+ apply(res);
81
+ setCreating(false);
82
+ timer.current = setTimeout(refresh, POLL_MS);
83
+ } })) : (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [state === 'failed' ? (_jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["The voice could not be made: ", voice.error ?? 'VocalStack gave no reason', "."] })) : (_jsxs("p", { style: muted, children: ["Clone ", name || 'their', " voice to read translations aloud in it."] })), _jsx("div", { children: _jsx(Button, { margin: false, onClick: () => setCreating(true), size: "small", children: state === 'failed' ? 'Try again' : 'Create a voice' }) })] }))) : state === 'training' ? (_jsxs("div", { children: [_jsxs("p", { style: muted, children: ["Training the voice", voice.progress ? ` · ${voice.progress}%` : '…'] }), _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: `${Math.max(2, voice.progress ?? 0)}%` } }) })] })) : (_jsx(ReadyVoice, { base: base, busy: busy, onDelete: remove, voice: voice })), error && voice && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)', marginTop: 8 }, children: error })] }));
84
+ };
85
+ const ReadyVoice = ({ base, busy, onDelete, voice }) => {
86
+ const call = useAPI();
87
+ const [langs, setLangs] = useState();
88
+ const [lang, setLang] = useState('en');
89
+ const [src, setSrc] = useState();
90
+ const [waiting, setWaiting] = useState(false);
91
+ const [error, setError] = useState();
92
+ const audio = useRef(null);
93
+ const { serverURL, api } = useAPIBase();
94
+ useEffect(() => {
95
+ call('/vocalstack/languages').then(setLangs, (err) => setError(err.message));
96
+ }, [call]);
97
+ /** The preview is made on first ask (202): ask until it is there, then play it. */
98
+ const play = async () => {
99
+ setError(undefined);
100
+ setWaiting(true);
101
+ const url = `${serverURL}${api}${base}/preview?${new URLSearchParams({ format: previewFormat(), lang })}`;
102
+ try {
103
+ for (let i = 0; i < 20; i++) {
104
+ const res = await fetch(url, { credentials: 'include' });
105
+ if (res.status === 202) {
106
+ await new Promise((r) => setTimeout(r, 2000));
107
+ continue;
108
+ }
109
+ if (!res.ok)
110
+ throw new Error((await res.json().catch(() => ({}))).error ?? `Preview failed (${res.status})`);
111
+ setSrc(URL.createObjectURL(await res.blob()));
112
+ requestAnimationFrame(() => void audio.current?.play().catch(() => undefined));
113
+ return;
114
+ }
115
+ throw new Error('The preview is taking a while; try again in a minute.');
116
+ }
117
+ catch (err) {
118
+ setError(err.message);
119
+ }
120
+ finally {
121
+ setWaiting(false);
122
+ }
123
+ };
124
+ const names = new Map(langs?.languages.map((l) => [l.code, l.name]));
125
+ const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
126
+ return (_jsxs("div", { style: { display: 'grid', gap: 8 }, children: [_jsxs("p", { style: muted, children: ["Ready", voice.sampleS ? `, cloned from ${Math.round(voice.sampleS)} s of speech` : '', ". Translations are read in this voice."] }), _jsxs("div", { style: { display: 'flex', gap: 6 }, children: [_jsx("select", { "aria-label": "Preview language", onChange: (e) => setLang(e.target.value), value: lang, children: (langs?.voice ?? ['en']).map((code) => (_jsx("option", { value: code, children: names.get(code) ?? code }, code))) }), _jsx(Button, { buttonStyle: "secondary", disabled: waiting, margin: false, onClick: play, size: "small", children: waiting ? 'Making…' : '▶ Hear' })] }), src && _jsx("audio", { controls: true, ref: audio, src: src, style: { width: '100%' } }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsx("div", { children: _jsx(Button, { buttonStyle: "error", disabled: busy, margin: false, onClick: onDelete, size: "small", children: "Delete voice" }) })] }));
127
+ };
128
+ const CreateVoice = ({ base, name, onCancel, onCreated }) => {
129
+ const call = useAPI();
130
+ const { serverURL, api } = useAPIBase();
131
+ const [tab, setTab] = useState('recording');
132
+ const [sources, setSources] = useState();
133
+ const [file, setFile] = useState();
134
+ const [fileS, setFileS] = useState();
135
+ const [consent, setConsent] = useState(false);
136
+ const [busy, setBusy] = useState(false);
137
+ const [error, setError] = useState();
138
+ useEffect(() => {
139
+ call(`${base}/sources`).then((r) => {
140
+ setSources(r.sources);
141
+ if (!r.sources.length)
142
+ setTab('record');
143
+ }, (err) => setError(err.message));
144
+ }, [base, call]);
145
+ const longEnough = (fileS ?? 0) >= MIN_S - 1.5;
146
+ const pick = (f) => {
147
+ setFile(f);
148
+ setFileS(undefined);
149
+ if (!f)
150
+ return;
151
+ // Measure it: VocalStack needs at least 30 s.
152
+ const a = new Audio(URL.createObjectURL(f));
153
+ a.onloadedmetadata = () => setFileS(a.duration);
154
+ };
155
+ const switchTo = (next) => {
156
+ setTab(next);
157
+ setFile(undefined);
158
+ setFileS(undefined);
159
+ setError(undefined);
160
+ };
161
+ /** A recorded or uploaded sample: sent through the server to VocalStack. */
162
+ const upload = async () => {
163
+ if (!file)
164
+ return;
165
+ setBusy(true);
166
+ setError(undefined);
167
+ try {
168
+ const form = new FormData();
169
+ form.append('file', file);
170
+ form.append('_payload', JSON.stringify({ consent }));
171
+ const r = await fetch(`${serverURL}${api}${base}`, { body: form, credentials: 'include', method: 'POST' });
172
+ const body = await r.json().catch(() => ({}));
173
+ if (!r.ok)
174
+ throw new Error(body.error ?? (r.status === 413 ? 'The sample is too large; use a shorter or compressed file.' : `Request failed (${r.status})`));
175
+ toast.success('Voice created. It is training now.');
176
+ onCreated(body);
177
+ }
178
+ catch (err) {
179
+ setError(err.message);
180
+ }
181
+ finally {
182
+ setBusy(false);
183
+ }
184
+ };
185
+ const muted = { color: 'var(--theme-elevation-500)', fontSize: 13, margin: 0 };
186
+ const tabs = [
187
+ ['recording', 'From a sermon'],
188
+ ['record', 'Record'],
189
+ ['file', 'Upload'],
190
+ ];
191
+ return (_jsxs("div", { style: { display: 'grid', gap: 10 }, children: [_jsx("div", { className: "vs-voice-tabs", children: tabs.map(([key, label]) => (_jsx(Button, { buttonStyle: tab === key ? 'primary' : 'secondary', margin: false, onClick: () => switchTo(key), size: "small", children: label }, key))) }), tab === 'recording' ? (!sources ? (_jsx("p", { style: muted, children: error ? '' : 'Looking for transcribed recordings…' })) : !sources.length ? (_jsxs("p", { style: muted, children: ["No transcribed recordings of ", name || 'them', " yet. Transcribe one, or record a sample."] })) : (_jsx(VoiceFromRecording, { base: base, name: name, onCreated: onCreated, sources: sources }))) : (_jsxs(_Fragment, { children: [tab === 'record' ? (_jsx(RecordSample, { onRecorded: (f, seconds) => {
192
+ setFile(f);
193
+ setFileS(seconds);
194
+ } })) : (_jsxs(_Fragment, { children: [_jsxs("p", { style: muted, children: [MIN_S, " s to 2 min of ", name || 'them', " speaking alone, clearly, with no music. An MP3 or M4A of about a minute is ideal."] }), _jsx("input", { accept: "audio/*", onChange: (e) => pick(e.target.files?.[0]), type: "file" })] })), file && fileS !== undefined && !longEnough && _jsxs("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: ["That is ", Math.round(fileS), " s; at least ", MIN_S, " s is needed."] }), _jsxs("label", { style: { alignItems: 'flex-start', display: 'flex', fontSize: 13, gap: 8 }, children: [_jsx("input", { checked: consent, onChange: (e) => setConsent(e.target.checked), style: { marginTop: 3 }, type: "checkbox" }), _jsxs("span", { children: ["I have ", name || 'their', "\u2019s permission to clone their voice."] })] }), error && _jsx("p", { style: { ...muted, color: 'var(--theme-error-500)' }, children: error }), _jsx("div", { children: _jsx(Button, { disabled: busy || !consent || !longEnough || !file, margin: false, onClick: upload, size: "small", children: busy ? 'Creating…' : 'Create voice' }) })] })), _jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", disabled: busy, margin: false, onClick: onCancel, size: "small", children: "Cancel" }) })] }));
195
+ };
196
+ function useAPIBase() {
197
+ const { config: { routes: { api }, serverURL, }, } = useConfig();
198
+ return { api, serverURL };
199
+ }
@@ -0,0 +1,21 @@
1
+ import type { VoiceFieldData, VoiceSource } from '../types.js';
2
+ /** As in the VocalStack dashboard: at least 5 s makes a voice, 20 s a steadier one, 25 s is plenty; 60 s at most. */
3
+ export declare const PICK_MIN_S = 5;
4
+ export declare const sampleStyles = "\n .vs-steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; margin-bottom: 4px; }\n .vs-step { border-top: 3px solid var(--theme-elevation-150); padding-top: 6px; font-size: 12px; color: var(--theme-elevation-500); }\n .vs-step--on { border-color: var(--vs-accent); color: var(--theme-text); font-weight: 600; }\n .vs-step--done { border-color: color-mix(in srgb, var(--vs-accent) 45%, transparent); }\n .vs-sample { border: 1px solid var(--theme-elevation-150); border-radius: 8px; overflow: hidden; }\n .vs-sample-body { padding: 10px 12px; display: grid; gap: 8px; }\n .vs-sample-head { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: var(--theme-elevation-500); }\n .vs-sample-text { font-size: 14px; line-height: 1.45; min-height: 2.9em; }\n .vs-sample-play { display: flex; align-items: center; gap: 10px; }\n .vs-play { width: 34px; height: 34px; flex: none; border-radius: 50%; border: 0; background: var(--vs-accent); color: #fff; cursor: pointer; font-size: 12px; }\n .vs-play:disabled { opacity: .5; cursor: default; }\n .vs-wave { flex: 1; display: flex; align-items: center; gap: 2px; height: 28px; min-width: 0; }\n .vs-wave span { flex: 1; border-radius: 1px; background: var(--theme-elevation-250); }\n .vs-wave span.on { background: var(--vs-accent); }\n .vs-sample-use { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--theme-elevation-150);\n background: var(--theme-elevation-50); font-size: 14px; cursor: pointer; }\n .vs-pager { display: flex; gap: 4px; }\n .vs-pager button { border: 0; background: none; color: var(--theme-text); cursor: pointer; font-size: 16px; padding: 0 6px; }\n .vs-pager button:disabled { opacity: .3; cursor: default; }\n .vs-meter { position: relative; height: 6px; border-radius: 3px; background: var(--theme-elevation-100); overflow: hidden; }\n .vs-meter span { position: absolute; inset: 0 auto 0 0; background: var(--vs-accent); transition: width .3s; }\n .vs-meter-marks { position: relative; height: 16px; font-size: 11px; color: var(--theme-elevation-500); }\n .vs-meter-marks span { position: absolute; transform: translateX(-50%); }\n .vs-chips { display: flex; flex-wrap: wrap; gap: 6px; }\n .vs-chip { display: inline-flex; gap: 6px; align-items: center; border: 1px solid var(--theme-elevation-150); border-radius: 12px; padding: 2px 4px 2px 10px; font-size: 12px; }\n .vs-chip button { border: 0; background: none; cursor: pointer; color: var(--theme-elevation-500); }\n .vs-chips--none { border: 1px dashed var(--theme-elevation-200); border-radius: 12px; padding: 4px 10px; font-size: 12px; color: var(--theme-elevation-500); }\n";
5
+ /**
6
+ * Clone a voice from sentences of one of the person's own transcribed recordings, as in the
7
+ * VocalStack dashboard: pick samples (or have them chosen), hear the voice, then name and keep it.
8
+ */
9
+ export declare const VoiceFromRecording: React.FC<{
10
+ base: string;
11
+ name: string;
12
+ onCreated: (res: {
13
+ name?: string;
14
+ vocalstackVoice: VoiceFieldData;
15
+ }) => void;
16
+ sources: VoiceSource[];
17
+ }>;
18
+ /** Record them speaking, in the browser, as the sample to clone from. */
19
+ export declare const RecordSample: React.FC<{
20
+ onRecorded: (file: File | undefined, seconds: number | undefined) => void;
21
+ }>;