@vocalstack/payload 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VocalStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,98 @@
1
- # Temporary Holding Version
1
+ # @vocalstack/payload
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ VocalStack for [Payload CMS](https://payloadcms.com) 3: a **Transcribe** button on every audio upload. The transcript is saved on the document as text plus timed sentences.
4
+
5
+ ## Install
6
+
7
+ Not on npm. Install from this repo; `dist/` is committed, so nothing builds on install (run `pnpm build` and commit `dist/` with every change):
8
+
9
+ ```sh
10
+ pnpm add github:vocalstack/payload-plugin
11
+ ```
12
+
13
+ ```ts
14
+ // payload.config.ts
15
+ import { vocalstackPlugin } from '@vocalstack/payload'
16
+
17
+ export default buildConfig({
18
+ plugins: [
19
+ vocalstackPlugin({
20
+ // Optional. Without it, connect from Admin → Settings → VocalStack.
21
+ apiKey: process.env.VOCALSTACK_API_KEY,
22
+ }),
23
+ ],
24
+ })
25
+ ```
26
+
27
+ Then run `payload generate:importmap`. The plugin adds fields to the targeted collections and a `vocalstack` global, so with Postgres also run `payload migrate:create`.
28
+
29
+ ## What it adds
30
+
31
+ - **Every upload collection that accepts audio** (`audio/*`, a wildcard, or no restriction), or the ones in `collections`, gets:
32
+ - a sidebar **Transcribe** button, shown on `audio/*` documents only. It shows progress and survives a reload mid-job, and **Stop** ends a job you no longer want: the document goes back to how it was (an earlier transcript stays), and VocalStack keeps what it transcribed before the stop.
33
+ - a `vocalstack` group:
34
+ - `transcript`: text you can edit; paragraphs break on a speaker change or a pause.
35
+ - `sentences`: `[{ start, end, speaker, text }]` in seconds.
36
+ - `status`, `language`, `error`, `recordingId`, `transcriptionId` and `transcribedAt`.
37
+ - `POST /api/{collection}/:id/vocalstack/transcribe`, `POST …/vocalstack/stop`, `GET …/vocalstack/status` and `GET …/vocalstack/stream` (live progress as Server-Sent Events).
38
+ - **Settings → VocalStack** (a global), where an editor connects an account. The key is stored server-side and is unreadable over the REST and GraphQL APIs.
39
+
40
+ ## Options
41
+
42
+ | Option | Default | |
43
+ |---|---|---|
44
+ | `apiKey` | none | A `vs_key_…` key with Read and Write. It wins over a key connected in the admin. |
45
+ | `collections` | every upload collection that accepts audio | Which upload collections get the button. |
46
+ | `audioFields` | none | Audio that isn't an upload document; see below. |
47
+ | `spokenLanguage` | auto-detect | A Whisper language code (`en`, `ro`, …). |
48
+ | `fileURL` | the doc's `url`, made absolute | `({ doc, collection, req }) => string`: the address VocalStack fetches. Point it at your bucket's public URL to skip the Payload file proxy. |
49
+ | `access` | signed-in users who can update the doc | Extra check for transcribing and for changing the connection. |
50
+ | `oneClickConnect` | `false` | Show **Connect VocalStack** (see below). |
51
+ | `apiURL` / `dashboardURL` | `https://api.vocalstack.com` / `https://app.vocalstack.com` | |
52
+ | `enabled` | `true` | `false` keeps the schema but removes the button and the endpoints. |
53
+
54
+ ### Audio that isn't an upload
55
+
56
+ Imported content often points at files by name or link instead of upload documents. `audioFields` gives each row of an array field its own button and `vocalstack` transcript:
57
+
58
+ ```ts
59
+ vocalstackPlugin({
60
+ audioFields: [
61
+ {
62
+ collection: 'episodes',
63
+ field: 'attachments', // a top-level array (tabs, rows and collapsibles are looked through)
64
+ condition: (row) => row.type === 'file',
65
+ audioURL: ({ row }) => (row.filename ? `https://cdn.example.com/episodes/${encodeURIComponent(String(row.filename))}` : undefined),
66
+ },
67
+ ],
68
+ })
69
+ ```
70
+
71
+ Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?field=attachments&row=<row id>`. A new row needs saving first.
72
+
73
+ **How the audio reaches VocalStack.** If the file has a public address, VocalStack fetches it (`POST /v1/transcriptions { url }`). Otherwise (localhost, a private network) the plugin uploads the bytes. Either way the job runs on VocalStack, and the admin polls every 3 s. The account is billed per second, with a 5-minute minimum per transcription.
74
+
75
+ ## One-click connect (protocol)
76
+
77
+ The alternative to pasting a key: **Connect VocalStack** opens the dashboard in a new tab, the person clicks **Authenticate**, and the tab closes. This is OAuth 2.0 authorization code + PKCE (RFC 7636) with an API key as the access token. There is no client registration: the consent screen shows the `redirect_uri` host instead.
78
+
79
+ ```
80
+ CMS admin CMS server app.vocalstack.com / api.vocalstack.com
81
+ ────────── ────────── ───────────────────────────────────────
82
+ click Connect ── POST /api/vocalstack/connect ─▶ state, verifier (10 min)
83
+ ◀──────────── { url } ──────────────
84
+ new tab ─▶ GET app/connect?response_type=code&client_name=…&redirect_uri=…&state=…
85
+ &code_challenge=…&code_challenge_method=S256&scope=read write
86
+ (sign in if needed; pick the organization; "example.com wants to transcribe with VocalStack")
87
+ click Authenticate ─▶ API stores a single-use grant (code hash, challenge, redirect, scopes, principal; 2 min)
88
+ ◀── 302 redirect_uri?code=…&state=…
89
+ tab ─────── GET /api/vocalstack/callback ─▶ check state (+ admin session)
90
+ POST api/v1/connect/token (form) ─▶ grant_type=authorization_code, code,
91
+ code_verifier, redirect_uri
92
+ verify, burn the code, create the key
93
+ ◀── { access_token: "vs_key_…", token_type: "api_key", key_id, account: { name } }
94
+ stores the key (never sent to a browser)
95
+ tab: "Connected", BroadcastChannel('vocalstack') ─▶ admin refreshes; tab closes
96
+ ```
97
+
98
+ Cancel redirects with `?error=access_denied&state=…`. The key appears in the dashboard's API keys list as `example.com (Payload CMS)`, where it can be revoked.
package/dist/api.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
+ * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
4
+ */
5
+ export declare const DEFAULT_API_URL = "https://api.vocalstack.com";
6
+ export declare const DEFAULT_DASHBOARD_URL = "https://app.vocalstack.com";
7
+ export type JobState = 'cropping' | 'done' | 'failed' | 'fetching' | 'queued' | 'stopped' | 'transcribing';
8
+ export type Job = {
9
+ error?: null | string;
10
+ /** Why a failed job failed; `stopped` when its owner stopped it. */
11
+ errorCode?: null | string;
12
+ progress: {
13
+ pct: number;
14
+ phase?: null | string;
15
+ phasePct?: null | number;
16
+ processedS?: number;
17
+ totalS?: null | number;
18
+ };
19
+ recordingId: string;
20
+ state: JobState;
21
+ transcriptionId: string;
22
+ };
23
+ export type Transcription = {
24
+ id: string;
25
+ job?: Job | null;
26
+ name: string;
27
+ };
28
+ export type Transcript = {
29
+ lang?: null | string;
30
+ segments: {
31
+ end: number;
32
+ seq: number;
33
+ start: number;
34
+ suppressed?: boolean;
35
+ words?: {
36
+ end: number;
37
+ start: number;
38
+ text: string;
39
+ }[] | null;
40
+ }[];
41
+ sentences: {
42
+ end: number;
43
+ language?: null | string;
44
+ sentenceId: number;
45
+ speaker: number;
46
+ start: number;
47
+ suppressed?: boolean;
48
+ text: string;
49
+ }[];
50
+ };
51
+ export declare class VocalStackAPIError extends Error {
52
+ code: string;
53
+ status: number;
54
+ constructor(status: number, code: string, message: string);
55
+ }
56
+ export declare class VocalStackAPI {
57
+ private apiKey;
58
+ private baseURL;
59
+ constructor(apiKey: string, baseURL?: string);
60
+ private request;
61
+ me(): Promise<Record<string, unknown>>;
62
+ transcribeURL(url: string, opts: {
63
+ idempotencyKey: string;
64
+ name: string;
65
+ spokenLanguage?: string;
66
+ }): Promise<Transcription>;
67
+ transcribeFile(file: Blob, fileName: string, opts: {
68
+ idempotencyKey: string;
69
+ name: string;
70
+ spokenLanguage?: string;
71
+ }): Promise<Transcription>;
72
+ job(recordingId: string): Promise<Job>;
73
+ /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
74
+ stop(recordingId: string, reason?: string): Promise<unknown>;
75
+ transcript(recordingId: string): Promise<Transcript>;
76
+ }
77
+ /** A short label for the connected account, from whatever `/v1/me` carries. */
78
+ export declare function accountLabel(me: Record<string, unknown>): string | undefined;
package/dist/api.js ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The handful of VocalStack API calls the plugin needs, on plain fetch (the
3
+ * SDK is not on npm yet). Contract: https://api.vocalstack.com/v1/openapi.json
4
+ */
5
+ export const DEFAULT_API_URL = 'https://api.vocalstack.com';
6
+ export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
7
+ export class VocalStackAPIError extends Error {
8
+ code;
9
+ status;
10
+ constructor(status, code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ this.status = status;
14
+ }
15
+ }
16
+ export class VocalStackAPI {
17
+ apiKey;
18
+ baseURL;
19
+ constructor(apiKey, baseURL = DEFAULT_API_URL) {
20
+ this.apiKey = apiKey;
21
+ this.baseURL = baseURL;
22
+ }
23
+ async request(method, path, body, headers = {}) {
24
+ const init = { headers: { accept: 'application/json', authorization: `Bearer ${this.apiKey}`, ...headers }, method };
25
+ if (body instanceof FormData)
26
+ init.body = body;
27
+ else if (body !== undefined) {
28
+ init.body = JSON.stringify(body);
29
+ init.headers['content-type'] = 'application/json';
30
+ }
31
+ const res = await fetch(`${this.baseURL}${path}`, init);
32
+ const data = await res.json().catch(() => undefined);
33
+ if (!res.ok) {
34
+ const err = (data?.error ?? data);
35
+ throw new VocalStackAPIError(res.status, err?.code ?? 'http_error', err?.message ?? `VocalStack answered ${res.status}`);
36
+ }
37
+ return data;
38
+ }
39
+ me() {
40
+ return this.request('GET', '/v1/me');
41
+ }
42
+ transcribeURL(url, opts) {
43
+ return this.request('POST', '/v1/transcriptions', { name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined, url }, { 'idempotency-key': opts.idempotencyKey });
44
+ }
45
+ transcribeFile(file, fileName, opts) {
46
+ const form = new FormData();
47
+ form.append('options', JSON.stringify({ name: opts.name, settings: opts.spokenLanguage ? { spokenLanguage: opts.spokenLanguage } : undefined }));
48
+ form.append('file', file, fileName);
49
+ return this.request('POST', '/v1/transcriptions', form, { 'idempotency-key': opts.idempotencyKey });
50
+ }
51
+ job(recordingId) {
52
+ return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/job`);
53
+ }
54
+ /** Stop a job before it is done. Its job fails with `stopped`; what was transcribed so far stays in VocalStack. */
55
+ stop(recordingId, reason) {
56
+ return this.request('POST', `/v1/recordings/${encodeURIComponent(recordingId)}/stop`, { reason: reason ?? null });
57
+ }
58
+ transcript(recordingId) {
59
+ return this.request('GET', `/v1/recordings/${encodeURIComponent(recordingId)}/transcript`);
60
+ }
61
+ }
62
+ /** A short label for the connected account, from whatever `/v1/me` carries. */
63
+ export function accountLabel(me) {
64
+ const pick = (o, ...keys) => {
65
+ if (!o || typeof o !== 'object')
66
+ return undefined;
67
+ for (const k of keys) {
68
+ const v = o[k];
69
+ if (typeof v === 'string' && v)
70
+ return v;
71
+ }
72
+ };
73
+ return pick(me.principal, 'name', 'displayName') ?? pick(me.organization, 'name') ?? pick(me.user, 'email', 'name') ?? pick(me, 'email', 'name', 'displayName');
74
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Brand colors as CSS variables, and the light/dark artwork swap, following
3
+ * Payload's theme (`html[data-theme]`). Rendered once per component tree; repeats are harmless.
4
+ */
5
+ export declare const BrandStyles: () => import("react").JSX.Element;
6
+ /** The VocalStack wordmark. */
7
+ export declare const Logo: React.FC<{
8
+ height?: number;
9
+ }>;
10
+ /** The V on its own, for small spaces. */
11
+ export declare const Mark: React.FC<{
12
+ height?: number;
13
+ }>;
@@ -0,0 +1,19 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { BRAND, LOGO_DARK, LOGO_LIGHT, MARK_DARK, MARK_LIGHT } from './brandAssets.js';
4
+ /**
5
+ * Brand colors as CSS variables, and the light/dark artwork swap, following
6
+ * Payload's theme (`html[data-theme]`). Rendered once per component tree; repeats are harmless.
7
+ */
8
+ export const BrandStyles = () => (_jsx("style", { children: `
9
+ .vs-brand { --vs-accent: ${BRAND.blue}; --vs-coral: ${BRAND.coral}; }
10
+ html[data-theme='dark'] .vs-brand { --vs-accent: ${BRAND.lightBlue}; --vs-coral: ${BRAND.lightCoral}; }
11
+ .vs-art { display: inline-flex; line-height: 0; }
12
+ .vs-art svg { height: 100%; width: auto; }
13
+ html[data-theme='dark'] .vs-art--light, html:not([data-theme='dark']) .vs-art--dark { display: none; }
14
+ ` }));
15
+ const Art = ({ dark, height, label, light }) => (_jsxs("span", { "aria-label": label, role: label ? 'img' : undefined, style: { display: 'inline-flex', verticalAlign: 'middle' }, children: [_jsx("span", { className: "vs-art vs-art--light", dangerouslySetInnerHTML: { __html: light }, style: { height } }), _jsx("span", { className: "vs-art vs-art--dark", dangerouslySetInnerHTML: { __html: dark }, style: { height } })] }));
16
+ /** The VocalStack wordmark. */
17
+ export const Logo = ({ height = 16 }) => _jsx(Art, { dark: LOGO_DARK, height: height, label: "VocalStack", light: LOGO_LIGHT });
18
+ /** The V on its own, for small spaces. */
19
+ export const Mark = ({ height = 14 }) => _jsx(Art, { dark: MARK_DARK, height: height, light: MARK_LIGHT });
@@ -0,0 +1,3 @@
1
+ export declare const ConnectionPanel: React.FC<{
2
+ oneClickConnect?: boolean;
3
+ }>;
@@ -0,0 +1,41 @@
1
+ 'use client';
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { Button, TextInput, toast } from '@payloadcms/ui';
4
+ import { useState } from 'react';
5
+ import { BrandStyles, Logo } from './Brand.js';
6
+ import { useConnection } from './useConnection.js';
7
+ const KEYS_URL = 'https://app.vocalstack.com/developers/keys';
8
+ export const ConnectionPanel = ({ oneClickConnect }) => {
9
+ const { call, connect, connecting, connection, setConnection } = useConnection();
10
+ const [apiKey, setAPIKey] = useState('');
11
+ const [saving, setSaving] = useState(false);
12
+ const [error, setError] = useState();
13
+ const run = async (fn, done) => {
14
+ setSaving(true);
15
+ setError(undefined);
16
+ try {
17
+ setConnection(await fn());
18
+ setAPIKey('');
19
+ toast.success(done);
20
+ }
21
+ catch (err) {
22
+ setError(err.message);
23
+ }
24
+ finally {
25
+ setSaving(false);
26
+ }
27
+ };
28
+ const save = () => void run(() => call('/vocalstack/key', { body: JSON.stringify({ apiKey }), method: 'POST' }), 'Connected to VocalStack.');
29
+ const muted = { color: 'var(--theme-elevation-500)' };
30
+ if (!connection)
31
+ return _jsx("p", { style: muted, children: "Checking the VocalStack connection\u2026" });
32
+ if (connection.source === 'options') {
33
+ return _jsx("p", { style: muted, children: "Connected with the API key from the plugin config. Change it there." });
34
+ }
35
+ return (_jsxs("div", { className: "vs-brand", style: { display: 'grid', gap: 'var(--base)', marginBottom: 'calc(var(--base) * 2)', maxWidth: 560 }, children: [_jsx(BrandStyles, {}), _jsx(Logo, { height: 24 }), connection.connected ? (_jsxs(_Fragment, { children: [_jsxs("p", { style: { margin: 0 }, children: ["Connected to VocalStack", connection.account ? ` as ${connection.account}` : '', ". Audio uploads now have a Transcribe button."] }), _jsx("div", { children: _jsx(Button, { buttonStyle: "secondary", disabled: saving, margin: false, onClick: () => run(() => call('/vocalstack/key', { method: 'DELETE' }), 'Disconnected.'), children: "Disconnect" }) })] })) : (_jsxs(_Fragment, { children: [_jsx("p", { style: { margin: 0 }, children: "Connect a VocalStack account to transcribe audio uploads. Transcriptions use that account's credit." }), oneClickConnect && (_jsxs("div", { children: [_jsx(Button, { disabled: connecting, margin: false, onClick: () => connect().catch((e) => setError(e.message)), children: connecting ? 'Waiting for VocalStack…' : 'Connect VocalStack' }), _jsx("p", { style: { ...muted, fontSize: 13, marginBottom: 0 }, children: "Opens VocalStack in a new tab; click Authenticate there." })] })), _jsxs("div", { onKeyDown: (e) => {
36
+ if (e.key === 'Enter' && apiKey.trim()) {
37
+ e.preventDefault();
38
+ save();
39
+ }
40
+ }, style: { display: 'grid', gap: 'calc(var(--base) / 2)' }, children: [_jsx(TextInput, { label: oneClickConnect ? 'Or paste an API key' : 'API key', onChange: (e) => setAPIKey(e.target.value), path: "vocalstack-api-key", placeholder: "vs_key_\u2026", value: apiKey }), _jsxs("p", { style: { ...muted, fontSize: 13, margin: 0 }, children: ["Create one with Read and Write permissions under", ' ', _jsx("a", { href: KEYS_URL, rel: "noreferrer", target: "_blank", children: "Developers \u2192 API keys" }), ". It is stored on the server and never shown again."] }), _jsx("div", { children: _jsx(Button, { disabled: saving || !apiKey.trim(), margin: false, onClick: save, children: "Save key" }) })] })] })), error && _jsx("p", { style: { color: 'var(--theme-error-500)', margin: 0 }, children: error })] }));
41
+ };
@@ -0,0 +1,8 @@
1
+ type Props = {
2
+ /** Set when the button sits in a row of this array field (`audioFields`). */
3
+ field?: string;
4
+ oneClickConnect?: boolean;
5
+ path?: string;
6
+ };
7
+ export declare const TranscribeButton: React.FC<Props>;
8
+ export {};
@@ -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,3 @@
1
+ export declare const TranscriptField: React.FC<{
2
+ path: string;
3
+ }>;