@vocalstack/payload 0.1.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { connectionEndpoints } from './endpoints/connection.js';
2
+ import { refreshAfterRead, speechEndpoints } from './endpoints/speech.js';
2
3
  import { streamEndpoint } from './endpoints/stream.js';
3
4
  import { transcribeEndpoints } from './endpoints/transcribe.js';
5
+ import { lookupEndpoints, voiceEndpoints } from './endpoints/voices.js';
6
+ import { readingsCollection, readingsSlug } from './readings.js';
4
7
  import { settingsGlobal } from './settings.js';
5
- export { timedTokens, transcriptText } from './text.js';
8
+ export { spokenSentences, timedTokens, transcriptText } from './text.js';
6
9
  const isAudioDoc = (data) => typeof data?.mimeType === 'string' && data.mimeType.startsWith('audio/');
7
10
  /** An upload collection that can hold audio: `audio/*`, a wildcard, or no restriction at all. */
8
11
  function acceptsAudio(collection) {
@@ -59,10 +62,71 @@ function transcriptionFields(enabled, options, target) {
59
62
  { name: 'transcribedAt', type: 'date', ...hidden },
60
63
  // [{ start, end, speaker, text }] in seconds, for captions or a synced player.
61
64
  { name: 'sentences', type: 'json', ...hidden },
65
+ // { [lang]: { translatedAt, sentences } }: the sentences above, translated.
66
+ { name: 'translations', type: 'json', ...hidden },
67
+ // { [lang]: { voice, state, …, sentences } }: translations read aloud, in the reading's timing.
68
+ { name: 'speech', type: 'json', ...hidden },
69
+ // Readings in speakers' cloned voices, or in stock ones (set from the translations panel).
70
+ { name: 'voices', type: 'select', defaultValue: 'synthetic', options: ['synthetic', 'cloned'], ...hidden },
71
+ ...(enabled
72
+ ? [
73
+ {
74
+ name: 'vocalstackSpeech',
75
+ type: 'ui',
76
+ admin: {
77
+ components: { Field: { clientProps: { field: target.field }, path: '@vocalstack/payload/client#SpeechField' } },
78
+ condition: (_, siblingData) => siblingData?.status === 'done',
79
+ },
80
+ },
81
+ ]
82
+ : []),
83
+ ],
84
+ },
85
+ ];
86
+ }
87
+ /** A person's cloned voice: the panel, and what VocalStack says about the voice. */
88
+ function voiceFields(enabled) {
89
+ return [
90
+ ...(enabled
91
+ ? [
92
+ {
93
+ name: 'vocalstackVoicePanel',
94
+ type: 'ui',
95
+ admin: { components: { Field: '@vocalstack/payload/client#VoiceField' }, position: 'sidebar' },
96
+ },
97
+ ]
98
+ : []),
99
+ {
100
+ name: 'vocalstackVoice',
101
+ type: 'group',
102
+ label: 'Voice',
103
+ admin: { hidden: true },
104
+ fields: [
105
+ { name: 'voiceId', type: 'text', ...hidden },
106
+ { name: 'state', type: 'select', defaultValue: 'none', options: ['none', 'training', 'ready', 'failed'], ...hidden },
107
+ { name: 'progress', type: 'number', ...hidden },
108
+ { name: 'error', type: 'text', ...hidden },
109
+ { name: 'sampleS', type: 'number', ...hidden },
110
+ { name: 'consentAt', type: 'date', ...hidden },
111
+ { name: 'createdAt', type: 'date', ...hidden },
62
112
  ],
63
113
  },
64
114
  ];
65
115
  }
116
+ /** Readings still being made when a document is read: brought up to date after the response, for whoever reads next. */
117
+ const readingsAfterRead = (options, rowFields, isUpload) => ({ collection, doc, req }) => {
118
+ if (!doc?.id)
119
+ return doc;
120
+ if (isUpload)
121
+ refreshAfterRead(req.payload, collection.slug, options, rowFields, doc.id, doc.vocalstack);
122
+ for (const { field } of rowFields) {
123
+ for (const row of doc[field] ?? []) {
124
+ if (row?.id && row.vocalstack && typeof row.vocalstack === 'object')
125
+ refreshAfterRead(req.payload, collection.slug, options, rowFields, doc.id, row.vocalstack, { field, row: row.id });
126
+ }
127
+ }
128
+ return doc;
129
+ };
66
130
  /** Add fields to the named array, looking through unnamed containers (rows, collapsibles, unnamed tabs). */
