@jskit-ai/assistant-voice 0.2.86 → 0.2.88
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 +92 -13
- package/examples/conversation/README.md +2 -2
- package/examples/conversation/package.json +9 -9
- package/package.json +10 -5
- package/src/client/ConversationDialog.vue +4 -1
- package/src/client/browser.js +4 -3
- package/src/client/voiceLauncher.js +27 -8
- package/src/server/index.js +7 -2
- package/src/server/standInSpeechEngine.js +116 -0
- package/src/server/voiceCredentials.js +220 -0
- package/src/server/voiceDaemon.js +286 -243
- package/src/server/voiceDaemonHttp.js +24 -0
- package/src/server/voiceProxy.js +31 -7
- package/src/server/voiceProxyConfig.js +25 -23
- package/src/server/voiceSpeechQueue.js +68 -0
- package/src/shared/protocol.js +212 -12
- package/src/server/voiceAccessToken.js +0 -82
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
function requestPathname(request = {}) {
|
|
2
|
+
try {
|
|
3
|
+
return new URL(String(request.url || "/"), "http://voice.local").pathname;
|
|
4
|
+
} catch {
|
|
5
|
+
return "/";
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function writeJsonResponse(response, statusCode, payload) {
|
|
10
|
+
const body = Buffer.from(JSON.stringify(payload));
|
|
11
|
+
response.writeHead(statusCode, {
|
|
12
|
+
"cache-control": "no-store",
|
|
13
|
+
"content-length": String(body.byteLength),
|
|
14
|
+
"content-type": "application/json; charset=utf-8"
|
|
15
|
+
});
|
|
16
|
+
response.end(body);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function refuseUpgrade(socket, status, extraHeaders = "") {
|
|
20
|
+
socket.write(`HTTP/1.1 ${status}\r\nConnection: close\r\n${extraHeaders}\r\n`);
|
|
21
|
+
socket.destroy();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export { refuseUpgrade, requestPathname, writeJsonResponse };
|
package/src/server/voiceProxy.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { WebSocket } from "ws";
|
|
2
2
|
|
|
3
3
|
import {
|
|
4
|
+
VOICE_CATALOGUE_PATH,
|
|
4
5
|
VOICE_MAX_AUDIO_FRAME_BYTES,
|
|
5
6
|
VOICE_MAX_CONTROL_BYTES,
|
|
7
|
+
VOICE_VOICES_PATH,
|
|
6
8
|
assertVoiceAudioFrame,
|
|
7
9
|
parseVoiceClientControl,
|
|
8
10
|
voiceServerMessage
|
|
@@ -39,18 +41,23 @@ function normalizeVoiceCloseMetadata(code, reason) {
|
|
|
39
41
|
});
|
|
40
42
|
}
|
|
41
43
|
|
|
42
|
-
|
|
44
|
+
// The service's HTTP address for a path beside its /v1/voice WebSocket.
|
|
45
|
+
function serviceUrl(config, pathname) {
|
|
46
|
+
const url = new URL(pathname, config.endpoint);
|
|
47
|
+
url.protocol = url.protocol === "wss:" ? "https:" : "http:";
|
|
48
|
+
return url;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function readServiceJson(config, pathname, fetchImpl, isValid) {
|
|
43
52
|
try {
|
|
44
53
|
if (!config?.available) throw new Error("Voice is not configured.");
|
|
45
|
-
const
|
|
46
|
-
url.protocol = url.protocol === "wss:" ? "https:" : "http:";
|
|
47
|
-
const response = await fetchImpl(url, {
|
|
54
|
+
const response = await fetchImpl(serviceUrl(config, pathname), {
|
|
48
55
|
headers: { authorization: `Bearer ${config.token}` }, signal: AbortSignal.timeout(5000)
|
|
49
56
|
});
|
|
50
57
|
if (!response.ok) throw new Error("Voice service refused the catalogue request.");
|
|
51
|
-
const
|
|
52
|
-
if (!
|
|
53
|
-
return
|
|
58
|
+
const body = await response.json();
|
|
59
|
+
if (!isValid(body)) throw new Error("Invalid voice catalogue.");
|
|
60
|
+
return body;
|
|
54
61
|
} catch (cause) {
|
|
55
62
|
// readable-check: allow patched-error - safety invariant: a speech-service failure is a plain 503 error, which the HTTP error handler answers without its text, like every server failure
|
|
56
63
|
throw Object.assign(new Error("Speaking voices could not load. Check the speech service and retry."), {
|
|
@@ -60,6 +67,22 @@ async function readVoiceCatalogue(config, { fetchImpl = fetch } = {}) {
|
|
|
60
67
|
}
|
|
61
68
|
}
|
|
62
69
|
|
|
70
|
+
const isVoiceList = body => Array.isArray(body?.voices) && typeof body.defaultVoice === "string";
|
|
71
|
+
|
|
72
|
+
/** The service's voices and default voice (GET /voices), without opening an audio connection. */
|
|
73
|
+
function readVoiceCatalogue(config, { fetchImpl = fetch } = {}) {
|
|
74
|
+
return readServiceJson(config, VOICE_VOICES_PATH, fetchImpl, isVoiceList);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The service's whole catalogue (GET /v1/catalogue): protocol version, sample
|
|
79
|
+
* rates, recognition models, voices and default voice.
|
|
80
|
+
*/
|
|
81
|
+
function readVoiceServiceCatalogue(config, { fetchImpl = fetch } = {}) {
|
|
82
|
+
return readServiceJson(config, VOICE_CATALOGUE_PATH, fetchImpl,
|
|
83
|
+
body => isVoiceList(body) && Number.isSafeInteger(body.protocolVersion) && Array.isArray(body.recognitionModels));
|
|
84
|
+
}
|
|
85
|
+
|
|
63
86
|
function closeSocket(socket, code, reason) {
|
|
64
87
|
if ([WEBSOCKET_CONNECTING, WEBSOCKET_OPEN].includes(socket?.readyState)) {
|
|
65
88
|
const metadata = normalizeVoiceCloseMetadata(code, reason);
|
|
@@ -235,5 +258,6 @@ function registerVoiceProxyRoute(fastify, {
|
|
|
235
258
|
export {
|
|
236
259
|
closeSocket,
|
|
237
260
|
readVoiceCatalogue,
|
|
261
|
+
readVoiceServiceCatalogue,
|
|
238
262
|
registerVoiceProxyRoute
|
|
239
263
|
};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { readFileSync, statSync } from "node:fs";
|
|
2
|
-
import {
|
|
2
|
+
import { isVoiceClientToken } from "./voiceCredentials.js";
|
|
3
3
|
|
|
4
4
|
function voiceEndpoint(value = "") {
|
|
5
5
|
const endpoint = String(value || "").trim();
|
|
@@ -18,52 +18,54 @@ function voiceEndpoint(value = "") {
|
|
|
18
18
|
return parsed.toString();
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
function voiceClientToken(value = "") {
|
|
22
|
+
const token = String(value || "").trim();
|
|
23
|
+
if (!isVoiceClientToken(token)) {
|
|
24
|
+
throw new Error("The voice credential is malformed: a token is 32 to 1024 base64url, base64 or hex characters.");
|
|
25
|
+
}
|
|
26
|
+
return token;
|
|
27
|
+
}
|
|
28
|
+
|
|
21
29
|
function readVoiceAccessToken(filePath = "") {
|
|
22
30
|
const pathname = String(filePath || "").trim();
|
|
23
31
|
if (!pathname) {
|
|
24
32
|
return "";
|
|
25
33
|
}
|
|
26
34
|
const metadata = statSync(pathname);
|
|
27
|
-
if (!metadata.isFile() || metadata.size <
|
|
35
|
+
if (!metadata.isFile() || metadata.size < 32 || metadata.size > 4_096) {
|
|
28
36
|
throw new Error("The voice credential file is invalid.");
|
|
29
37
|
}
|
|
30
|
-
|
|
31
|
-
let valid;
|
|
32
|
-
try {
|
|
33
|
-
const [version, tenant = "", signature = "", ...extra] = token.split(".");
|
|
34
|
-
valid = version === VOICE_ACCESS_TOKEN_VERSION &&
|
|
35
|
-
extra.length === 0 &&
|
|
36
|
-
voiceTenant(tenant) === tenant &&
|
|
37
|
-
/^[A-Za-z0-9_-]{43}$/u.test(signature) &&
|
|
38
|
-
Buffer.from(signature, "base64url").toString("base64url") === signature;
|
|
39
|
-
} catch {
|
|
40
|
-
valid = false;
|
|
41
|
-
}
|
|
42
|
-
if (!valid) {
|
|
43
|
-
throw new Error("The voice credential is malformed.");
|
|
44
|
-
}
|
|
45
|
-
return token;
|
|
38
|
+
return voiceClientToken(readFileSync(pathname, "utf8"));
|
|
46
39
|
}
|
|
47
40
|
|
|
48
|
-
|
|
41
|
+
/**
|
|
42
|
+
* A voice client's connection to its speech service: the service's /v1/voice
|
|
43
|
+
* address and the client's token, given as its value or a protected file.
|
|
44
|
+
* @param {{ endpoint?: string, accessToken?: string, accessTokenFile?: string }} [options]
|
|
45
|
+
*/
|
|
46
|
+
function resolveVoiceProxyConfig({ endpoint: value = "", accessToken = "", accessTokenFile = "" } = {}) {
|
|
49
47
|
const endpoint = voiceEndpoint(value);
|
|
48
|
+
const tokenValue = String(accessToken || "").trim();
|
|
50
49
|
const tokenFile = String(accessTokenFile || "").trim();
|
|
51
|
-
if (!endpoint && !tokenFile) {
|
|
50
|
+
if (!endpoint && !tokenValue && !tokenFile) {
|
|
52
51
|
return Object.freeze({
|
|
53
52
|
available: false,
|
|
54
53
|
endpoint: "",
|
|
55
54
|
token: ""
|
|
56
55
|
});
|
|
57
56
|
}
|
|
58
|
-
if (
|
|
57
|
+
if (tokenValue && tokenFile) {
|
|
58
|
+
throw new Error("Give the voice service accessToken or accessTokenFile, not both.");
|
|
59
|
+
}
|
|
60
|
+
if (!endpoint || (!tokenValue && !tokenFile)) {
|
|
59
61
|
throw new Error(
|
|
60
|
-
"Voice endpoint and accessTokenFile must be configured together."
|
|
62
|
+
"Voice endpoint and its accessToken or accessTokenFile must be configured together."
|
|
61
63
|
);
|
|
62
64
|
}
|
|
63
65
|
return Object.freeze({
|
|
64
66
|
available: true,
|
|
65
67
|
endpoint,
|
|
66
|
-
token: readVoiceAccessToken(tokenFile)
|
|
68
|
+
token: tokenValue ? voiceClientToken(tokenValue) : readVoiceAccessToken(tokenFile)
|
|
67
69
|
});
|
|
68
70
|
}
|
|
69
71
|
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs up to `concurrency` operations at once and holds at most `maximumQueued`
|
|
3
|
+
* more; past that it refuses with voice_busy.
|
|
4
|
+
*/
|
|
5
|
+
function createBoundedSpeechQueue({ concurrency = 1, maximumQueued = 4 } = {}) {
|
|
6
|
+
const pending = [];
|
|
7
|
+
let running = 0;
|
|
8
|
+
let closed = false;
|
|
9
|
+
|
|
10
|
+
// An operation leaves the count before its caller hears its result, so a
|
|
11
|
+
// caller that reads depth afterwards does not count it.
|
|
12
|
+
const settle = (callback, value) => {
|
|
13
|
+
running -= 1;
|
|
14
|
+
callback(value);
|
|
15
|
+
drain();
|
|
16
|
+
};
|
|
17
|
+
const drain = () => {
|
|
18
|
+
while (!closed && running < concurrency && pending.length) {
|
|
19
|
+
const next = pending.shift();
|
|
20
|
+
running += 1;
|
|
21
|
+
Promise.resolve()
|
|
22
|
+
.then(next.operation)
|
|
23
|
+
.then(value => settle(next.resolve, value), error => settle(next.reject, error));
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function close() {
|
|
28
|
+
closed = true;
|
|
29
|
+
const error = Object.assign(new Error("Voice speech queue is shutting down."), {
|
|
30
|
+
code: "voice_queue_closed", messageCode: "assistant.voice.daemon.queueClosing", messageParams: {}
|
|
31
|
+
});
|
|
32
|
+
for (const entry of pending.splice(0)) {
|
|
33
|
+
entry.reject(error);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function run(operation) {
|
|
38
|
+
if (closed) {
|
|
39
|
+
const error = Object.assign(new Error("Voice speech queue is unavailable."), {
|
|
40
|
+
code: "voice_queue_closed", messageCode: "assistant.voice.daemon.queueUnavailable", messageParams: {}
|
|
41
|
+
});
|
|
42
|
+
return Promise.reject(error);
|
|
43
|
+
}
|
|
44
|
+
if (typeof operation !== "function") {
|
|
45
|
+
return Promise.reject(new TypeError("Voice speech queue requires an operation."));
|
|
46
|
+
}
|
|
47
|
+
if (pending.length >= maximumQueued) {
|
|
48
|
+
const error = Object.assign(new Error("Voice speech capacity is currently busy. Try again shortly."), {
|
|
49
|
+
code: "voice_busy", messageCode: "assistant.voice.daemon.capacityBusy", messageParams: {}
|
|
50
|
+
});
|
|
51
|
+
return Promise.reject(error);
|
|
52
|
+
}
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
pending.push({ operation, reject, resolve });
|
|
55
|
+
drain();
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return Object.freeze({
|
|
60
|
+
close,
|
|
61
|
+
get depth() {
|
|
62
|
+
return pending.length + running;
|
|
63
|
+
},
|
|
64
|
+
run
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export { createBoundedSpeechQueue };
|
package/src/shared/protocol.js
CHANGED
|
@@ -3,6 +3,9 @@ import en from "../../locales/en.json" with { type: "json" };
|
|
|
3
3
|
|
|
4
4
|
const VOICE_PROTOCOL_VERSION = 1;
|
|
5
5
|
const VOICE_DAEMON_WEBSOCKET_PATH = "/v1/voice";
|
|
6
|
+
const VOICE_CATALOGUE_PATH = "/v1/catalogue";
|
|
7
|
+
const VOICE_VOICES_PATH = "/voices";
|
|
8
|
+
const VOICE_HEALTH_PATH = "/health";
|
|
6
9
|
const VOICE_INPUT_SAMPLE_RATE = 16_000;
|
|
7
10
|
const VOICE_OUTPUT_SAMPLE_RATE = 22_050;
|
|
8
11
|
const VOICE_MAX_CONTROL_BYTES = 16 * 1024;
|
|
@@ -245,26 +248,214 @@ const BUILT_IN_RECOGNITION_WORD_PATTERN = new RegExp(
|
|
|
245
248
|
"giu"
|
|
246
249
|
);
|
|
247
250
|
|
|
251
|
+
const MAXIMUM_RECOGNITION_HOTWORDS = 1000;
|
|
252
|
+
const MAXIMUM_HOTWORD_CHARACTERS = 100;
|
|
253
|
+
const HOTWORD_PATTERN = /^([A-Za-z0-9' ]{1,100}?)(?: +:(\d{1,2}(?:\.\d{1,3})?))?$/u;
|
|
254
|
+
const HOTWORD_RULE = 'a hotword is 1 to 100 letters, digits, apostrophes and spaces, with an optional " :SCORE"';
|
|
255
|
+
const MAXIMUM_RECOGNITION_SPELLINGS = 1000;
|
|
256
|
+
const MAXIMUM_SPELLING_CHARACTERS = 100;
|
|
257
|
+
const SPOKEN_PHRASE_PATTERN = /^[a-z0-9'](?:[a-z0-9' ]{0,98}[a-z0-9'])?$/u;
|
|
258
|
+
const recognitionVocabularyPatterns = new WeakMap();
|
|
259
|
+
|
|
260
|
+
function spokenPhrase(value = "") {
|
|
261
|
+
return String(value).trim().replace(/\s+/gu, " ").toLowerCase();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function isBuiltInRecognitionSpelling(phrase = "") {
|
|
265
|
+
const spoken = spokenPhrase(phrase);
|
|
266
|
+
return Object.hasOwn(BUILT_IN_RECOGNITION_SPELLINGS, spoken) ||
|
|
267
|
+
BUILT_IN_RECOGNITION_PHRASES.some(([pattern]) => new RegExp(`^(?:${pattern.source})$`, "iu").test(spoken));
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** How many spellings recognition applies: JSKIT's own and a host's, a host's replacing JSKIT's on a clash. */
|
|
271
|
+
function recognitionSpellingCount(vocabulary = {}) {
|
|
272
|
+
return BUILT_IN_RECOGNITION_PHRASES.length + Object.keys(BUILT_IN_RECOGNITION_SPELLINGS).length +
|
|
273
|
+
Object.keys(vocabulary).filter(phrase => !isBuiltInRecognitionSpelling(phrase)).length;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* A host's spellings checked: each spoken phrase (1 to 100 letters, digits,
|
|
278
|
+
* apostrophes and single spaces, in any case) to the form it is written in (1
|
|
279
|
+
* to 100 characters, no control characters or surrounding spaces), at most
|
|
280
|
+
* 1000. Keyed by the phrase in lower case.
|
|
281
|
+
* @param {Record<string, string>} value
|
|
282
|
+
* @returns {Readonly<Record<string, string>>}
|
|
283
|
+
*/
|
|
284
|
+
function recognitionSpellings(value = {}) {
|
|
285
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
286
|
+
throw new TypeError("Spellings must map spoken phrases to their written forms.");
|
|
287
|
+
}
|
|
288
|
+
const entries = Object.entries(value);
|
|
289
|
+
if (entries.length > MAXIMUM_RECOGNITION_SPELLINGS) {
|
|
290
|
+
throw new TypeError(`Spellings are limited to ${MAXIMUM_RECOGNITION_SPELLINGS} phrases.`);
|
|
291
|
+
}
|
|
292
|
+
const spellings = {};
|
|
293
|
+
for (const [phrase, written] of entries) {
|
|
294
|
+
const spoken = spokenPhrase(phrase);
|
|
295
|
+
if (!SPOKEN_PHRASE_PATTERN.test(spoken)) {
|
|
296
|
+
throw new TypeError(`Spelling "${phrase}": the spoken phrase must be 1 to 100 letters, digits, apostrophes and spaces.`);
|
|
297
|
+
}
|
|
298
|
+
if (typeof written !== "string" || !written || written !== written.trim() ||
|
|
299
|
+
written.length > MAXIMUM_SPELLING_CHARACTERS || /\p{Cc}/u.test(written)) {
|
|
300
|
+
throw new TypeError(`Spelling "${phrase}": the written form must be 1 to 100 characters, with no control characters or surrounding spaces.`);
|
|
301
|
+
}
|
|
302
|
+
if (Object.hasOwn(spellings, spoken)) throw new TypeError(`Spelling "${phrase}" is given twice.`);
|
|
303
|
+
spellings[spoken] = written;
|
|
304
|
+
}
|
|
305
|
+
return Object.freeze(spellings);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Reads a spellings file: one `spoken phrase => Written form` per line; blank
|
|
310
|
+
* lines and lines starting with # are skipped. A refusal names its line.
|
|
311
|
+
* @param {string} text
|
|
312
|
+
* @returns {Readonly<Record<string, string>>}
|
|
313
|
+
*/
|
|
314
|
+
function parseRecognitionSpellings(text = "") {
|
|
315
|
+
const spellings = {};
|
|
316
|
+
const lines = new Map();
|
|
317
|
+
for (const [index, raw] of String(text).split("\n").entries()) {
|
|
318
|
+
const line = raw.trim();
|
|
319
|
+
if (!line || line.startsWith("#")) continue;
|
|
320
|
+
const number = index + 1;
|
|
321
|
+
const arrow = line.indexOf("=>");
|
|
322
|
+
if (arrow < 0) throw new TypeError(`Spellings line ${number} must read "spoken phrase => Written form".`);
|
|
323
|
+
const phrase = line.slice(0, arrow).trim();
|
|
324
|
+
const written = line.slice(arrow + 2).trim();
|
|
325
|
+
const spoken = spokenPhrase(phrase);
|
|
326
|
+
if (lines.has(spoken)) throw new TypeError(`Spellings line ${number}: "${phrase}" is already spelled on line ${lines.get(spoken)}.`);
|
|
327
|
+
try {
|
|
328
|
+
recognitionSpellings({ [phrase]: written });
|
|
329
|
+
} catch (error) {
|
|
330
|
+
throw new TypeError(`Spellings line ${number}: ${error.message}`);
|
|
331
|
+
}
|
|
332
|
+
lines.set(spoken, number);
|
|
333
|
+
spellings[spoken] = written;
|
|
334
|
+
if (lines.size > MAXIMUM_RECOGNITION_SPELLINGS) {
|
|
335
|
+
throw new TypeError(`Spellings line ${number}: spellings are limited to ${MAXIMUM_RECOGNITION_SPELLINGS} phrases.`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return Object.freeze(spellings);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* A hotword's words, in the upper case the recognizer's tokens use, and its line
|
|
343
|
+
* as the recognizer reads it (the optional score keeps its spelling), or null
|
|
344
|
+
* when it is not a hotword.
|
|
345
|
+
* @param {string} value
|
|
346
|
+
* @returns {{ words: string, line: string } | null}
|
|
347
|
+
*/
|
|
348
|
+
function recognitionHotword(value = "") {
|
|
349
|
+
const match = HOTWORD_PATTERN.exec(String(value ?? "").trim().replace(/\s+/gu, " "));
|
|
350
|
+
if (!match || !match[1].trim()) return null;
|
|
351
|
+
const words = match[1].trim().toUpperCase();
|
|
352
|
+
return { words, line: match[2] ? `${words} :${match[2]}` : words };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Why a phrase is not a hotword, in words a host can act on.
|
|
356
|
+
function hotwordRefusal(value) {
|
|
357
|
+
const text = String(value ?? "").trim().replace(/\s+/gu, " ");
|
|
358
|
+
const scored = /^(.*?) +:(\S*)$/u.exec(text);
|
|
359
|
+
const words = (scored ? scored[1] : text).trim();
|
|
360
|
+
const character = /[^A-Za-z0-9' ]/u.exec(words)?.[0];
|
|
361
|
+
const reason = scored && !/^\d{1,2}(?:\.\d{1,3})?$/u.test(scored[2])
|
|
362
|
+
? `the score "${scored[2]}" is not a number below 100 with at most three decimals`
|
|
363
|
+
: !words ? "it has no words"
|
|
364
|
+
: character ? `${JSON.stringify(character)} is not allowed`
|
|
365
|
+
: words.length > MAXIMUM_HOTWORD_CHARACTERS ? `it is ${words.length} characters long` : "it is not a hotword";
|
|
366
|
+
return `Hotword ${JSON.stringify(text.slice(0, 80))}: ${reason}; ${HOTWORD_RULE}.`;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* A host's hotwords checked, at most 1000, as the recognizer reads them: each
|
|
371
|
+
* one's words in upper case and its optional score.
|
|
372
|
+
* @param {string[]} value
|
|
373
|
+
* @returns {readonly string[]}
|
|
374
|
+
*/
|
|
375
|
+
function recognitionHotwords(value = []) {
|
|
376
|
+
if (!Array.isArray(value) || value.length > MAXIMUM_RECOGNITION_HOTWORDS) {
|
|
377
|
+
throw new TypeError(`Hotwords must be a list of at most ${MAXIMUM_RECOGNITION_HOTWORDS} phrases.`);
|
|
378
|
+
}
|
|
379
|
+
return Object.freeze(value.map(phrase => {
|
|
380
|
+
const hotword = recognitionHotword(phrase);
|
|
381
|
+
if (!hotword) throw new TypeError(hotwordRefusal(phrase));
|
|
382
|
+
return hotword.line;
|
|
383
|
+
}));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Reads a hotwords file: one hotword per line (1 to 100 letters, digits,
|
|
388
|
+
* apostrophes and spaces, then optionally " :SCORE"); blank lines and lines
|
|
389
|
+
* starting with # are skipped. A refusal names its line.
|
|
390
|
+
* @param {string} text
|
|
391
|
+
* @returns {readonly string[]} The hotwords as the recognizer reads them.
|
|
392
|
+
*/
|
|
393
|
+
function parseRecognitionHotwords(text = "") {
|
|
394
|
+
const hotwords = [];
|
|
395
|
+
for (const [index, raw] of String(text).split("\n").entries()) {
|
|
396
|
+
const line = raw.trim();
|
|
397
|
+
if (!line || line.startsWith("#")) continue;
|
|
398
|
+
const number = index + 1;
|
|
399
|
+
if (hotwords.length === MAXIMUM_RECOGNITION_HOTWORDS) {
|
|
400
|
+
throw new TypeError(`Hotwords line ${number}: hotwords are limited to ${MAXIMUM_RECOGNITION_HOTWORDS} phrases.`);
|
|
401
|
+
}
|
|
402
|
+
const hotword = recognitionHotword(line);
|
|
403
|
+
if (!hotword) throw new TypeError(`Hotwords line ${number}: ${hotwordRefusal(line)}`);
|
|
404
|
+
hotwords.push(hotword.line);
|
|
405
|
+
}
|
|
406
|
+
return Object.freeze(hotwords);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
// One pattern for a vocabulary's phrases, longest first, made once per vocabulary.
|
|
410
|
+
function recognitionVocabularyPattern(vocabulary) {
|
|
411
|
+
let compiled = recognitionVocabularyPatterns.get(vocabulary);
|
|
412
|
+
if (!compiled) {
|
|
413
|
+
const spellings = new Map(Object.entries(vocabulary).map(([phrase, written]) => [spokenPhrase(phrase), written]));
|
|
414
|
+
const phrases = [...spellings.keys()].filter(Boolean).sort((left, right) => right.length - left.length);
|
|
415
|
+
compiled = {
|
|
416
|
+
pattern: phrases.length ? new RegExp(`\\b(?:${phrases.map(phrase => (
|
|
417
|
+
phrase.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&").replace(/ /gu, "\\s+")
|
|
418
|
+
)).join("|")})\\b`, "giu") : null,
|
|
419
|
+
spellings
|
|
420
|
+
};
|
|
421
|
+
recognitionVocabularyPatterns.set(vocabulary, compiled);
|
|
422
|
+
}
|
|
423
|
+
return compiled;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function applyBuiltInRecognitionSpellings(text) {
|
|
427
|
+
let result = text;
|
|
428
|
+
for (const [pattern, spelling] of BUILT_IN_RECOGNITION_PHRASES) {
|
|
429
|
+
result = result.replace(pattern, spelling);
|
|
430
|
+
}
|
|
431
|
+
return result.replace(BUILT_IN_RECOGNITION_WORD_PATTERN, (word) => (
|
|
432
|
+
BUILT_IN_RECOGNITION_SPELLINGS[word.toLowerCase()] || word
|
|
433
|
+
));
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Makes an all-uppercase recognition readable: sentence case, JSKIT's spellings
|
|
438
|
+
* and a host's `vocabulary` (spoken phrase to written form). A host's phrases,
|
|
439
|
+
* longest first, take the words they match before JSKIT's spellings apply to the
|
|
440
|
+
* rest, so a host's spelling wins on a clash. Mixed-case text is left intact.
|
|
441
|
+
*/
|
|
248
442
|
function normalizeRecognizedText(value = "", vocabulary = {}) {
|
|
249
443
|
const text = String(value || "").replace(/\s+/gu, " ").trim();
|
|
250
444
|
if (!text || text !== text.toUpperCase() || !/[A-Z]/u.test(text)) {
|
|
251
445
|
return text;
|
|
252
446
|
}
|
|
253
|
-
const
|
|
447
|
+
const sentenceCase = text.toLowerCase().replace(/(^|[.!?]\s+)([a-z])/gu, (_match, prefix, letter) => (
|
|
254
448
|
`${prefix}${letter.toUpperCase()}`
|
|
255
449
|
));
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
for (const [phrase, spelling] of Object.entries(vocabulary)) {
|
|
264
|
-
const literal = phrase.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
|
|
265
|
-
result = result.replace(new RegExp(`\\b${literal}\\b`, "giu"), () => spelling);
|
|
450
|
+
const { pattern, spellings } = recognitionVocabularyPattern(vocabulary);
|
|
451
|
+
if (!pattern) return applyBuiltInRecognitionSpellings(sentenceCase);
|
|
452
|
+
let result = "";
|
|
453
|
+
let start = 0;
|
|
454
|
+
for (const match of sentenceCase.matchAll(pattern)) {
|
|
455
|
+
result += applyBuiltInRecognitionSpellings(sentenceCase.slice(start, match.index)) + spellings.get(spokenPhrase(match[0]));
|
|
456
|
+
start = match.index + match[0].length;
|
|
266
457
|
}
|
|
267
|
-
return result;
|
|
458
|
+
return result + applyBuiltInRecognitionSpellings(sentenceCase.slice(start));
|
|
268
459
|
}
|
|
269
460
|
|
|
270
461
|
function speechTextFromAssistant(value = "", maximumCharacters = VOICE_MAX_SPEECH_TEXT_CHARACTERS, wording = VOICE_SPEECH_WORDING) {
|
|
@@ -473,7 +664,9 @@ function voiceServerMessage(type = "", fields = {}) {
|
|
|
473
664
|
}
|
|
474
665
|
|
|
475
666
|
export {
|
|
667
|
+
VOICE_CATALOGUE_PATH,
|
|
476
668
|
VOICE_DAEMON_WEBSOCKET_PATH,
|
|
669
|
+
VOICE_HEALTH_PATH,
|
|
477
670
|
VOICE_DEFAULT_SYNTHESIS_TIMEOUT_MS,
|
|
478
671
|
VOICE_ID_PATTERN,
|
|
479
672
|
VOICE_INPUT_SAMPLE_RATE,
|
|
@@ -485,11 +678,18 @@ export {
|
|
|
485
678
|
VOICE_MAX_SYNTHESIS_TIMEOUT_MS,
|
|
486
679
|
VOICE_OUTPUT_SAMPLE_RATE,
|
|
487
680
|
VOICE_PROTOCOL_VERSION,
|
|
681
|
+
VOICE_VOICES_PATH,
|
|
488
682
|
assertVoiceAudioFrame,
|
|
489
683
|
float32ToPcm16Le,
|
|
490
684
|
normalizeRecognizedText,
|
|
491
685
|
parseVoiceClientControl,
|
|
686
|
+
parseRecognitionHotwords,
|
|
687
|
+
parseRecognitionSpellings,
|
|
492
688
|
pcm16LeToFloat32,
|
|
689
|
+
recognitionHotword,
|
|
690
|
+
recognitionHotwords,
|
|
691
|
+
recognitionSpellingCount,
|
|
692
|
+
recognitionSpellings,
|
|
493
693
|
speechPauseDurationMs,
|
|
494
694
|
speechPhrases,
|
|
495
695
|
speechTextFromAssistant,
|
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import crypto from "node:crypto";
|
|
2
|
-
|
|
3
|
-
const VOICE_ACCESS_TOKEN_VERSION = "v1";
|
|
4
|
-
const VOICE_TENANT_PATTERN = /^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/u;
|
|
5
|
-
|
|
6
|
-
function voiceTenant(value = "") {
|
|
7
|
-
const tenant = String(value || "").trim().toLowerCase();
|
|
8
|
-
if (!VOICE_TENANT_PATTERN.test(tenant)) {
|
|
9
|
-
const error = new Error("Voice access requires a valid tenant name.");
|
|
10
|
-
error.code = "voice_tenant_invalid";
|
|
11
|
-
throw error;
|
|
12
|
-
}
|
|
13
|
-
return tenant;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
function voiceAccessKey(value = "") {
|
|
17
|
-
const key = Buffer.isBuffer(value) ? value : Buffer.from(String(value || ""), "utf8");
|
|
18
|
-
if (key.byteLength < 32) {
|
|
19
|
-
const error = new Error("Voice access signing keys must contain at least 32 bytes.");
|
|
20
|
-
error.code = "voice_access_key_invalid";
|
|
21
|
-
throw error;
|
|
22
|
-
}
|
|
23
|
-
return key;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
function voiceAccessSignature(key, tenant) {
|
|
27
|
-
return crypto
|
|
28
|
-
.createHmac("sha256", voiceAccessKey(key))
|
|
29
|
-
.update(`${VOICE_ACCESS_TOKEN_VERSION}.${voiceTenant(tenant)}`, "utf8")
|
|
30
|
-
.digest("base64url");
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
function createVoiceAccessToken({ key, tenant } = {}) {
|
|
34
|
-
const normalizedTenant = voiceTenant(tenant);
|
|
35
|
-
return [
|
|
36
|
-
VOICE_ACCESS_TOKEN_VERSION,
|
|
37
|
-
normalizedTenant,
|
|
38
|
-
voiceAccessSignature(key, normalizedTenant)
|
|
39
|
-
].join(".");
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function verifyVoiceAccessToken(token = "", { key } = {}) {
|
|
43
|
-
const [version = "", rawTenant = "", signature = "", ...extra] = String(token || "").trim().split(".");
|
|
44
|
-
if (version !== VOICE_ACCESS_TOKEN_VERSION || !rawTenant || !signature || extra.length) {
|
|
45
|
-
return null;
|
|
46
|
-
}
|
|
47
|
-
let tenant;
|
|
48
|
-
let expected;
|
|
49
|
-
try {
|
|
50
|
-
tenant = voiceTenant(rawTenant);
|
|
51
|
-
expected = voiceAccessSignature(key, tenant);
|
|
52
|
-
} catch {
|
|
53
|
-
return null;
|
|
54
|
-
}
|
|
55
|
-
const actualBytes = Buffer.from(signature, "utf8");
|
|
56
|
-
const expectedBytes = Buffer.from(expected, "utf8");
|
|
57
|
-
if (
|
|
58
|
-
actualBytes.byteLength !== expectedBytes.byteLength ||
|
|
59
|
-
!crypto.timingSafeEqual(actualBytes, expectedBytes)
|
|
60
|
-
) {
|
|
61
|
-
return null;
|
|
62
|
-
}
|
|
63
|
-
return Object.freeze({
|
|
64
|
-
tenant,
|
|
65
|
-
version
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
function bearerVoiceAccessToken(headers = {}) {
|
|
70
|
-
const value = String(headers.authorization || headers.Authorization || "").trim();
|
|
71
|
-
const match = /^Bearer\s+([^\s]+)$/iu.exec(value);
|
|
72
|
-
return match ? match[1] : "";
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
export {
|
|
76
|
-
VOICE_ACCESS_TOKEN_VERSION,
|
|
77
|
-
bearerVoiceAccessToken,
|
|
78
|
-
createVoiceAccessToken,
|
|
79
|
-
verifyVoiceAccessToken,
|
|
80
|
-
voiceAccessKey,
|
|
81
|
-
voiceTenant
|
|
82
|
-
};
|