@vocalstack/payload 0.9.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +20 -1
- package/dist/api.d.ts +2 -0
- package/dist/api.js +13 -2
- package/dist/components/TranscribeSelected.d.ts +7 -0
- package/dist/components/TranscribeSelected.js +101 -0
- package/dist/components/progress.d.ts +9 -0
- package/dist/components/progress.js +39 -0
- package/dist/endpoints/bulk.d.ts +13 -0
- package/dist/endpoints/bulk.js +193 -0
- package/dist/endpoints/connection.js +2 -2
- package/dist/endpoints/stream.js +5 -3
- package/dist/endpoints/transcribe.d.ts +25 -4
- package/dist/endpoints/transcribe.js +59 -16
- package/dist/exports/client.d.ts +2 -0
- package/dist/exports/client.js +2 -0
- package/dist/index.js +14 -0
- package/dist/types.d.ts +49 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -94,6 +94,25 @@ vocalstackPlugin({
|
|
|
94
94
|
|
|
95
95
|
Rows are addressed by their id: `POST /api/episodes/:id/vocalstack/transcribe?field=attachments&row=<row id>`. A new row needs saving first.
|
|
96
96
|
|
|
97
|
+
### Transcribing from the list
|
|
98
|
+
|
|
99
|
+
Select documents in a list (an audio upload collection, or a collection with `audioFields`) and a **Transcribe** button with the VocalStack mark shows above the table. After a confirmation it starts a transcription for every audio file of the selection (each audio row of each document), 25 documents per request; "Select all" across pages takes every document the list's filters match. Files already transcribed or in progress are skipped, and if VocalStack refuses a start every other start would get too (no credit, a cap, the key), nothing more is started and the reason is shown once. `bulkTranscribe: false` turns it off.
|
|
100
|
+
|
|
101
|
+
While the list is open it asks every 5 s (`POST /api/<collection>/vocalstack/settle`) how running jobs stand, saves the ones that finished on their documents and refreshes the list, so nobody has to open each document. The answer's `jobs` (`{ id, row, phase, progress }`, phase `queued`, `fetching`, `transcribing` or `finalizing`) is also there for a list cell: `useTranscriptionProgress(collection, id)` from `@vocalstack/payload/client` returns `{ phase, progress }` for a document while it runs.
|
|
102
|
+
|
|
103
|
+
```tsx
|
|
104
|
+
'use client'
|
|
105
|
+
import { useTranscriptionProgress } from '@vocalstack/payload/client'
|
|
106
|
+
|
|
107
|
+
export const TranscribedCell = ({ cellData, rowData }) => {
|
|
108
|
+
const live = useTranscriptionProgress('sermons', rowData?.id)
|
|
109
|
+
if (live) return <span>{live.phase === 'transcribing' ? `${live.progress}%` : live.phase}</span>
|
|
110
|
+
return <span>{cellData ? '✓' : '–'}</span>
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Every call to VocalStack says `User-Agent: VocalStack-Payload/<version>`, so its transcriptions are recorded as origin `payload`.
|
|
115
|
+
|
|
97
116
|
### Speakers
|
|
98
117
|
|
|
99
118
|
```ts
|
|
@@ -176,7 +195,7 @@ The translation is saved on the document, and where VocalStack can read the lang
|
|
|
176
195
|
|
|
177
196
|
When VocalStack does not answer (an outage, an upgrade), the endpoints say *VocalStack is unavailable, try again shortly.* instead of waiting.
|
|
178
197
|
|
|
179
|
-
**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 connected workspace is billed per second, with a 5-minute minimum per transcription.
|
|
198
|
+
**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. If VocalStack's fetch of a public address fails because of the link (its server refuses VocalStack, as addresses signed for one viewer, IP address or region do; it answers with nothing; or it cannot be reached or found from VocalStack: job `errorCode` `link_refused`, `link_empty`, `link_unreachable` or `link_not_found`), the plugin reads the file itself and uploads the bytes in a new job, once. The job's own reason is shown only when that fails too. Either way the job runs on VocalStack, and the admin polls every 3 s. The connected workspace is billed per second, with a 5-minute minimum per transcription.
|
|
180
199
|
|
|
181
200
|
## The workspace
|
|
182
201
|
|
package/dist/api.d.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* Contract: https://api.vocalstack.com/v1/openapi.json
|
|
6
6
|
*/
|
|
7
7
|
import { VocalStack } from '@vocalstack/js-sdk';
|
|
8
|
+
/** Lets VocalStack record transcriptions made here as origin `payload`. */
|
|
9
|
+
export declare const USER_AGENT = "VocalStack-Payload/0.11.0";
|
|
8
10
|
export declare const DEFAULT_API_URL = "https://api.vocalstack.com";
|
|
9
11
|
export declare const DEFAULT_DASHBOARD_URL = "https://app.vocalstack.com";
|
|
10
12
|
export type JobState = 'cropping' | 'done' | 'failed' | 'fetching' | 'queued' | 'stopped' | 'transcribing';
|
package/dist/api.js
CHANGED
|
@@ -5,6 +5,9 @@
|
|
|
5
5
|
* Contract: https://api.vocalstack.com/v1/openapi.json
|
|
6
6
|
*/
|
|
7
7
|
import { VocalStack, VocalStackError } from '@vocalstack/js-sdk';
|
|
8
|
+
import { VERSION } from './version.js';
|
|
9
|
+
/** Lets VocalStack record transcriptions made here as origin `payload`. */
|
|
10
|
+
export const USER_AGENT = `VocalStack-Payload/${VERSION}`;
|
|
8
11
|
export const DEFAULT_API_URL = 'https://api.vocalstack.com';
|
|
9
12
|
export const DEFAULT_DASHBOARD_URL = 'https://app.vocalstack.com';
|
|
10
13
|
function savedSpeakerOf(raw) {
|
|
@@ -82,7 +85,15 @@ export class VocalStackAPI {
|
|
|
82
85
|
baseUrl: baseURL,
|
|
83
86
|
// One retry of a busy or restarting API; the admin and listeners ask again anyway.
|
|
84
87
|
maxRetries: 1,
|
|
85
|
-
fetch: (input, init) =>
|
|
88
|
+
fetch: (input, init) => {
|
|
89
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
|
|
90
|
+
headers.set('user-agent', USER_AGENT);
|
|
91
|
+
return fetch(input, {
|
|
92
|
+
...init,
|
|
93
|
+
headers,
|
|
94
|
+
signal: init?.signal ?? AbortSignal.timeout(timeoutFor(String(input instanceof Request ? input.url : input), init?.method)),
|
|
95
|
+
});
|
|
96
|
+
},
|
|
86
97
|
});
|
|
87
98
|
}
|
|
88
99
|
me() {
|
|
@@ -163,7 +174,7 @@ export class VocalStackAPI {
|
|
|
163
174
|
const query = Object.entries(init.query ?? {}).filter((e) => e[1] !== undefined);
|
|
164
175
|
const qs = query.length ? `?${new URLSearchParams(query)}` : '';
|
|
165
176
|
const url = `${this.#baseURL}${path}${qs}`;
|
|
166
|
-
const headers = { accept: init.audio ? '*/*' : 'application/json', authorization: `Bearer ${this.#apiKey}
|
|
177
|
+
const headers = { accept: init.audio ? '*/*' : 'application/json', authorization: `Bearer ${this.#apiKey}`, 'user-agent': USER_AGENT };
|
|
167
178
|
if (init.body)
|
|
168
179
|
headers['content-type'] = 'application/json';
|
|
169
180
|
if (init.idempotencyKey)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Above a list of transcribable documents: [V Transcribe] for the selected rows. While the list is open, finished jobs are saved on their
|
|
3
|
+
* documents (and the list refreshed), so no one has to open each one.
|
|
4
|
+
*/
|
|
5
|
+
export declare const TranscribeSelected: React.FC<{
|
|
6
|
+
collection: string;
|
|
7
|
+
}>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { Button, ConfirmationModal, toast, useModal, useSelection } from '@payloadcms/ui';
|
|
4
|
+
import { useRouter } from 'next/navigation.js';
|
|
5
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
6
|
+
import { BrandStyles, Mark } from './Brand.js';
|
|
7
|
+
import { setJobs } from './progress.js';
|
|
8
|
+
import { useAPI } from './useConnection.js';
|
|
9
|
+
/** `SelectAllStatus.AllAvailable`: "Select all" across every page of the list. */
|
|
10
|
+
const ALL = 'allAvailable';
|
|
11
|
+
/** Documents per request; the server takes at most this many. */
|
|
12
|
+
const BATCH = 25;
|
|
13
|
+
/** How often the list asks how running jobs are doing (and saves finished ones). */
|
|
14
|
+
const SETTLE_MS = 5_000;
|
|
15
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
16
|
+
/**
|
|
17
|
+
* Above a list of transcribable documents: [V Transcribe] for the selected rows. While the list is open, finished jobs are saved on their
|
|
18
|
+
* documents (and the list refreshed), so no one has to open each one.
|
|
19
|
+
*/
|
|
20
|
+
export const TranscribeSelected = ({ collection }) => {
|
|
21
|
+
const call = useAPI();
|
|
22
|
+
const router = useRouter();
|
|
23
|
+
const { count, getQueryParams, selectAll, selectedIDs, toggleAll } = useSelection();
|
|
24
|
+
const { openModal } = useModal();
|
|
25
|
+
const modalSlug = `vocalstack-transcribe-${collection}`;
|
|
26
|
+
const [starting, setStarting] = useState();
|
|
27
|
+
const timer = useRef(undefined);
|
|
28
|
+
const settle = useCallback(async () => {
|
|
29
|
+
clearTimeout(timer.current);
|
|
30
|
+
try {
|
|
31
|
+
const r = await call(`/${collection}/vocalstack/settle`, { method: 'POST' });
|
|
32
|
+
setJobs(collection, r.jobs ?? []);
|
|
33
|
+
if (r.finished || r.failed)
|
|
34
|
+
router.refresh();
|
|
35
|
+
if (r.failed)
|
|
36
|
+
toast.error(`${plural(r.failed, 'transcription')} failed. Open the document to see why.`);
|
|
37
|
+
if (r.processing)
|
|
38
|
+
timer.current = setTimeout(settle, SETTLE_MS);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// Not signed in any more, or the server is away: try again later.
|
|
42
|
+
timer.current = setTimeout(settle, SETTLE_MS * 6);
|
|
43
|
+
}
|
|
44
|
+
}, [call, collection, router]);
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
void settle();
|
|
47
|
+
return () => clearTimeout(timer.current);
|
|
48
|
+
}, [settle]);
|
|
49
|
+
/** Every selected id; with "Select all" across pages, the ids the list's filter matches. */
|
|
50
|
+
const ids = useCallback(async () => {
|
|
51
|
+
if (selectAll !== ALL)
|
|
52
|
+
return selectedIDs;
|
|
53
|
+
const params = getQueryParams();
|
|
54
|
+
const { docs } = await call(`/${collection}${params}${params ? '&' : '?'}depth=0&pagination=false&select[id]=true`, { method: 'GET' });
|
|
55
|
+
return docs.map((d) => d.id);
|
|
56
|
+
}, [call, collection, getQueryParams, selectAll, selectedIDs]);
|
|
57
|
+
const start = useCallback(async () => {
|
|
58
|
+
const all = await ids();
|
|
59
|
+
const total = { failed: [], notStarted: 0, skipped: { done: 0, noAudio: 0, processing: 0 }, started: 0 };
|
|
60
|
+
setStarting({ done: 0, total: all.length });
|
|
61
|
+
try {
|
|
62
|
+
for (let i = 0; i < all.length && !total.stopped; i += BATCH) {
|
|
63
|
+
const r = await call(`/${collection}/vocalstack/transcribe-many`, { body: JSON.stringify({ ids: all.slice(i, i + BATCH) }), method: 'POST' });
|
|
64
|
+
total.started += r.started;
|
|
65
|
+
total.notStarted += r.notStarted;
|
|
66
|
+
total.failed.push(...r.failed);
|
|
67
|
+
for (const k of ['done', 'noAudio', 'processing'])
|
|
68
|
+
total.skipped[k] += r.skipped[k];
|
|
69
|
+
total.stopped = r.stopped;
|
|
70
|
+
setStarting({ done: Math.min(i + BATCH, all.length), total: all.length });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
catch (err) {
|
|
74
|
+
total.stopped = { error: err.message };
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
setStarting(undefined);
|
|
78
|
+
}
|
|
79
|
+
const skipped = [
|
|
80
|
+
total.skipped.done && `${total.skipped.done} already transcribed`,
|
|
81
|
+
total.skipped.processing && `${total.skipped.processing} already in progress`,
|
|
82
|
+
total.skipped.noAudio && `${plural(total.skipped.noAudio, 'without audio', 'without audio')}`,
|
|
83
|
+
].filter(Boolean);
|
|
84
|
+
const summary = [`Started ${plural(total.started, 'transcription')}.`, skipped.length ? `Skipped: ${skipped.join(', ')}.` : ''].join(' ').trim();
|
|
85
|
+
if (total.stopped)
|
|
86
|
+
toast.error(`${total.stopped.error}${total.started ? ` ${summary}` : ''}`);
|
|
87
|
+
else if (total.failed.length)
|
|
88
|
+
toast.warning(`${summary} ${plural(total.failed.length, 'file')} could not be started: ${total.failed[0].error}`);
|
|
89
|
+
else
|
|
90
|
+
toast.success(summary);
|
|
91
|
+
if (total.started) {
|
|
92
|
+
toggleAll(false);
|
|
93
|
+
router.refresh();
|
|
94
|
+
void settle();
|
|
95
|
+
}
|
|
96
|
+
}, [call, collection, ids, router, settle, toggleAll]);
|
|
97
|
+
if (!count && !starting)
|
|
98
|
+
return null;
|
|
99
|
+
const howMany = selectAll === ALL ? 'every matching document' : plural(count, 'selected document');
|
|
100
|
+
return (_jsxs("div", { className: "vs-brand", style: { alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: 'calc(var(--base) * 0.75)', marginBottom: 'calc(var(--base) * 0.75)' }, children: [_jsx(BrandStyles, {}), count > 0 && (_jsx(Button, { buttonStyle: "secondary", disabled: Boolean(starting), margin: false, onClick: () => openModal(modalSlug), size: "small", tooltip: `Transcribe ${howMany} with VocalStack`, children: _jsxs("span", { style: { alignItems: 'center', display: 'inline-flex', gap: 6 }, children: [_jsx(Mark, { height: 12 }), starting ? `Starting ${starting.done} of ${starting.total}…` : 'Transcribe'] }) })), _jsx(ConfirmationModal, { body: _jsxs("p", { children: ["Transcribe the audio of ", howMany, " with VocalStack. Files already transcribed or in progress are skipped. Your VocalStack workspace is billed for each transcription."] }), confirmLabel: "Transcribe", heading: "Transcribe with VocalStack", modalSlug: modalSlug, onConfirm: () => void start() })] }));
|
|
101
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { JobProgress } from '../types.js';
|
|
2
|
+
export declare function setJobs(collection: string, next: JobProgress[]): void;
|
|
3
|
+
/**
|
|
4
|
+
* Where a document's transcription stands while it runs: `{ phase, progress }` (phase
|
|
5
|
+
* `queued`, `fetching`, `transcribing` or `finalizing`; progress 0–100), or undefined when
|
|
6
|
+
* nothing of it is running (or the list has not asked yet). With several audio files
|
|
7
|
+
* running, the one furthest behind.
|
|
8
|
+
*/
|
|
9
|
+
export declare function useTranscriptionProgress(collection: string, id: number | string | undefined): Pick<JobProgress, 'phase' | 'progress'> | undefined;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useSyncExternalStore } from 'react';
|
|
3
|
+
/**
|
|
4
|
+
* Running jobs by collection, as the list's last settle reported them. The list's
|
|
5
|
+
* Transcribe bar fills it; any cell in the list can read its row's job with
|
|
6
|
+
* `useTranscriptionProgress`.
|
|
7
|
+
*/
|
|
8
|
+
const jobs = new Map();
|
|
9
|
+
const listeners = new Set();
|
|
10
|
+
export function setJobs(collection, next) {
|
|
11
|
+
jobs.set(collection, next);
|
|
12
|
+
for (const l of listeners)
|
|
13
|
+
l();
|
|
14
|
+
}
|
|
15
|
+
const subscribe = (l) => {
|
|
16
|
+
listeners.add(l);
|
|
17
|
+
return () => listeners.delete(l);
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Where a document's transcription stands while it runs: `{ phase, progress }` (phase
|
|
21
|
+
* `queued`, `fetching`, `transcribing` or `finalizing`; progress 0–100), or undefined when
|
|
22
|
+
* nothing of it is running (or the list has not asked yet). With several audio files
|
|
23
|
+
* running, the one furthest behind.
|
|
24
|
+
*/
|
|
25
|
+
export function useTranscriptionProgress(collection, id) {
|
|
26
|
+
const key = useSyncExternalStore(subscribe, () => {
|
|
27
|
+
if (id === undefined)
|
|
28
|
+
return '';
|
|
29
|
+
const mine = (jobs.get(collection) ?? []).filter((j) => String(j.id) === String(id));
|
|
30
|
+
if (!mine.length)
|
|
31
|
+
return '';
|
|
32
|
+
const behind = mine.reduce((a, b) => (b.progress < a.progress ? b : a));
|
|
33
|
+
return `${behind.phase}|${behind.progress}`;
|
|
34
|
+
}, () => '');
|
|
35
|
+
if (!key)
|
|
36
|
+
return undefined;
|
|
37
|
+
const [phase, progress] = key.split('|');
|
|
38
|
+
return { phase, progress: Number(progress) };
|
|
39
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { CollectionSlug, Endpoint } from 'payload';
|
|
2
|
+
import type { AudioFieldConfig, VocalStackPluginOptions } from '../types.js';
|
|
3
|
+
/** Documents one call may start; the admin sends a long selection in batches, so each request stays short. */
|
|
4
|
+
export declare const BULK_BATCH = 25;
|
|
5
|
+
/**
|
|
6
|
+
* POST /api/<collection>/vocalstack/transcribe-many { ids } starts a transcription for each
|
|
7
|
+
* audio file of each document (the upload itself, or every audio row). Files already
|
|
8
|
+
* transcribed or being transcribed are skipped. At most BULK_BATCH documents per call.
|
|
9
|
+
*
|
|
10
|
+
* POST /api/<collection>/vocalstack/settle saves every job of the collection that has
|
|
11
|
+
* finished, so transcriptions started from the list are kept without anyone opening them.
|
|
12
|
+
*/
|
|
13
|
+
export declare function bulkEndpoints(collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[], isUpload: boolean): Endpoint[];
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { DEFAULT_API_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
3
|
+
import { resolveAPIKey } from '../settings.js';
|
|
4
|
+
import { apiError, canUpdate, checkJob, locate, refileWith, startJob } from './transcribe.js';
|
|
5
|
+
const json = (body, status = 200) => Response.json(body, { status });
|
|
6
|
+
/** Documents one call may start; the admin sends a long selection in batches, so each request stays short. */
|
|
7
|
+
export const BULK_BATCH = 25;
|
|
8
|
+
/** Jobs one settle checks, a few at a time. */
|
|
9
|
+
const SETTLE_LIMIT = 40;
|
|
10
|
+
const SETTLE_PARALLEL = 4;
|
|
11
|
+
/** A list open in several tabs asks often; VocalStack is asked at most this often per collection. */
|
|
12
|
+
const SETTLE_EVERY_MS = 4_000;
|
|
13
|
+
/** What there is to transcribe in one document: the upload itself, and each audio row. */
|
|
14
|
+
async function targetsOf(req, collection, rowFields, isUpload, id) {
|
|
15
|
+
const doc = (await req.payload.findByID({ id, collection, depth: 0, overrideAccess: false, req, user: req.user }).catch(() => null));
|
|
16
|
+
if (!doc)
|
|
17
|
+
return [];
|
|
18
|
+
const out = [];
|
|
19
|
+
if (isUpload && doc.mimeType?.startsWith('audio/'))
|
|
20
|
+
out.push({ id });
|
|
21
|
+
for (const config of rowFields) {
|
|
22
|
+
for (const row of doc[config.field] ?? []) {
|
|
23
|
+
if (row?.id && (!config.condition || config.condition(row)))
|
|
24
|
+
out.push({ field: config.field, id, row: row.id });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
/** Run `work` over `items`, `n` at a time. */
|
|
30
|
+
async function pool(items, n, work) {
|
|
31
|
+
let next = 0;
|
|
32
|
+
await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
|
|
33
|
+
while (next < items.length)
|
|
34
|
+
await work(items[next++]);
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
/** A refusal that every other start would get too: no key, no credit, a cap or rate limit. */
|
|
38
|
+
const stopsAll = (err) => err instanceof VocalStackAPIError && [401, 402, 403, 429].includes(err.status);
|
|
39
|
+
/** A job's phase in the list's words: the work before and after transcribing reads as queued, fetching or finalizing. */
|
|
40
|
+
function phaseOf(phase, progress) {
|
|
41
|
+
if (phase === 'transcribing')
|
|
42
|
+
return progress >= 99 ? 'finalizing' : 'transcribing';
|
|
43
|
+
if (phase === 'fetching' || phase === 'extracting')
|
|
44
|
+
return 'fetching';
|
|
45
|
+
if (!phase || phase === 'queued')
|
|
46
|
+
return 'queued';
|
|
47
|
+
return progress > 0 ? 'finalizing' : 'queued';
|
|
48
|
+
}
|
|
49
|
+
const lastSettle = new Map();
|
|
50
|
+
/**
|
|
51
|
+
* POST /api/<collection>/vocalstack/transcribe-many { ids } starts a transcription for each
|
|
52
|
+
* audio file of each document (the upload itself, or every audio row). Files already
|
|
53
|
+
* transcribed or being transcribed are skipped. At most BULK_BATCH documents per call.
|
|
54
|
+
*
|
|
55
|
+
* POST /api/<collection>/vocalstack/settle saves every job of the collection that has
|
|
56
|
+
* finished, so transcriptions started from the list are kept without anyone opening them.
|
|
57
|
+
*/
|
|
58
|
+
export function bulkEndpoints(collection, options, rowFields, isUpload) {
|
|
59
|
+
const apiURL = options.apiURL ?? DEFAULT_API_URL;
|
|
60
|
+
return [
|
|
61
|
+
{
|
|
62
|
+
method: 'post',
|
|
63
|
+
path: '/vocalstack/transcribe-many',
|
|
64
|
+
handler: async (req) => {
|
|
65
|
+
if (!req.user)
|
|
66
|
+
return json({ error: 'Sign in first.' }, 401);
|
|
67
|
+
if (options.access && !(await options.access({ req })))
|
|
68
|
+
return json({ error: 'You may not transcribe these files.' }, 403);
|
|
69
|
+
const body = (await req.json?.().catch(() => ({})));
|
|
70
|
+
const ids = Array.isArray(body?.ids) ? body.ids.filter((id) => typeof id === 'string' || typeof id === 'number') : [];
|
|
71
|
+
if (!ids.length)
|
|
72
|
+
return json({ error: 'Choose what to transcribe.' }, 400);
|
|
73
|
+
if (ids.length > BULK_BATCH)
|
|
74
|
+
return json({ error: `At most ${BULK_BATCH} at a time.` }, 400);
|
|
75
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
76
|
+
if (!apiKey)
|
|
77
|
+
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
78
|
+
const api = new VocalStackAPI(apiKey, apiURL);
|
|
79
|
+
const result = { failed: [], notStarted: 0, skipped: { done: 0, noAudio: 0, processing: 0 }, started: 0 };
|
|
80
|
+
for (const id of ids) {
|
|
81
|
+
if (!(await canUpdate(req, collection, id))) {
|
|
82
|
+
result.failed.push({ error: 'You may not transcribe this.', id });
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const targets = await targetsOf(req, collection, rowFields, isUpload, id);
|
|
86
|
+
if (!targets.length)
|
|
87
|
+
result.skipped.noAudio++;
|
|
88
|
+
for (const at of targets) {
|
|
89
|
+
if (result.stopped) {
|
|
90
|
+
result.notStarted++;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const target = await locate(req, collection, options, rowFields, 'admin', at);
|
|
94
|
+
if (target instanceof Response) {
|
|
95
|
+
result.failed.push({ error: (await target.json().catch(() => ({}))).error ?? 'Not found.', id });
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (target.data.status === 'processing') {
|
|
99
|
+
result.skipped.processing++;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (target.data.status === 'done' && target.data.transcript) {
|
|
103
|
+
result.skipped.done++;
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (!(await target.url())) {
|
|
107
|
+
result.skipped.noAudio++;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
const call = { idempotencyKey: `payload:${collection}:${id}:${randomUUID()}`, name: target.name, spokenLanguage: options.spokenLanguage };
|
|
112
|
+
const tx = await startJob(req, api, target, call);
|
|
113
|
+
await target.save({ error: null, recordingId: null, status: 'processing', transcriptionId: tx.id });
|
|
114
|
+
result.started++;
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
if (stopsAll(err)) {
|
|
118
|
+
const { code, error } = (await apiError(err).json());
|
|
119
|
+
result.stopped = { code, error };
|
|
120
|
+
result.notStarted++;
|
|
121
|
+
}
|
|
122
|
+
else
|
|
123
|
+
result.failed.push({ error: err instanceof Error ? err.message : String(err), id });
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return json(result);
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
method: 'post',
|
|
132
|
+
path: '/vocalstack/settle',
|
|
133
|
+
handler: async (req) => {
|
|
134
|
+
if (!req.user)
|
|
135
|
+
return json({ error: 'Sign in first.' }, 401);
|
|
136
|
+
const recent = lastSettle.get(collection);
|
|
137
|
+
if (recent && Date.now() - recent.at < SETTLE_EVERY_MS)
|
|
138
|
+
return json({ ...recent.result, failed: 0, finished: 0 });
|
|
139
|
+
const where = {
|
|
140
|
+
or: [
|
|
141
|
+
...(isUpload ? [{ 'vocalstack.status': { equals: 'processing' } }] : []),
|
|
142
|
+
...rowFields.map((f) => ({ [`${f.field}.vocalstack.status`]: { equals: 'processing' } })),
|
|
143
|
+
],
|
|
144
|
+
};
|
|
145
|
+
// Read as the user: only what they may see is checked.
|
|
146
|
+
const { docs } = await req.payload.find({ collection, depth: 0, limit: SETTLE_LIMIT, overrideAccess: false, pagination: false, req, user: req.user, where });
|
|
147
|
+
const pending = [];
|
|
148
|
+
for (const doc of docs) {
|
|
149
|
+
const id = doc.id;
|
|
150
|
+
if (isUpload && doc.vocalstack?.status === 'processing')
|
|
151
|
+
pending.push({ id });
|
|
152
|
+
for (const { field } of rowFields) {
|
|
153
|
+
for (const row of doc[field] ?? [])
|
|
154
|
+
if (row?.id && row.vocalstack?.status === 'processing')
|
|
155
|
+
pending.push({ field, id, row: row.id });
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const result = { failed: 0, finished: 0, jobs: [], processing: 0 };
|
|
159
|
+
if (!pending.length) {
|
|
160
|
+
lastSettle.set(collection, { at: Date.now(), result });
|
|
161
|
+
return json(result);
|
|
162
|
+
}
|
|
163
|
+
const apiKey = await resolveAPIKey(req, options);
|
|
164
|
+
if (!apiKey)
|
|
165
|
+
return json({ ...result, processing: pending.length });
|
|
166
|
+
const api = new VocalStackAPI(apiKey, apiURL);
|
|
167
|
+
await pool(pending, SETTLE_PARALLEL, async (at) => {
|
|
168
|
+
const target = await locate(req, collection, options, rowFields, 'admin', at);
|
|
169
|
+
if (target instanceof Response || target.data.status !== 'processing' || !target.data.transcriptionId)
|
|
170
|
+
return;
|
|
171
|
+
try {
|
|
172
|
+
const status = await checkJob(api, target, target.data.transcriptionId, refileWith(req, api, target, collection, options.spokenLanguage), false);
|
|
173
|
+
if (status.status === 'processing') {
|
|
174
|
+
result.processing++;
|
|
175
|
+
result.jobs.push({ id: at.id, phase: phaseOf(status.phase, status.progress ?? 0), progress: Math.round(status.progress ?? 0), row: at.row });
|
|
176
|
+
}
|
|
177
|
+
else if (status.status === 'failed')
|
|
178
|
+
result.failed++;
|
|
179
|
+
else
|
|
180
|
+
result.finished++;
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
// VocalStack could not be asked now; the next settle asks again.
|
|
184
|
+
result.processing++;
|
|
185
|
+
result.jobs.push({ id: at.id, phase: 'queued', progress: 0, row: at.row });
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
lastSettle.set(collection, { at: Date.now(), result });
|
|
189
|
+
return json(result);
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
];
|
|
193
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
-
import { accountLabel, DEFAULT_API_URL, DEFAULT_DASHBOARD_URL, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
2
|
+
import { accountLabel, DEFAULT_API_URL, DEFAULT_DASHBOARD_URL, USER_AGENT, VocalStackAPI, VocalStackAPIError } from '../api.js';
|
|
3
3
|
import { readSettings, writeSettings } from '../settings.js';
|
|
4
4
|
import { workspaceOf } from '../workspace.js';
|
|
5
5
|
const json = (body, status = 200) => Response.json(body, { status });
|
|
@@ -186,7 +186,7 @@ export function connectionEndpoints(options) {
|
|
|
186
186
|
return page(params.get('error') === 'access_denied' ? 'Connection cancelled.' : `VocalStack said: ${params.get('error_description') ?? params.get('error')}`, false);
|
|
187
187
|
const res = await fetch(`${apiURL}/v1/connect/token`, {
|
|
188
188
|
body: new URLSearchParams({ code: params.get('code') ?? '', code_verifier: settings.connectVerifier, grant_type: 'authorization_code', redirect_uri: callbackURL(req) }),
|
|
189
|
-
headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
|
|
189
|
+
headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded', 'user-agent': USER_AGENT },
|
|
190
190
|
method: 'POST',
|
|
191
191
|
});
|
|
192
192
|
const token = (await res.json().catch(() => ({})));
|
package/dist/endpoints/stream.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DEFAULT_API_URL, VocalStackAPI } from '../api.js';
|
|
2
2
|
import { resolveAPIKey } from '../settings.js';
|
|
3
3
|
import { attachWords } from '../text.js';
|
|
4
|
-
import { apiError, checkJob, locate, toSentences } from './transcribe.js';
|
|
4
|
+
import { apiError, checkJob, locate, refileWith, toSentences } from './transcribe.js';
|
|
5
5
|
const OVER = new Set(['done', 'failed', 'cropping', 'ended', 'finalized']);
|
|
6
6
|
/**
|
|
7
7
|
* GET /:id/vocalstack/stream: the job live, as Server-Sent Events. The server holds
|
|
@@ -57,8 +57,10 @@ export function streamEndpoint(collection, options, rowFields) {
|
|
|
57
57
|
};
|
|
58
58
|
// VocalStack signals the end several ways (progress, state, socket close); check once at a time.
|
|
59
59
|
let settling;
|
|
60
|
-
const settle = () => (settling ??= checkJob(api, target, transcriptionId)
|
|
61
|
-
.then(
|
|
60
|
+
const settle = () => (settling ??= checkJob(api, target, transcriptionId, refileWith(req, api, target, collection, options.spokenLanguage))
|
|
61
|
+
.then(
|
|
62
|
+
// A job started again from the file's bytes (its link failed) has a new id: close, and EventSource reconnects to follow it.
|
|
63
|
+
(r) => (r.status === 'processing' && (!r.vocalstack || r.vocalstack.transcriptionId === transcriptionId) ? undefined : finish(r)), (err) => finish({ error: err.message, status: 'failed' }))
|
|
62
64
|
.finally(() => (settling = undefined)));
|
|
63
65
|
// What the page has been told: settled sentences by id, the words of committed
|
|
64
66
|
// segments (sentences take theirs by time), and the words heard since.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { CollectionSlug, Endpoint, PayloadRequest } from 'payload';
|
|
2
2
|
import type { ArrayRow, AudioFieldConfig, StatusResponse, TranscriptSentence, VocalStackFieldData, VocalStackPluginOptions } from '../types.js';
|
|
3
|
-
import { type Transcript, VocalStackAPI } from '../api.js';
|
|
3
|
+
import { type Job, type Transcript, type Transcription, VocalStackAPI } from '../api.js';
|
|
4
4
|
/** Whether the signed-in user may update this document, by the collection's own `access.update`. */
|
|
5
5
|
export declare function canUpdate(req: PayloadRequest, collection: CollectionSlug, id: number | string): Promise<boolean>;
|
|
6
6
|
type Patch = ((current: VocalStackFieldData) => VocalStackFieldData) | VocalStackFieldData;
|
|
@@ -9,6 +9,8 @@ export type Target = {
|
|
|
9
9
|
data: VocalStackFieldData;
|
|
10
10
|
doc: Record<string, unknown>;
|
|
11
11
|
fileName: string;
|
|
12
|
+
/** The document's id. */
|
|
13
|
+
id: number | string;
|
|
12
14
|
name: string;
|
|
13
15
|
/** Set when the target is a row of an array field. */
|
|
14
16
|
row?: ArrayRow;
|
|
@@ -16,15 +18,34 @@ export type Target = {
|
|
|
16
18
|
save: (patch: Patch) => Promise<VocalStackFieldData>;
|
|
17
19
|
url: () => Promise<string | undefined>;
|
|
18
20
|
};
|
|
19
|
-
export declare function locate(req: PayloadRequest, collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[], readAs: 'admin' | 'user'
|
|
21
|
+
export declare function locate(req: PayloadRequest, collection: CollectionSlug, options: VocalStackPluginOptions, rowFields: AudioFieldConfig[], readAs: 'admin' | 'user',
|
|
22
|
+
/** Which document (and row) to act on; by default the request's own (`/:id`, `?field=&row=`). */
|
|
23
|
+
at?: {
|
|
24
|
+
field?: string;
|
|
25
|
+
id: number | string;
|
|
26
|
+
row?: string;
|
|
27
|
+
}): Promise<Response | Target>;
|
|
20
28
|
/** A transcript's sentences, each with its words. */
|
|
21
29
|
export declare function toSentences(t: Pick<Transcript, 'segments' | 'sentences'>): TranscriptSentence[];
|
|
22
30
|
export declare function apiError(err: unknown): Response;
|
|
31
|
+
/** Start a job for the target's file: by link when VocalStack can fetch it, otherwise (or when `asFile`) by sending the bytes. */
|
|
32
|
+
export declare function startJob(req: PayloadRequest, api: VocalStackAPI, target: Target, call: {
|
|
33
|
+
idempotencyKey: string;
|
|
34
|
+
name: string;
|
|
35
|
+
spokenLanguage?: string;
|
|
36
|
+
}, asFile?: boolean): Promise<Transcription & {
|
|
37
|
+
job: Job;
|
|
38
|
+
}>;
|
|
39
|
+
/** Sends the file's bytes in place of a link VocalStack could not use; the new job is saved on the target. */
|
|
40
|
+
export declare function refileWith(req: PayloadRequest, api: VocalStackAPI, target: Target, collection: CollectionSlug, spokenLanguage?: string): () => Promise<StatusResponse>;
|
|
23
41
|
/**
|
|
24
42
|
* Where a job stands, saving the outcome on the document once it is over: the
|
|
25
|
-
* whole transcript when done, the reason when it failed.
|
|
43
|
+
* whole transcript when done, the reason when it failed. With `refile`, a job whose
|
|
44
|
+
* link failed (see REFILE_CODES) is started again from the file's bytes.
|
|
26
45
|
*/
|
|
27
|
-
export declare function checkJob(api: VocalStackAPI, target: Target, transcriptionId: string)
|
|
46
|
+
export declare function checkJob(api: VocalStackAPI, target: Pick<Target, 'data' | 'save'>, transcriptionId: string, refile?: () => Promise<StatusResponse>,
|
|
47
|
+
/** Read the sentences so far while it runs (for a page following it). */
|
|
48
|
+
withPartial?: boolean): Promise<StatusResponse>;
|
|
28
49
|
/**
|
|
29
50
|
* POST /:id/vocalstack/transcribe and GET /:id/vocalstack/status. With no query
|
|
30
51
|
* they act on the upload document itself; with `?field=<array>&row=<row id>` on one row.
|
|
@@ -18,6 +18,8 @@ function serially(key, run) {
|
|
|
18
18
|
}
|
|
19
19
|
/** Finished jobs being saved, so that every "done" signal for one job shares a single save. */
|
|
20
20
|
const finishing = new Map();
|
|
21
|
+
/** Jobs whose link failed, being started again from the bytes: one new job per failed one. */
|
|
22
|
+
const refiling = new Map();
|
|
21
23
|
/** Whether the signed-in user may update this document, by the collection's own `access.update`. */
|
|
22
24
|
export async function canUpdate(req, collection, id) {
|
|
23
25
|
if (!req.user)
|
|
@@ -35,13 +37,15 @@ const merge = (current, patch) => ({
|
|
|
35
37
|
...current,
|
|
36
38
|
...(typeof patch === 'function' ? patch(current ?? {}) : patch),
|
|
37
39
|
});
|
|
38
|
-
export async function locate(req, collection, options, rowFields, readAs
|
|
39
|
-
|
|
40
|
+
export async function locate(req, collection, options, rowFields, readAs,
|
|
41
|
+
/** Which document (and row) to act on; by default the request's own (`/:id`, `?field=&row=`). */
|
|
42
|
+
at) {
|
|
43
|
+
const id = at?.id ?? req.routeParams?.id;
|
|
40
44
|
const find = (overrideAccess) => req.payload.findByID({ id, collection, depth: 0, overrideAccess, req, user: req.user }).catch(() => null);
|
|
41
45
|
const doc = await find(readAs === 'admin');
|
|
42
46
|
if (!doc)
|
|
43
47
|
return json({ error: 'Not found.' }, 404);
|
|
44
|
-
const field = req.searchParams.get('field');
|
|
48
|
+
const field = at ? at.field : req.searchParams.get('field');
|
|
45
49
|
if (!field) {
|
|
46
50
|
const upload = doc;
|
|
47
51
|
if (!req.payload.collections[collection]?.config.upload)
|
|
@@ -52,6 +56,7 @@ export async function locate(req, collection, options, rowFields, readAs) {
|
|
|
52
56
|
data: upload.vocalstack ?? {},
|
|
53
57
|
doc,
|
|
54
58
|
fileName: upload.filename ?? 'audio',
|
|
59
|
+
id,
|
|
55
60
|
name: upload.filename ?? `${collection} ${id}`,
|
|
56
61
|
save: (patch) => serially(`${collection}:${id}`, async () => {
|
|
57
62
|
const fresh = (typeof patch === 'function' ? (await find(true)) : null) ?? upload;
|
|
@@ -65,7 +70,7 @@ export async function locate(req, collection, options, rowFields, readAs) {
|
|
|
65
70
|
const config = rowFields.find((f) => f.field === field);
|
|
66
71
|
if (!config)
|
|
67
72
|
return json({ error: `${field} is not a VocalStack audio field.` }, 400);
|
|
68
|
-
const rowId = req.searchParams.get('row');
|
|
73
|
+
const rowId = at ? at.row : req.searchParams.get('row');
|
|
69
74
|
const row = (doc[field] ?? []).find((r) => r.id === rowId);
|
|
70
75
|
if (!row)
|
|
71
76
|
return json({ error: 'Save the document first, then transcribe.' }, 404);
|
|
@@ -74,6 +79,7 @@ export async function locate(req, collection, options, rowFields, readAs) {
|
|
|
74
79
|
data: row.vocalstack ?? {},
|
|
75
80
|
doc,
|
|
76
81
|
fileName: 'audio',
|
|
82
|
+
id,
|
|
77
83
|
name: config.name?.({ doc, row }) ?? (typeof doc.title === 'string' && doc.title ? doc.title : `${collection} ${id}`),
|
|
78
84
|
row,
|
|
79
85
|
save: (patch) => serially(`${collection}:${id}`, async () => {
|
|
@@ -113,11 +119,40 @@ export function apiError(err) {
|
|
|
113
119
|
}
|
|
114
120
|
return json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
115
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* Link failures that sending the bytes can get past: the file's server refused
|
|
124
|
+
* VocalStack (signed for one viewer, IP address or region), answered with nothing,
|
|
125
|
+
* or could not be reached or found from VocalStack. Payload may still read the file.
|
|
126
|
+
*/
|
|
127
|
+
const REFILE_CODES = new Set(['link_empty', 'link_not_found', 'link_refused', 'link_unreachable']);
|
|
128
|
+
/** Start a job for the target's file: by link when VocalStack can fetch it, otherwise (or when `asFile`) by sending the bytes. */
|
|
129
|
+
export async function startJob(req, api, target, call, asFile = false) {
|
|
130
|
+
const url = await target.url();
|
|
131
|
+
if (!url)
|
|
132
|
+
throw new Error('There is no audio file here.');
|
|
133
|
+
const tx = !asFile && isPublicURL(url)
|
|
134
|
+
? await api.transcribeURL(url, call)
|
|
135
|
+
: await api.transcribeFile(await fetchFile(req, url), decodeURIComponent(new URL(url).pathname.split('/').pop() || target.fileName), call);
|
|
136
|
+
if (!tx.job)
|
|
137
|
+
throw new Error('VocalStack did not start a job for this file.');
|
|
138
|
+
return tx;
|
|
139
|
+
}
|
|
140
|
+
/** Sends the file's bytes in place of a link VocalStack could not use; the new job is saved on the target. */
|
|
141
|
+
export function refileWith(req, api, target, collection, spokenLanguage) {
|
|
142
|
+
return async () => {
|
|
143
|
+
const tx = await startJob(req, api, target, { idempotencyKey: `payload:${collection}:${target.id}:${randomUUID()}`, name: target.name, spokenLanguage }, true);
|
|
144
|
+
const vocalstack = await target.save({ error: null, status: 'processing', transcriptionId: tx.id });
|
|
145
|
+
return { phase: tx.job.state, progress: 0, status: 'processing', vocalstack };
|
|
146
|
+
};
|
|
147
|
+
}
|
|
116
148
|
/**
|
|
117
149
|
* Where a job stands, saving the outcome on the document once it is over: the
|
|
118
|
-
* whole transcript when done, the reason when it failed.
|
|
150
|
+
* whole transcript when done, the reason when it failed. With `refile`, a job whose
|
|
151
|
+
* link failed (see REFILE_CODES) is started again from the file's bytes.
|
|
119
152
|
*/
|
|
120
|
-
export async function checkJob(api, target, transcriptionId
|
|
153
|
+
export async function checkJob(api, target, transcriptionId, refile,
|
|
154
|
+
/** Read the sentences so far while it runs (for a page following it). */
|
|
155
|
+
withPartial = true) {
|
|
121
156
|
let job;
|
|
122
157
|
try {
|
|
123
158
|
job = await api.job(transcriptionId);
|
|
@@ -131,13 +166,25 @@ export async function checkJob(api, target, transcriptionId) {
|
|
|
131
166
|
}
|
|
132
167
|
if (job.state === 'stopped' || (job.state === 'failed' && job.errorCode === 'stopped'))
|
|
133
168
|
return restore(target);
|
|
169
|
+
if (job.state === 'failed' && refile && job.errorCode && REFILE_CODES.has(job.errorCode)) {
|
|
170
|
+
let again = refiling.get(transcriptionId);
|
|
171
|
+
if (!again) {
|
|
172
|
+
again = refile();
|
|
173
|
+
refiling.set(transcriptionId, again);
|
|
174
|
+
void again.catch(() => undefined).then(() => setTimeout(() => refiling.delete(transcriptionId), 60_000));
|
|
175
|
+
}
|
|
176
|
+
// Reading or sending the file failed too: report the link's reason, as before.
|
|
177
|
+
const started = await again.catch(() => undefined);
|
|
178
|
+
if (started)
|
|
179
|
+
return started;
|
|
180
|
+
}
|
|
134
181
|
if (job.state === 'failed' || job.state === 'cropping') {
|
|
135
182
|
const error = job.state === 'cropping' ? 'VocalStack is waiting for a crop window; open the transcription in VocalStack.' : (job.error ?? 'The transcription failed.');
|
|
136
183
|
return { error, status: 'failed', vocalstack: await target.save({ error, status: 'failed' }) };
|
|
137
184
|
}
|
|
138
185
|
if (job.state !== 'done') {
|
|
139
186
|
const progress = job.state === 'fetching' ? (job.progress.phasePct ?? 0) : job.progress.pct;
|
|
140
|
-
if (job.state !== 'transcribing')
|
|
187
|
+
if (job.state !== 'transcribing' || !withPartial)
|
|
141
188
|
return { phase: job.progress.phase ?? job.state, progress, status: 'processing' };
|
|
142
189
|
// Sentences are readable while the job runs; send what is there so far.
|
|
143
190
|
const partial = await api.transcript(transcriptionId).then(toSentences, () => undefined);
|
|
@@ -200,17 +247,12 @@ export function transcribeEndpoints(collection, options, rowFields) {
|
|
|
200
247
|
return target;
|
|
201
248
|
if (target.data.status === 'processing')
|
|
202
249
|
return json({ status: 'processing', vocalstack: target.data });
|
|
203
|
-
|
|
204
|
-
if (!url)
|
|
250
|
+
if (!(await target.url()))
|
|
205
251
|
return json({ error: 'There is no audio file here.' }, 400);
|
|
206
252
|
const api = new VocalStackAPI(apiKey, apiURL);
|
|
207
253
|
const call = { idempotencyKey: `payload:${collection}:${id}:${randomUUID()}`, name: target.name, spokenLanguage: options.spokenLanguage };
|
|
208
254
|
try {
|
|
209
|
-
const tx =
|
|
210
|
-
? await api.transcribeURL(url, call)
|
|
211
|
-
: await api.transcribeFile(await fetchFile(req, url), decodeURIComponent(new URL(url).pathname.split('/').pop() || target.fileName), call);
|
|
212
|
-
if (!tx.job)
|
|
213
|
-
throw new Error('VocalStack did not start a job for this file.');
|
|
255
|
+
const tx = await startJob(req, api, target, call);
|
|
214
256
|
const vocalstack = await target.save({ error: null, recordingId: null, status: 'processing', transcriptionId: tx.id });
|
|
215
257
|
return json({ phase: tx.job.state, progress: 0, status: 'processing', vocalstack }, 202);
|
|
216
258
|
}
|
|
@@ -236,7 +278,8 @@ export function transcribeEndpoints(collection, options, rowFields) {
|
|
|
236
278
|
if (!apiKey)
|
|
237
279
|
return json({ code: 'not_connected', error: 'Connect VocalStack first.' }, 409);
|
|
238
280
|
try {
|
|
239
|
-
|
|
281
|
+
const api = new VocalStackAPI(apiKey, apiURL);
|
|
282
|
+
return json(await checkJob(api, target, field.transcriptionId, refileWith(req, api, target, collection, options.spokenLanguage)));
|
|
240
283
|
}
|
|
241
284
|
catch (err) {
|
|
242
285
|
return apiError(err);
|
|
@@ -269,7 +312,7 @@ export function transcribeEndpoints(collection, options, rowFields) {
|
|
|
269
312
|
catch (err) {
|
|
270
313
|
// Too late to stop: the job ended meanwhile, so take its outcome instead.
|
|
271
314
|
if (err instanceof VocalStackAPIError && err.status === 409)
|
|
272
|
-
return json(await checkJob(api, target, transcriptionId).catch(() => restore(target)));
|
|
315
|
+
return json(await checkJob(api, target, transcriptionId, refileWith(req, api, target, collection, options.spokenLanguage)).catch(() => restore(target)));
|
|
273
316
|
return apiError(err);
|
|
274
317
|
}
|
|
275
318
|
},
|
package/dist/exports/client.d.ts
CHANGED
|
@@ -4,3 +4,5 @@ export { SpeechField } from '../components/SpeechField.js';
|
|
|
4
4
|
export { TranscribeButton } from '../components/TranscribeButton.js';
|
|
5
5
|
export { TranscriptField } from '../components/TranscriptField.js';
|
|
6
6
|
export { UpdateNotice } from '../components/UpdateNotice.js';
|
|
7
|
+
export { TranscribeSelected } from '../components/TranscribeSelected.js';
|
|
8
|
+
export { useTranscriptionProgress } from '../components/progress.js';
|
package/dist/exports/client.js
CHANGED
|
@@ -5,3 +5,5 @@ export { SpeechField } from '../components/SpeechField.js';
|
|
|
5
5
|
export { TranscribeButton } from '../components/TranscribeButton.js';
|
|
6
6
|
export { TranscriptField } from '../components/TranscriptField.js';
|
|
7
7
|
export { UpdateNotice } from '../components/UpdateNotice.js';
|
|
8
|
+
export { TranscribeSelected } from '../components/TranscribeSelected.js';
|
|
9
|
+
export { useTranscriptionProgress } from '../components/progress.js';
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { bulkEndpoints } from './endpoints/bulk.js';
|
|
1
2
|
import { connectionEndpoints } from './endpoints/connection.js';
|
|
2
3
|
import { refreshAfterRead, speechEndpoints } from './endpoints/speech.js';
|
|
3
4
|
import { streamEndpoint } from './endpoints/stream.js';
|
|
@@ -214,10 +215,23 @@ export const vocalstackPlugin = (options = {}) => (config) => {
|
|
|
214
215
|
? [
|
|
215
216
|
...(collection.endpoints || []),
|
|
216
217
|
...transcribeEndpoints(collection.slug, options, rowFields),
|
|
218
|
+
...bulkEndpoints(collection.slug, options, rowFields, isUpload),
|
|
217
219
|
streamEndpoint(collection.slug, options, rowFields),
|
|
218
220
|
...speechEndpoints(collection.slug, options, rowFields),
|
|
219
221
|
]
|
|
220
222
|
: collection.endpoints,
|
|
223
|
+
admin: enabled && options.bulkTranscribe !== false
|
|
224
|
+
? {
|
|
225
|
+
...collection.admin,
|
|
226
|
+
components: {
|
|
227
|
+
...collection.admin?.components,
|
|
228
|
+
beforeListTable: [
|
|
229
|
+
...(collection.admin?.components?.beforeListTable ?? []),
|
|
230
|
+
{ clientProps: { collection: collection.slug }, path: '@vocalstack/payload/client#TranscribeSelected' },
|
|
231
|
+
],
|
|
232
|
+
},
|
|
233
|
+
}
|
|
234
|
+
: collection.admin,
|
|
221
235
|
fields,
|
|
222
236
|
hooks: enabled
|
|
223
237
|
? { ...collection.hooks, afterRead: [...(collection.hooks?.afterRead ?? []), readingsAfterRead(options, rowFields, isUpload)] }
|
package/dist/types.d.ts
CHANGED
|
@@ -46,6 +46,12 @@ export type VocalStackPluginOptions = {
|
|
|
46
46
|
* Authenticate there). Needs the dashboard's /connect flow; until then, paste a key.
|
|
47
47
|
*/
|
|
48
48
|
oneClickConnect?: boolean;
|
|
49
|
+
/**
|
|
50
|
+
* A Transcribe button above each list of transcribable documents, for the rows selected
|
|
51
|
+
* there; the list also saves transcripts that finished while no one had them open.
|
|
52
|
+
* Default: on.
|
|
53
|
+
*/
|
|
54
|
+
bulkTranscribe?: boolean;
|
|
49
55
|
/**
|
|
50
56
|
* Check npm for a newer version of this plugin (from the server, at most every
|
|
51
57
|
* 6 hours) and say so in the admin: in the nav and on Settings → VocalStack.
|
|
@@ -333,3 +339,46 @@ export type SpeechResponse = {
|
|
|
333
339
|
more?: boolean;
|
|
334
340
|
vocalstack: VocalStackFieldData;
|
|
335
341
|
};
|
|
342
|
+
/** POST /api/<collection>/vocalstack/transcribe-many */
|
|
343
|
+
export type BulkTranscribeResponse = {
|
|
344
|
+
/** Files that could not be started, with why. */
|
|
345
|
+
failed: {
|
|
346
|
+
error: string;
|
|
347
|
+
id: number | string;
|
|
348
|
+
}[];
|
|
349
|
+
/** Files left alone because VocalStack refused to start more (see `stopped`). */
|
|
350
|
+
notStarted: number;
|
|
351
|
+
skipped: {
|
|
352
|
+
done: number;
|
|
353
|
+
noAudio: number;
|
|
354
|
+
processing: number;
|
|
355
|
+
};
|
|
356
|
+
started: number;
|
|
357
|
+
/** VocalStack refused every further start: not connected, out of credit, a cap or a rate limit. */
|
|
358
|
+
stopped?: {
|
|
359
|
+
code?: string;
|
|
360
|
+
error: string;
|
|
361
|
+
};
|
|
362
|
+
};
|
|
363
|
+
/** POST /api/<collection>/vocalstack/settle */
|
|
364
|
+
export type BulkSettleResponse = {
|
|
365
|
+
/** Jobs that failed since the last settle. */
|
|
366
|
+
failed: number;
|
|
367
|
+
/** Jobs saved as done since the last settle. */
|
|
368
|
+
finished: number;
|
|
369
|
+
/** Where each running job stands, by document (one entry per audio file). */
|
|
370
|
+
jobs: JobProgress[];
|
|
371
|
+
/** Jobs still running. */
|
|
372
|
+
processing: number;
|
|
373
|
+
};
|
|
374
|
+
/** One running job, as the list shows it. */
|
|
375
|
+
export type JobProgress = {
|
|
376
|
+
/** The document's id. */
|
|
377
|
+
id: number | string;
|
|
378
|
+
/** `queued`, `fetching`, `transcribing`, `finalizing`: what it is doing now. */
|
|
379
|
+
phase: string;
|
|
380
|
+
/** 0–100, of the whole job. */
|
|
381
|
+
progress: number;
|
|
382
|
+
/** The array row, for an audio row. */
|
|
383
|
+
row?: string;
|
|
384
|
+
};
|
package/dist/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const PACKAGE_NAME = "@vocalstack/payload";
|
|
2
|
-
export declare const VERSION = "0.
|
|
2
|
+
export declare const VERSION = "0.11.0";
|
package/dist/version.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vocalstack/payload",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "VocalStack for Payload CMS: transcribe audio, translate it into other languages and read it aloud, kept in your own database and storage.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -50,6 +50,6 @@
|
|
|
50
50
|
},
|
|
51
51
|
"packageManager": "pnpm@10.15.1",
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@vocalstack/js-sdk": "2.
|
|
53
|
+
"@vocalstack/js-sdk": "2.2.0"
|
|
54
54
|
}
|
|
55
55
|
}
|