67
131
  function addToArray(fields, name, extra) {
68
132
  let found = false;
@@ -84,11 +148,25 @@ function addToArray(fields, name, extra) {
84
148
  export const vocalstackPlugin = (options = {}) => (config) => {
85
149
  const enabled = options.enabled !== false;
86
150
  const collections = config.collections ?? [];
87
- const uploads = new Set(options.collections ?? collections.filter(acceptsAudio).map((c) => c.slug));
151
+ const readings = readingsSlug(options);
152
+ const uploads = new Set(options.collections ?? collections.filter((c) => c.slug !== readings && acceptsAudio(c)).map((c) => c.slug));
88
153
  const audioFields = options.audioFields ?? [];
154
+ const voices = options.voices ?? [];
155
+ for (const v of voices) {
156
+ if (!collections.some((c) => c.slug === v.collection))
157
+ throw new Error(`vocalstackPlugin: no collection "${v.collection}" for voices`);
158
+ }
89
159
  return {
90
160
  ...config,
91
- collections: collections.map((collection) => {
161
+ collections: [...collections, ...(readings && !collections.some((c) => c.slug === readings) ? [(options.readings && options.readings.overrides ? options.readings.overrides : (c) => c)(readingsCollection(readings))] : [])].map((original) => {
162
+ const voice = voices.find((v) => v.collection === original.slug);
163
+ const collection = voice
164
+ ? {
165
+ ...original,
166
+ endpoints: enabled ? [...(original.endpoints || []), ...voiceEndpoints(voice, options)] : original.endpoints,
167
+ fields: [...original.fields, ...voiceFields(enabled)],
168
+ }
169
+ : original;
92
170
  const rowFields = audioFields.filter((f) => f.collection === collection.slug);
93
171
  const isUpload = uploads.has(collection.slug);
94
172
  if (!isUpload && !rowFields.length)
@@ -103,11 +181,21 @@ export const vocalstackPlugin = (options = {}) => (config) => {
103
181
  }
104
182
  return {
105
183
  ...collection,
106
- endpoints: enabled ? [...(collection.endpoints || []), ...transcribeEndpoints(collection.slug, options, rowFields), streamEndpoint(collection.slug, options, rowFields)] : collection.endpoints,
184
+ endpoints: enabled
185
+ ? [
186
+ ...(collection.endpoints || []),
187
+ ...transcribeEndpoints(collection.slug, options, rowFields),
188
+ streamEndpoint(collection.slug, options, rowFields),
189
+ ...speechEndpoints(collection.slug, options, rowFields),
190
+ ]
191
+ : collection.endpoints,
107
192
  fields,
193
+ hooks: enabled
194
+ ? { ...collection.hooks, afterRead: [...(collection.hooks?.afterRead ?? []), readingsAfterRead(options, rowFields, isUpload)] }
195
+ : collection.hooks,
108
196
  };
109
197
  }),
110
- endpoints: enabled ? [...(config.endpoints ?? []), ...connectionEndpoints(options)] : config.endpoints,
198
+ endpoints: enabled ? [...(config.endpoints ?? []), ...connectionEndpoints(options), ...lookupEndpoints(options)] : config.endpoints,
111
199
  globals: [...(config.globals ?? []), settingsGlobal(options)],
112
200
  };
113
201
  };
@@ -0,0 +1,17 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { ListenerOptions, VocalStackPluginOptions } from './types.js';
3
+ import { type Languages } from './api.js';
4
+ /** The most languages one recording is translated or read into, besides its spoken one (VocalStack's limit). */
5
+ export declare const LANGUAGE_LIMIT = 10;
6
+ /**
7
+ * What VocalStack translates and reads aloud: asked now and then, and remembered. While
8
+ * VocalStack cannot be asked, the last answer (or the list shipped with the plugin) stands in,
9
+ * so a site never loses its language list to an outage.
10
+ */
11
+ export declare function languageList(req: PayloadRequest, options: VocalStackPluginOptions): Promise<Languages>;
12
+ /** The listener options, or nothing when listeners may not ask for languages. */
13
+ export declare const listenerOptions: (options: VocalStackPluginOptions) => ListenerOptions | undefined;
14
+ /** The languages listeners are offered: VocalStack's, narrowed to the site's own list when it has one. */
15
+ export declare function forListeners(all: Languages, listeners: ListenerOptions): Languages;
16
+ /** Whether this visitor may ask for another new language now; counts it when so. */
17
+ export declare function allowNewLanguage(req: PayloadRequest, perHour: number): boolean;
@@ -0,0 +1,64 @@
1
+ import { DEFAULT_API_URL, VocalStackAPI } from './api.js';
2
+ import { LANGUAGES_SNAPSHOT } from './languagesSnapshot.js';
3
+ import { resolveAPIKey } from './settings.js';
4
+ /** The most languages one recording is translated or read into, besides its spoken one (VocalStack's limit). */
5
+ export const LANGUAGE_LIMIT = 10;
6
+ let cached;
7
+ const FRESH_MS = 3600_000;
8
+ /**
9
+ * What VocalStack translates and reads aloud: asked now and then, and remembered. While
10
+ * VocalStack cannot be asked, the last answer (or the list shipped with the plugin) stands in,
11
+ * so a site never loses its language list to an outage.
12
+ */
13
+ export async function languageList(req, options) {
14
+ if (cached && Date.now() - cached.at < FRESH_MS)
15
+ return cached.value;
16
+ try {
17
+ const apiKey = await resolveAPIKey(req, options);
18
+ if (!apiKey)
19
+ return cached?.value ?? LANGUAGES_SNAPSHOT;
20
+ const value = await new VocalStackAPI(apiKey, options.apiURL ?? DEFAULT_API_URL).languages();
21
+ if (value?.languages?.length)
22
+ cached = { at: Date.now(), value };
23
+ return cached?.value ?? LANGUAGES_SNAPSHOT;
24
+ }
25
+ catch {
26
+ // Ask again in a few minutes rather than on every request.
27
+ if (cached)
28
+ cached = { ...cached, at: Date.now() - FRESH_MS + 300_000 };
29
+ return cached?.value ?? LANGUAGES_SNAPSHOT;
30
+ }
31
+ }
32
+ /** The listener options, or nothing when listeners may not ask for languages. */
33
+ export const listenerOptions = (options) => !options.listeners ? undefined : options.listeners === true ? {} : options.listeners;
34
+ /** The languages listeners are offered: VocalStack's, narrowed to the site's own list when it has one. */
35
+ export function forListeners(all, listeners) {
36
+ if (!listeners.languages?.length)
37
+ return all;
38
+ const allowed = new Set(listeners.languages.map((l) => l.toLowerCase()));
39
+ const languages = all.languages.filter((l) => allowed.has(l.code));
40
+ return {
41
+ languages,
42
+ translation: languages.filter((l) => l.translation).map((l) => l.code),
43
+ voice: languages.filter((l) => l.voice).map((l) => l.code),
44
+ };
45
+ }
46
+ /** New languages asked for, by visitor, this hour (on this server). */
47
+ const asked = new Map();
48
+ /** Whether this visitor may ask for another new language now; counts it when so. */
49
+ export function allowNewLanguage(req, perHour) {
50
+ const ip = (req.headers.get('x-forwarded-for')?.split(',')[0] ?? req.headers.get('x-real-ip') ?? 'unknown').trim();
51
+ const now = Date.now();
52
+ const recent = (asked.get(ip) ?? []).filter((t) => now - t < 3600_000);
53
+ if (recent.length >= perHour) {
54
+ asked.set(ip, recent);
55
+ return false;
56
+ }
57
+ recent.push(now);
58
+ asked.set(ip, recent);
59
+ if (asked.size > 5000)
60
+ for (const [k, v] of asked)
61
+ if (!v.some((t) => now - t < 3600_000))
62
+ asked.delete(k);
63
+ return true;
64
+ }
@@ -0,0 +1,2 @@
1
+ import type { Languages } from './api.js';
2
+ export declare const LANGUAGES_SNAPSHOT: Languages;
@@ -0,0 +1,112 @@
1
+ /**
2
+ * VocalStack's languages as they were when this version was built: what listeners are
3
+ * offered while VocalStack cannot be asked (it is down, or not connected yet).
4
+ * [code, name, native name, read aloud]
5
+ */
6
+ const ROWS = [
7
+ ["af", "Afrikaans", "Afrikaans", false],
8
+ ["am", "Amharic", "አማርኛ", false],
9
+ ["ar", "Arabic", "العربية", true],
10
+ ["as", "Assamese", "অসমীয়া", false],
11
+ ["az", "Azerbaijani", "Azərbaycan dili", false],
12
+ ["ba", "Bashkir", "Башҡортса", false],
13
+ ["be", "Belarusian", "Беларуская", false],
14
+ ["bg", "Bulgarian", "Български", true],
15
+ ["bn", "Bengali", "বাংলা", true],
16
+ ["bo", "Tibetan", "བོད་སྐད་", false],
17
+ ["br", "Breton", "Brezhoneg", false],
18
+ ["bs", "Bosnian", "Bosanski", false],
19
+ ["ca", "Catalan", "Català", true],
20
+ ["cs", "Czech", "Čeština", true],
21
+ ["cy", "Welsh", "Cymraeg", true],
22
+ ["da", "Danish", "Dansk", true],
23
+ ["de", "German", "Deutsch", true],
24
+ ["el", "Greek", "Ελληνικά", true],
25
+ ["en", "English", "English", true],
26
+ ["es", "Spanish", "Español", true],
27
+ ["et", "Estonian", "Eesti", true],
28
+ ["eu", "Basque", "Euskara", true],
29
+ ["fa", "Persian", "فارسی", true],
30
+ ["fi", "Finnish", "Suomi", true],
31
+ ["fo", "Faroese", "Føroyskt", false],
32
+ ["fr", "French", "Français", true],
33
+ ["gl", "Galician", "Galego", false],
34
+ ["gu", "Gujarati", "ગુજરાતી", false],
35
+ ["ha", "Hausa", "Hausa", false],
36
+ ["haw", "Hawaiian", "ʻŌlelo Hawaiʻi", false],
37
+ ["he", "Hebrew", "עברית", true],
38
+ ["hi", "Hindi", "हिन्दी", true],
39
+ ["hr", "Croatian", "Hrvatski", true],
40
+ ["ht", "Haitian Creole", "Kreyòl ayisyen", false],
41
+ ["hu", "Hungarian", "Magyar", true],
42
+ ["hy", "Armenian", "Հայերեն", true],
43
+ ["id", "Indonesian", "Bahasa Indonesia", true],
44
+ ["is", "Icelandic", "Íslenska", true],
45
+ ["it", "Italian", "Italiano", true],
46
+ ["ja", "Japanese", "日本語", true],
47
+ ["jw", "Javanese", "Basa Jawa", false],
48
+ ["ka", "Georgian", "ქართული", true],
49
+ ["kk", "Kazakh", "Қазақ тілі", true],
50
+ ["km", "Khmer", "ខ្មែរ", false],
51
+ ["kn", "Kannada", "ಕನ್ನಡ", false],
52
+ ["ko", "Korean", "한국어", true],
53
+ ["la", "Latin", "Latina", false],
54
+ ["lb", "Luxembourgish", "Lëtzebuergesch", true],
55
+ ["ln", "Lingala", "Lingála", false],
56
+ ["lo", "Lao", "ລາວ", false],
57
+ ["lt", "Lithuanian", "Lietuvių", true],
58
+ ["lv", "Latvian", "Latviešu", true],
59
+ ["mg", "Malagasy", "Malagasy", false],
60
+ ["mi", "Māori", "Te Reo Māori", false],
61
+ ["mk", "Macedonian", "Македонски", false],
62
+ ["ml", "Malayalam", "മലയാളം", true],
63
+ ["mn", "Mongolian", "Монгол", false],
64
+ ["mr", "Marathi", "मराठी", true],
65
+ ["ms", "Malay", "Bahasa Melayu", false],
66
+ ["mt", "Maltese", "Malti", false],
67
+ ["my", "Burmese", "မြန်မာစာ", false],
68
+ ["ne", "Nepali", "नेपाली", true],
69
+ ["nl", "Dutch", "Nederlands", true],
70
+ ["nn", "Norwegian Nynorsk", "Nynorsk", false],
71
+ ["no", "Norwegian", "Norsk", true],
72
+ ["oc", "Occitan", "Occitan", false],
73
+ ["pa", "Punjabi", "ਪੰਜਾਬੀ", false],
74
+ ["pl", "Polish", "Polski", true],
75
+ ["ps", "Pashto", "پښتو", false],
76
+ ["pt", "Portuguese", "Português", true],
77
+ ["ro", "Romanian", "Română", true],
78
+ ["ru", "Russian", "Русский", true],
79
+ ["sa", "Sanskrit", "संस्कृतम्", false],
80
+ ["sd", "Sindhi", "سنڌي", false],
81
+ ["si", "Sinhala", "සිංහල", false],
82
+ ["sk", "Slovak", "Slovenčina", true],
83
+ ["sl", "Slovenian", "Slovenščina", true],
84
+ ["sn", "Shona", "chiShona", false],
85
+ ["so", "Somali", "Soomaali", false],
86
+ ["sq", "Albanian", "Shqip", true],
87
+ ["sr", "Serbian", "Српски", true],
88
+ ["su", "Sundanese", "Basa Sunda", false],
89
+ ["sv", "Swedish", "Svenska", true],
90
+ ["sw", "Swahili", "Kiswahili", true],
91
+ ["ta", "Tamil", "தமிழ்", false],
92
+ ["te", "Telugu", "తెలుగు", true],
93
+ ["tg", "Tajik", "Тоҷикӣ", false],
94
+ ["th", "Thai", "ไทย", true],
95
+ ["tk", "Turkmen", "Türkmençe", false],
96
+ ["tl", "Tagalog", "Tagalog", false],
97
+ ["tr", "Turkish", "Türkçe", true],
98
+ ["tt", "Tatar", "Татарча", false],
99
+ ["uk", "Ukrainian", "Українська", true],
100
+ ["ur", "Urdu", "اردو", true],
101
+ ["uz", "Uzbek", "Oʻzbekcha", false],
102
+ ["vi", "Vietnamese", "Tiếng Việt", true],
103
+ ["yi", "Yiddish", "ייִדיש", false],
104
+ ["yo", "Yoruba", "Yorùbá", false],
105
+ ["yue", "Cantonese", "粵語", false],
106
+ ["zh", "Chinese", "中文", true],
107
+ ];
108
+ export const LANGUAGES_SNAPSHOT = {
109
+ languages: ROWS.map(([code, name, native, voice]) => ({ code, name, native, translation: true, voice })),
110
+ translation: ROWS.map(([code]) => code),
111
+ voice: ROWS.filter(([, , , voice]) => voice).map(([code]) => code),
112
+ };
@@ -0,0 +1,6 @@
1
+ import type { CollectionConfig, CollectionSlug } from 'payload';
2
+ import type { VocalStackPluginOptions } from './types.js';
3
+ /** The upload collection finished readings are saved in, or none. */
4
+ export declare const readingsSlug: (options: VocalStackPluginOptions) => CollectionSlug | undefined;
5
+ /** Spoken readings, kept as MP3 uploads so they are served from the site's own storage. */
6
+ export declare const readingsCollection: (slug: CollectionSlug) => CollectionConfig;
@@ -0,0 +1,24 @@
1
+ /** The upload collection finished readings are saved in, or none. */
2
+ export const readingsSlug = (options) => options.readings === false ? undefined : (options.readings?.slug ?? 'vocalstack-readings');
3
+ /** Spoken readings, kept as MP3 uploads so they are served from the site's own storage. */
4
+ export const readingsCollection = (slug) => ({
5
+ slug,
6
+ labels: { plural: 'Readings', singular: 'Reading' },
7
+ admin: {
8
+ description: 'Translations read aloud, saved from VocalStack once they are ready. Made and removed from the transcript.',
9
+ group: 'VocalStack',
10
+ useAsTitle: 'filename',
11
+ },
12
+ access: {
13
+ create: ({ req }) => Boolean(req.user),
14
+ delete: ({ req }) => Boolean(req.user),
15
+ read: () => true,
16
+ update: ({ req }) => Boolean(req.user),
17
+ },
18
+ upload: { mimeTypes: ['audio/mpeg'] },
19
+ fields: [
20
+ { name: 'lang', type: 'text', admin: { readOnly: true } },
21
+ { name: 'recordingId', type: 'text', admin: { readOnly: true } },
22
+ { name: 'voice', type: 'text', admin: { readOnly: true } },
23
+ ],
24
+ });
package/dist/text.d.ts CHANGED
@@ -20,3 +20,10 @@ export declare function attachWords<T extends TranscriptSentence>(sentences: T[]
20
20
  * differ, the times are spread evenly across the sentence.
21
21
  */
22
22
  export declare function timedTokens(s: TranscriptSentence): TranscriptWord[];
23
+ /**
24
+ * Translated sentences in the timing of their spoken track. The track keeps each
25
+ * sentence where it was said, unless the one before still runs: then it follows it
26
+ * after a short pause. Each sentence's words come from the clip's word times, paired
27
+ * with the translated text; when they do not pair up, they are spread evenly.
28
+ */
29
+ export declare function spokenSentences(translated: TranscriptSentence[], clipDur: Record<string, number>, wordTimes?: Record<string, [number, number][]>): TranscriptSentence[];
package/dist/text.js CHANGED
@@ -50,3 +50,29 @@ export function timedTokens(s) {
50
50
  const span = (s.end - s.start) / tokens.length;
51
51
  return tokens.map((t, i) => [round(s.start + i * span), round(s.start + (i + 1) * span), t]);
52
52
  }
53
+ /** The pause VocalStack leaves between two spoken sentences, at least. */
54
+ const SPOKEN_GAP_S = 0.15;
55
+ /**
56
+ * Translated sentences in the timing of their spoken track. The track keeps each
57
+ * sentence where it was said, unless the one before still runs: then it follows it
58
+ * after a short pause. Each sentence's words come from the clip's word times, paired
59
+ * with the translated text; when they do not pair up, they are spread evenly.
60
+ */
61
+ export function spokenSentences(translated, clipDur, wordTimes = {}) {
62
+ let cursor = 0;
63
+ const out = [];
64
+ for (const s of [...translated].sort((a, b) => (a.id ?? 0) - (b.id ?? 0))) {
65
+ const dur = s.id === undefined ? undefined : clipDur[String(s.id)];
66
+ if (!dur)
67
+ continue;
68
+ const at = Math.max(s.start, cursor);
69
+ cursor = at + dur + SPOKEN_GAP_S;
70
+ const tokens = s.text.trim().split(/\s+/).filter(Boolean);
71
+ const times = wordTimes[String(s.id)] ?? [];
72
+ const words = times.length === tokens.length
73
+ ? tokens.map((t, i) => [round(at + times[i][0]), round(at + times[i][1]), t])
74
+ : tokens.map((t, i) => [round(at + (i * dur) / tokens.length), round(at + ((i + 1) * dur) / tokens.length), t]);
75
+ out.push({ ...s, end: round(at + dur), start: round(at), words });
76
+ }
77
+ return out;
78
+ }
package/dist/types.d.ts CHANGED
@@ -1,5 +1,21 @@
1
- import type { CollectionSlug, PayloadRequest, TypeWithID } from 'payload';
1
+ import type { CollectionConfig, CollectionSlug, PayloadRequest, TypeWithID } from 'payload';
2
2
  export type VocalStackPluginOptions = {
3
+ /**
4
+ * Where finished spoken readings are kept: the plugin downloads each one's MP3
5
+ * once and saves it as an upload here, so listeners are served from your
6
+ * storage and VocalStack is not asked again. Default: an upload collection
7
+ * `vocalstack-readings` the plugin adds (point your storage adapter at it).
8
+ * `false` streams readings from VocalStack instead.
9
+ *
10
+ * `overrides` adjusts the added collection (access, labels, admin, upload
11
+ * options). A host may instead define its own upload collection with that slug;
12
+ * the plugin then uses it as it is. It needs to accept `audio/mpeg` and have text
13
+ * fields `lang`, `recordingId` and `voice`.
14
+ */
15
+ readings?: false | {
16
+ overrides?: (collection: CollectionConfig) => CollectionConfig;
17
+ slug?: CollectionSlug;
18
+ };
3
19
  /** Turn the plugin off without removing it (fields stay in the schema). */
4
20
  enabled?: boolean;
5
21
  /**
@@ -45,6 +61,107 @@ export type VocalStackPluginOptions = {
45
61
  access?: (args: {
46
62
  req: PayloadRequest;
47
63
  }) => boolean | Promise<boolean>;
64
+ /**
65
+ * Collections of people (speakers, presenters) that each get a cloned VocalStack voice:
66
+ * made from a stretch of a recording they speak in, or from a sample, with their permission.
67
+ */
68
+ voices?: VoiceCollectionConfig[];
69
+ /**
70
+ * Let the site's visitors ask for a transcript in their own language: it is translated,
71
+ * read aloud where VocalStack has a voice for it, and kept on the document (and the
72
+ * readings collection) like an editor's. Off by default. `true` allows every language
73
+ * VocalStack translates; see {@link ListenerOptions}.
74
+ */
75
+ listeners?: boolean | ListenerOptions;
76
+ /**
77
+ * Whether a transcript is read in its speakers' cloned voices or in synthetic ones, decided by
78
+ * the site (e.g. from the person speaking: `cloned` when they agreed to voice cloning). Answer
79
+ * nothing to leave it to the transcript's own toggle. When set, the toggle is not shown.
80
+ */
81
+ voiceMode?: (args: {
82
+ collection: CollectionSlug;
83
+ doc: Record<string, unknown>;
84
+ req: PayloadRequest;
85
+ row?: ArrayRow;
86
+ }) => Promise<undefined | VoiceMode> | undefined | VoiceMode;
87
+ };
88
+ export type ListenerOptions = {
89
+ /** Languages visitors may ask for. Default: every language VocalStack translates. */
90
+ languages?: string[];
91
+ /** Read new languages aloud too, where VocalStack has a voice for them. Default `true`. */
92
+ speak?: boolean;
93
+ /** Who may ask for a new language. Default: anyone who may read the document. */
94
+ access?: (args: {
95
+ lang: string;
96
+ req: PayloadRequest;
97
+ }) => boolean | Promise<boolean>;
98
+ /** New languages one visitor (by IP address) may ask for in an hour, on this server. Default 10. */
99
+ perHour?: number;
100
+ };
101
+ export type VoiceCollectionConfig = {
102
+ collection: CollectionSlug;
103
+ /** The voice's name in VocalStack. Default: the collection's `useAsTitle` field, else `name`. */
104
+ name?: (args: {
105
+ doc: Record<string, unknown>;
106
+ }) => string;
107
+ /** Transcribed recordings this person speaks in, offered as the sample to clone from. */
108
+ recordings?: (args: {
109
+ doc: Record<string, unknown>;
110
+ req: PayloadRequest;
111
+ }) => Promise<VoiceSource[]> | VoiceSource[];
112
+ };
113
+ /** A transcribed recording to take a voice sample from. */
114
+ export type VoiceSource = {
115
+ label: string;
116
+ recordingId: string;
117
+ sentences?: TranscriptSentence[];
118
+ };
119
+ export type VoiceState = 'failed' | 'none' | 'ready' | 'training';
120
+ /** The `vocalstackVoice` group on a voice collection's documents. */
121
+ export type VoiceFieldData = {
122
+ consentAt?: null | string;
123
+ createdAt?: null | string;
124
+ error?: null | string;
125
+ progress?: null | number;
126
+ sampleS?: null | number;
127
+ state?: null | VoiceState;
128
+ voiceId?: null | string;
129
+ };
130
+ export type Translation = {
131
+ /** The transcript's sentences (same ids and times), their text translated. */
132
+ sentences: TranscriptSentence[];
133
+ translatedAt: null | string;
134
+ /**
135
+ * Asked for and not finished: the server carries on translating (when the document is
136
+ * read, or its progress asked for) until every sentence is done, with no one watching.
137
+ */
138
+ pending?: boolean;
139
+ /** Why translating stopped, when it failed for good. */
140
+ error?: null | string;
141
+ requestedAt?: null | string;
142
+ };
143
+ /** `translating`: asked for, waiting for its translation to finish before VocalStack reads it. */
144
+ export type SpeechState = 'failed' | 'queued' | 'running' | 'sealed' | 'translating';
145
+ export type Speech = {
146
+ /** While it is made: how many sentences have been voiced so far. */
147
+ done?: null | number;
148
+ durationS?: null | number;
149
+ error?: null | string;
150
+ renderedAt?: null | string;
151
+ requestedAt: string;
152
+ /** Once sealed: the translated sentences in the spoken track's timing, with their words. */
153
+ sentences?: null | TranscriptSentence[];
154
+ state: SpeechState;
155
+ /** Read in speakers' cloned voices, or in stock (synthetic) ones. */
156
+ cast?: null | VoiceMode;
157
+ /** VocalStack's key for the voices it is read in (e.g. `cast:-1=M1`); `null` until VocalStack says. */
158
+ voice: null | string;
159
+ /** Once sealed: the reading's MP3, saved once in the readings upload collection and served from there. */
160
+ audio?: null | {
161
+ filename?: null | string;
162
+ id: number | string;
163
+ url: string;
164
+ };
48
165
  };
49
166
  export type ArrayRow = Record<string, unknown> & {
50
167
  id?: null | string;
@@ -84,7 +201,15 @@ export type VocalStackFieldData = {
84
201
  transcript?: null | string;
85
202
  transcriptionId?: null | string;
86
203
  transcribedAt?: null | string;
204
+ /** By language code. */
205
+ translations?: null | Record<string, Translation>;
206
+ /** Spoken translations, by language code. */
207
+ speech?: null | Record<string, Speech>;
208
+ /** The voices readings of this transcript are made in. Default `synthetic`. */
209
+ voices?: null | VoiceMode;
87
210
  };
211
+ /** `cloned`: each speaker's own cloned voice, where they have one; `synthetic`: VocalStack's stock voices. */
212
+ export type VoiceMode = 'cloned' | 'synthetic';
88
213
  /** [start, end, text], seconds. */
89
214
  export type TranscriptWord = [number, number, string];
90
215
  export type TranscriptSentence = {
@@ -121,3 +246,36 @@ export type ConnectionResponse = {
121
246
  /** `options`: the key is in the plugin config; `admin`: connected from the admin panel. */
122
247
  source?: 'admin' | 'options';
123
248
  };
249
+ /** Where one language of a transcript stands, for a listener: what the listen endpoint answers. */
250
+ export type ListenStatus = {
251
+ lang: string;
252
+ /** `ready`: it can be read (and heard, when `speech` is `ready`). `none`: never asked for. */
253
+ state: 'failed' | 'none' | 'ready' | 'translating';
254
+ /** Sentences translated so far, and in all. */
255
+ done: number;
256
+ total: number;
257
+ error?: null | string;
258
+ /** Whether VocalStack reads this language aloud. */
259
+ voice: boolean;
260
+ speech?: {
261
+ /** Sentences read so far (while `reading`). */
262
+ done?: null | number;
263
+ /** The reading's MP3, kept in the site's own storage, once ready. */
264
+ audio?: null | string;
265
+ error?: null | string;
266
+ state: 'failed' | 'reading' | 'ready' | 'waiting';
267
+ } | null;
268
+ /** Changes whenever the translation or the reading does: a cache key for the text and audio. */
269
+ version: string;
270
+ };
271
+ /** What the translate and speak endpoints answer. */
272
+ export type SpeechResponse = {
273
+ /** The voices readings are made in now, and whether the site decides it (`voiceMode`) rather than the toggle. */
274
+ voiceMode?: {
275
+ fixed: boolean;
276
+ mode: VoiceMode;
277
+ };
278
+ /** The translate endpoint ran out of time; call it again to carry on. */
279
+ more?: boolean;
280
+ vocalstack: VocalStackFieldData;
281
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@vocalstack/payload",
3
- "version": "0.1.0",
4
- "description": "VocalStack for Payload CMS: a Transcribe button on every audio upload.",
3
+ "version": "0.4.0",
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",
7
7
  "main": "./dist/index.js",
@@ -45,5 +45,9 @@
45
45
  },
46
46
  "engines": {
47
47
  "node": ">=20"
48
+ },
49
+ "packageManager": "pnpm@10.15.1",
50
+ "dependencies": {
51
+ "@vocalstack/js-sdk": "2.0.0-alpha.1"
48
52
  }
49
53
  }