clavarium 0.2.153-beta.1 → 0.2.154-beta.1
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/npm-shrinkwrap.json +10 -10
- package/package.json +3 -3
- package/server/api.mjs +9 -2
- package/server/boxes.mjs +132 -8
- package/server/dictation-engines.mjs +91 -0
- package/server/features.mjs +366 -0
- package/server/main.mjs +26 -3
- package/server/rooms.mjs +5 -3
- package/server/talk.mjs +5 -1
- package/server/voice.mjs +139 -47
- package/server/wakelearn.mjs +214 -0
- package/web/app.js +308 -52
- package/web/features.js +480 -0
- package/web/index.html +36 -9
- package/web/style.css +421 -136
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.154-beta.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.154-beta.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
|
13
13
|
"@xterm/xterm": "^6.0.0",
|
|
14
|
-
"clavarium-binder": "0.1.
|
|
14
|
+
"clavarium-binder": "0.1.60-next.1",
|
|
15
15
|
"clavarium-docket": "0.1.2-next.2",
|
|
16
|
-
"clavarium-parley": "0.17.
|
|
16
|
+
"clavarium-parley": "0.17.64-next.1",
|
|
17
17
|
"clavarium-tether": "0.1.0-next.49",
|
|
18
18
|
"mammoth": "1.13.0",
|
|
19
19
|
"mermaid": "11.17.2",
|
|
@@ -761,9 +761,9 @@
|
|
|
761
761
|
}
|
|
762
762
|
},
|
|
763
763
|
"node_modules/clavarium-binder": {
|
|
764
|
-
"version": "0.1.
|
|
765
|
-
"resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.
|
|
766
|
-
"integrity": "sha512-
|
|
764
|
+
"version": "0.1.60-next.1",
|
|
765
|
+
"resolved": "https://registry.npmjs.org/clavarium-binder/-/clavarium-binder-0.1.60-next.1.tgz",
|
|
766
|
+
"integrity": "sha512-Tyat1gQu+V4XCvQknRTBc3TChsE3RTWdRuQATsQoTDD7/FmaXWijFhmhH8IaUdMhtA5p5IikxEfDha7AR0PBlw==",
|
|
767
767
|
"license": "MIT",
|
|
768
768
|
"bin": {
|
|
769
769
|
"binder": "bin/binder.mjs",
|
|
@@ -787,9 +787,9 @@
|
|
|
787
787
|
}
|
|
788
788
|
},
|
|
789
789
|
"node_modules/clavarium-parley": {
|
|
790
|
-
"version": "0.17.
|
|
791
|
-
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.
|
|
792
|
-
"integrity": "sha512-
|
|
790
|
+
"version": "0.17.64-next.1",
|
|
791
|
+
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.64-next.1.tgz",
|
|
792
|
+
"integrity": "sha512-xODV5QxOSFMjZAchfK7z3ZSvvSTeI57TYKifvDFjBrkK4Z3bAzc/0cnAq/OYid7nX4viMjZGV4OlJnRVowYg7Q==",
|
|
793
793
|
"license": "MIT",
|
|
794
794
|
"bin": {
|
|
795
795
|
"parley": "bin/parley.mjs",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.154-beta.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
|
|
@@ -44,9 +44,9 @@
|
|
|
44
44
|
"dependencies": {
|
|
45
45
|
"@xterm/addon-fit": "^0.11.0",
|
|
46
46
|
"@xterm/xterm": "^6.0.0",
|
|
47
|
-
"clavarium-binder": "0.1.
|
|
47
|
+
"clavarium-binder": "0.1.60-next.1",
|
|
48
48
|
"clavarium-docket": "0.1.2-next.2",
|
|
49
|
-
"clavarium-parley": "0.17.
|
|
49
|
+
"clavarium-parley": "0.17.64-next.1",
|
|
50
50
|
"clavarium-tether": "0.1.0-next.49",
|
|
51
51
|
"mammoth": "1.13.0",
|
|
52
52
|
"mermaid": "11.17.2",
|
package/server/api.mjs
CHANGED
|
@@ -89,7 +89,7 @@
|
|
|
89
89
|
* POST /api/asset-groups/place {asset, group}: put an asset in a group (group null to take it out)
|
|
90
90
|
* POST /api/asset-groups/<id>/rename {label}
|
|
91
91
|
* POST /api/asset-groups/<id>/remove
|
|
92
|
-
* GET /api/rooms the rooms (#268): [{id, name, host, members: [{id, kind, name, ref, host?}]}]
|
|
92
|
+
* GET /api/rooms the rooms (#268): [{id, name, host, members: [{id, kind, name, ref, host?}], unread, last, thinking: [names]}]
|
|
93
93
|
* POST /api/rooms {name, conversations: [names], boxes: [ids], host?}: a new room
|
|
94
94
|
* POST /api/rooms/<id> {name?, host?, add?: {conversations, boxes}, remove?: [member ids]}
|
|
95
95
|
* POST /api/rooms/<id>/remove the room and its thread
|
|
@@ -116,10 +116,15 @@
|
|
|
116
116
|
* GET /api/shortcuts
|
|
117
117
|
* POST /api/shortcuts {label, text, enter}
|
|
118
118
|
* POST /api/shortcuts/<id>/remove
|
|
119
|
+
* GET /api/features POST /api/features/dismiss|goals|sharing|welcome what this Clavarium can do, and its next step
|
|
120
|
+
* (features.mjs, answered before this: main.mjs)
|
|
119
121
|
* GET /api/voice is dictation available?
|
|
120
122
|
* POST /api/voice?lang= the body IS a WAV recording -> {text}; lang: the device's language
|
|
121
123
|
* GET /api/dictation the engine chosen in Settings (never a key: a secret's name)
|
|
122
|
-
* POST /api/dictation {provider, url, model, secret,
|
|
124
|
+
* POST /api/dictation {language, main: {provider, url, model, secret}, backup: {...} | {provider: 'none'}}: chosen, at once
|
|
125
|
+
* (a body of before, {provider, url, model, secret, language}, sets the main one)
|
|
126
|
+
* GET /api/dictation/models?provider=&secret= that provider's speech-to-text models [{id, label}] (read with the key, kept 24 h)
|
|
127
|
+
* GET /api/dictation/suggestions {providers: [{id, label, models, keys}], suggestions: [{slot, provider, model, secret}]}
|
|
123
128
|
* POST /api/dictation/off the environment's engine, if any, again
|
|
124
129
|
* POST /api/dictation/try?provider=&url=&model=&secret=&language=&lang= a WAV -> {text}, nothing saved
|
|
125
130
|
* GET /api/files?c=<conversation>&r=<resource>&p=<path> a listing
|
|
@@ -205,6 +210,8 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
205
210
|
try {
|
|
206
211
|
if (request.method === 'GET' && pathname === '/api/voice') return send(200, { available: voice?.current() !== undefined, engine: voice?.model ?? null }), true;
|
|
207
212
|
if (request.method === 'GET' && pathname === '/api/dictation' && voice) return send(200, voice.about()), true;
|
|
213
|
+
if (request.method === 'GET' && pathname === '/api/dictation/models' && voice) return send(200, await voice.models(query.get('provider') ?? '', query.get('secret') ?? '')), true;
|
|
214
|
+
if (request.method === 'GET' && pathname === '/api/dictation/suggestions' && voice) return send(200, await voice.suggestions()), true;
|
|
208
215
|
if (request.method === 'POST' && (pathname === '/api/voice' || (pathname === '/api/dictation/try' && voice))) {
|
|
209
216
|
if (!originOk(request.headers) || request.headers['content-type'] !== 'audio/wav') {
|
|
210
217
|
return send(403, { error: 'This request does not come from this site.' }), true;
|
package/server/boxes.mjs
CHANGED
|
@@ -14,12 +14,14 @@
|
|
|
14
14
|
* key gets 401 and the box goes back to its setup
|
|
15
15
|
*
|
|
16
16
|
* Both are under /c/: the edge lets them through without sign-on, as the
|
|
17
|
-
* device door. Nothing is kept of the audio, here or on the box
|
|
17
|
+
* device door. Nothing is kept of the audio, here or on the box -- but the wake word's own
|
|
18
|
+
* 1.6 s of a box set to learn it (wakelearn.mjs).
|
|
18
19
|
*/
|
|
19
20
|
import { spawn as spawnProcess } from 'node:child_process';
|
|
20
21
|
import { createWriteStream, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
|
21
22
|
import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
|
|
22
23
|
import { Refusal } from './conversations.mjs';
|
|
24
|
+
import { WIRE, cutoffOf, scoreOf } from './wakelearn.mjs';
|
|
23
25
|
|
|
24
26
|
export const CODE_MINUTES = 10;
|
|
25
27
|
export const PAIR_PATH = '/c/api/box/pair';
|
|
@@ -260,12 +262,12 @@ export function piecesOf(pcm, { least = 8, most = 14 } = {}) {
|
|
|
260
262
|
|
|
261
263
|
export class Boxes {
|
|
262
264
|
#file; #codes = new Map(); #links = new Map(); #tries = []; #now;
|
|
263
|
-
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep; #react;
|
|
265
|
+
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep; #react; #learn;
|
|
264
266
|
|
|
265
267
|
/* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
|
|
266
268
|
exists(conversation), hear(wav) -> text, say(conversation, text, room), speak(text) -> PCM 16 kHz. */
|
|
267
|
-
constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch, recordDir = null, parts = null, keep = null, react = async () => null }) {
|
|
268
|
-
this.#react = react;
|
|
269
|
+
constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch, recordDir = null, parts = null, keep = null, react = async () => null, learn = null }) {
|
|
270
|
+
this.#react = react; this.#learn = learn;
|
|
269
271
|
this.#spawn = spawn; this.#fetch = fetcher; this.#recordDir = recordDir; this.#parts = parts; this.#keep = keep;
|
|
270
272
|
this.#file = file; this.#changed = changed; this.#origin = origin; this.#exists = exists; this.#hear = hear; this.#say = say; this.#speak = speak; this.#now = now; this.#log = log;
|
|
271
273
|
}
|
|
@@ -492,6 +494,89 @@ export class Boxes {
|
|
|
492
494
|
if (!list.some((b) => b.id === id)) throw new Refusal(404, 'No such voice box.');
|
|
493
495
|
this.#save(list.filter((b) => b.id !== id));
|
|
494
496
|
this.#links.get(id)?.socket.close(4001, 'withdrawn');
|
|
497
|
+
try { this.#learn?.forget(id); } catch { /* nothing kept */ }
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/* THE WAKE WORD THAT LEARNS (wakelearn.mjs): "normal" keeps nothing, "learn" keeps each wake clip with
|
|
501
|
+
its label. Its counts are made either way. */
|
|
502
|
+
#box(id) { const b = this.#all().find((x) => x.id === id); if (!b) throw new Refusal(404, 'No such voice box.'); return b; }
|
|
503
|
+
#learning() { if (!this.#learn) throw new Refusal(501, 'This server keeps no wake clips.'); return this.#learn; }
|
|
504
|
+
wakeMode(id, mode) {
|
|
505
|
+
if (!['normal', 'learn'].includes(mode)) throw new Refusal(400, 'A mode: normal or learn.');
|
|
506
|
+
this.#change(id, { wake: mode });
|
|
507
|
+
return this.wakeStats(id);
|
|
508
|
+
}
|
|
509
|
+
wakeStats(id) { const b = this.#box(id); return { ...this.#learning().stats(id, b.wake ?? 'normal'), cutoff: this.#cutoff(b), wakeModel: b.model ?? null, modelProblem: b.modelProblem ?? null }; }
|
|
510
|
+
#cutoff(b) { return cutoffOf(b.cutoff) ?? WIRE.firmwareCutoff; }
|
|
511
|
+
wakeErase(id) { const b = this.#box(id); const n = this.#learning().erase(id); this.#log(`voice box ${b.name}: ${n} wake clip(s) erased`); return this.wakeStats(id); }
|
|
512
|
+
/* "Improve now": the threshold tuned at once; nothing better, the trainer (phase 2) is asked. */
|
|
513
|
+
wakeImprove(id) {
|
|
514
|
+
const b = this.#box(id);
|
|
515
|
+
const tuning = this.wakeTune(id, 'asked');
|
|
516
|
+
if (tuning.better) return { queued: false, at: tuning.at, tuning };
|
|
517
|
+
const at = this.#learning().improve(id); this.#log(`voice box ${b.name}: a better wake word asked`);
|
|
518
|
+
return { queued: true, at, tuning };
|
|
519
|
+
}
|
|
520
|
+
/* THRESHOLD TUNING (wakelearn.mjs, tuneCutoff): a better cutoff found is sent to the box (wake.cutoff);
|
|
521
|
+
once it confirms (its ack, or its hello showing it), said in its conversation. Not connected: sent at
|
|
522
|
+
its next hello. */
|
|
523
|
+
wakeTune(id, why = 'asked') {
|
|
524
|
+
const b = this.#box(id);
|
|
525
|
+
const r = this.#learning().tune(id, this.#cutoff(b));
|
|
526
|
+
const t = this.#learn.tuned(id, { ...r, why, state: r.better ? 'sent' : 'none' });
|
|
527
|
+
this.#log(`voice box ${b.name}: wake threshold tuning (${why}): ${r.better ? `${r.from} -> ${r.to}` : r.reason}`);
|
|
528
|
+
if (r.better) this.#sendCutoff(id, r.to);
|
|
529
|
+
return t;
|
|
530
|
+
}
|
|
531
|
+
#sendCutoff(id, value) {
|
|
532
|
+
if (!this.#links.get(id)?.tunable) return; /* not connected, or a firmware without wake.cutoff (its hello says none) */
|
|
533
|
+
this.command(id, { t: WIRE.cutoff, value }).then(
|
|
534
|
+
(a) => { if (a?.ok === false) this.#tuneState(id, 'refused'); else void this.#cutoffSet(id, value); },
|
|
535
|
+
() => { /* no answer: sent again at its next hello */ });
|
|
536
|
+
}
|
|
537
|
+
#tuneState(id, state) { const t = this.#learn?.tuning(id); if (t) this.#learn.tuned(id, { ...t, state }); }
|
|
538
|
+
/* The box holds `value` (its ack, or its hello): kept; a tuning sent for it is said, once. */
|
|
539
|
+
async #cutoffSet(id, value) {
|
|
540
|
+
let b; try { b = this.#box(id); } catch { return null; }
|
|
541
|
+
if (b.cutoff !== value) this.#change(id, { cutoff: value });
|
|
542
|
+
const t = this.#learn?.tuning(id);
|
|
543
|
+
if (!t || t.state !== 'sent' || t.to !== value) return null;
|
|
544
|
+
this.#learn.tuned(id, { ...t, state: 'applied', appliedAt: new Date(this.#now()).toISOString() });
|
|
545
|
+
const fr = /^fr/.test(b.lang ?? '');
|
|
546
|
+
const n = (v, d = 1) => String(Math.round(Number(v) * 10 ** d) / 10 ** d).replace('.', fr ? ',' : '.');
|
|
547
|
+
const c = (v) => Number(v).toFixed(2).replace('.', fr ? ',' : '.');
|
|
548
|
+
const text = fr
|
|
549
|
+
? `Mot d'éveil réglé : seuil ${c(t.from)} → ${c(t.to)} (faux réveils ${n(t.falsePerDayBefore)} → ${n(t.falsePerDayAfter)} par jour sur tes ${t.clips} extraits ; appels manqués ${t.missedBefore} → ${t.missedAfter}).`
|
|
550
|
+
: `Wake word tuned: threshold ${c(t.from)} → ${c(t.to)} (false wakes ${n(t.falsePerDayBefore)} → ${n(t.falsePerDayAfter)} a day on your ${t.clips} clips; missed calls ${t.missedBefore} → ${t.missedAfter}).`;
|
|
551
|
+
this.#log(`voice box ${b.name}: wake threshold now ${value}`);
|
|
552
|
+
try { await this.#say(b.conversation, text, { id: b.id, name: b.name, ...(b.place ? { place: b.place } : {}) }); } catch (error) { this.#log(`voice box ${b.name}: the tuning not said (${error.message})`); }
|
|
553
|
+
return text;
|
|
554
|
+
}
|
|
555
|
+
/* WEEKLY (Sunday from 03:00, the box's own time): each learning box tuned once a week. Called often. */
|
|
556
|
+
wakeWeekly() {
|
|
557
|
+
const now = this.#now(); const ran = [];
|
|
558
|
+
for (const b of this.#all()) {
|
|
559
|
+
if (b.wake !== 'learn' || !this.#learn) continue;
|
|
560
|
+
const local = new Date(now + offsetOf(b.zone, now) * 60_000);
|
|
561
|
+
if (local.getUTCDay() !== 0 || local.getUTCHours() < 3) continue;
|
|
562
|
+
if (now - (Date.parse(b.wakeWeeklyAt ?? '') || 0) < 6 * 86_400_000) continue;
|
|
563
|
+
this.#change(b.id, { wakeWeeklyAt: new Date(now).toISOString() });
|
|
564
|
+
try { ran.push(this.wakeTune(b.id, 'weekly')); } catch (error) { this.#log(`voice box ${b.name}: weekly tuning failed (${error.message})`); }
|
|
565
|
+
}
|
|
566
|
+
return ran;
|
|
567
|
+
}
|
|
568
|
+
/* Phase 2's trainer put a better model on the box: kept, and said in its conversation in its name. */
|
|
569
|
+
async modelInstalled(id, { before, after }) {
|
|
570
|
+
const b = this.#box(id);
|
|
571
|
+
const m = this.#learning().installed(id, { before, after });
|
|
572
|
+
const { kept } = this.#learn.stats(id, b.wake);
|
|
573
|
+
const n = (v) => String(Math.round(Number(v) * 10) / 10).replace('.', /^fr/.test(b.lang ?? '') ? ',' : '.');
|
|
574
|
+
const text = /^fr/.test(b.lang ?? '')
|
|
575
|
+
? `Nouveau mot d'éveil installé (faux réveils ${n(before)} \u2192 ${n(after)} par jour sur tes ${kept} extraits).`
|
|
576
|
+
: `New wake word installed (false wakes ${n(before)} \u2192 ${n(after)} a day on your ${kept} clips).`;
|
|
577
|
+
this.#log(`voice box ${b.name}: new wake word installed`);
|
|
578
|
+
try { await this.#say(b.conversation, text, { id: b.id, name: b.name, ...(b.place ? { place: b.place } : {}) }); } catch (error) { this.#log(`voice box ${b.name}: the new wake word not said (${error.message})`); }
|
|
579
|
+
return { ...m, text };
|
|
495
580
|
}
|
|
496
581
|
|
|
497
582
|
/* A conversation removed or renamed: its boxes follow, or are left without one. */
|
|
@@ -627,6 +712,7 @@ export class Boxes {
|
|
|
627
712
|
}
|
|
628
713
|
/* The wake word's own 1.6 s (wake.clip): kept apart, heard again before the word is trusted. */
|
|
629
714
|
if (link.clip) { if (link.clip.bytes < CLIP_MAX_BYTES) { link.clip.parts.push(Buffer.from(data)); link.clip.bytes += data.length; } return; }
|
|
715
|
+
if (link.near) { if (link.near.bytes < CLIP_MAX_BYTES) { link.near.parts.push(Buffer.from(data)); link.near.bytes += data.length; } return; }
|
|
630
716
|
if (!sentence || link.muted) return;
|
|
631
717
|
size += data.length;
|
|
632
718
|
if (size <= SENTENCE_MAX) sentence.push(Buffer.from(data));
|
|
@@ -644,6 +730,19 @@ export class Boxes {
|
|
|
644
730
|
}
|
|
645
731
|
if (m.t === 'hello') send({ t: 'clock', offset: offsetOf(link.box().zone, this.#now()) });
|
|
646
732
|
if (m.t === 'ping' && this.#now() - (link.clockAt ?? 0) > 3_600_000) { link.clockAt = this.#now(); send({ t: 'clock', offset: offsetOf(link.box().zone, this.#now()) }); }
|
|
733
|
+
if (m.t === 'hello') {
|
|
734
|
+
/* Its threshold and model (0.1.49): a tuning it holds is confirmed; one it missed, sent again. */
|
|
735
|
+
const cut = cutoffOf(m.cutoff); link.tunable = cut !== null;
|
|
736
|
+
const model = typeof m.model === 'string' ? m.model.slice(0, 40) : null;
|
|
737
|
+
const modelProblem = typeof m.model_problem === 'string' && m.model_problem ? m.model_problem.slice(0, 160) : null;
|
|
738
|
+
const was = link.box();
|
|
739
|
+
if (model !== (was.model ?? null) || modelProblem !== (was.modelProblem ?? null)) this.#change(box.id, { model, modelProblem });
|
|
740
|
+
if (modelProblem) this.#log(`voice box ${box.name}: its wake model: ${modelProblem}`);
|
|
741
|
+
const t = this.#learn?.tuning(box.id);
|
|
742
|
+
if (cut !== null) void this.#cutoffSet(box.id, cut);
|
|
743
|
+
else if (was.cutoff != null) this.#change(box.id, { cutoff: null }); /* an older firmware: 0.94, built in */
|
|
744
|
+
if (t?.state === 'sent' && t.to !== cut) this.#sendCutoff(box.id, t.to);
|
|
745
|
+
}
|
|
647
746
|
if (m.t === 'hello') { link.muted = m.muted === true; link.volume = Number.isFinite(m.volume) ? m.volume : null; this.#change(box.id, { firmware: String(m.firmware ?? '').slice(0, 20) }); seen(); return; }
|
|
648
747
|
if (m.t === 'record.start' && this.#recordDir) {
|
|
649
748
|
mkdirSync(this.#recordDir, { recursive: true });
|
|
@@ -657,8 +756,10 @@ export class Boxes {
|
|
|
657
756
|
r.out.end(() => { void this.#recorded(link, r); });
|
|
658
757
|
return;
|
|
659
758
|
}
|
|
660
|
-
if (m.t ===
|
|
661
|
-
if (m.t ===
|
|
759
|
+
if (m.t === WIRE.clip && m.edge === 'start') { link.clip = { parts: [], bytes: 0, score: scoreOf(m.score) }; /* none (before 0.1.49): unknown, left out of tuning */ return; }
|
|
760
|
+
if (m.t === WIRE.clip && m.edge === 'end' && link.clip) { const { parts, score } = link.clip; link.clip = null; link.wakeCheck = this.#checkWake(link, Buffer.concat(parts), { score }); return; }
|
|
761
|
+
if (m.t === WIRE.near && m.edge === 'start') { link.near = { parts: [], bytes: 0, score: scoreOf(m.score) }; return; }
|
|
762
|
+
if (m.t === WIRE.near && m.edge === 'end' && link.near) { const { parts, score } = link.near; link.near = null; void this.#checkNear(link, Buffer.concat(parts), score); return; }
|
|
662
763
|
if (m.t === 'event' && m.name === 'wake.own') { this.#log(`voice box ${box.name}: heard its own voice say the wake word, ignored`); return; }
|
|
663
764
|
if (m.t === 'event' && m.name === 'noise.dropped') { this.#log(`voice box ${box.name}: a sound near full scale was cut by its noise guard`); return; }
|
|
664
765
|
/* The box listens for a sentence while this side still records: the two disagree (a reconnection, a
|
|
@@ -742,10 +843,20 @@ export class Boxes {
|
|
|
742
843
|
|
|
743
844
|
/* Each step said in the server's log, never what was said: its length only. */
|
|
744
845
|
/* The 1.6 s before the sentence, heard again: is the wake word in it? Its words, and whether it reads as the word. */
|
|
745
|
-
async #checkWake(link, pcm) {
|
|
846
|
+
async #checkWake(link, pcm, { score = null, near = false } = {}) {
|
|
746
847
|
if (pcm.length < 8_000) return null;
|
|
747
848
|
const heard = String(await this.#hear(wavOf(pcm), link.box().lang) ?? '').trim();
|
|
748
|
-
|
|
849
|
+
const ok = WAKE_HEARD.test(plainWords(heard));
|
|
850
|
+
/* Counted, and kept when the box learns (the clip only: never the sentence), with the box's score. */
|
|
851
|
+
const box = link.box();
|
|
852
|
+
try { this.#learn?.checked(box.id, pcm, ok, { keep: box.wake === 'learn', heard, score, near }); } catch (error) { this.#log(`voice box ${box.name}: wake clip not kept (${error.message})`); }
|
|
853
|
+
return { heard, ok };
|
|
854
|
+
}
|
|
855
|
+
/* A NEAR MISS (wake.near): checked the same way, only when the box learns; one at a time; nothing said. */
|
|
856
|
+
async #checkNear(link, pcm, score) {
|
|
857
|
+
if (link.box().wake !== 'learn' || link.nearBusy) return;
|
|
858
|
+
link.nearBusy = true;
|
|
859
|
+
try { await this.#checkWake(link, pcm, { score, near: true }); } catch { /* not heard: not kept */ } finally { link.nearBusy = false; }
|
|
749
860
|
}
|
|
750
861
|
async #heard(link, pcm) {
|
|
751
862
|
const box0 = link.box();
|
|
@@ -855,12 +966,22 @@ export class Boxes {
|
|
|
855
966
|
* POST /api/boxes/<id>/wifi-forget {ssid}: not the one it uses now
|
|
856
967
|
* POST /api/boxes/<id>/alert {text?}
|
|
857
968
|
* POST /api/boxes/<id>/reboot
|
|
969
|
+
* GET /api/boxes/<id>/wake -> {mode, kept, real, false, near, missed, oldest, falsePerDay, missedPerDay,
|
|
970
|
+
* cutoff, wakeModel, tuning: {at, why, state, better, reason, from, to, clips,
|
|
971
|
+
* falsePerDayBefore, falsePerDayAfter, missedBefore, missedAfter} | null,
|
|
972
|
+
* model: {installedAt, falsePerDayBefore, falsePerDayAfter} | null, improveAsked}
|
|
973
|
+
* POST /api/boxes/<id>/wake-mode {mode: normal|learn} -> the same
|
|
974
|
+
* POST /api/boxes/<id>/wake-erase every clip of the box deleted -> the same
|
|
975
|
+
* POST /api/boxes/<id>/wake-improve -> 202 {queued, at, tuning}: the threshold tuned now; nothing better, the
|
|
976
|
+
* trainer asked (queued)
|
|
858
977
|
*/
|
|
859
978
|
export async function handleBoxes(request, response, boxes, originOk, headers = {}, qr = null) {
|
|
860
979
|
const { pathname } = new URL(request.url ?? '/', 'http://local');
|
|
861
980
|
const send = (status, body) => { response.writeHead(status, { ...headers, 'content-type': 'application/json; charset=utf-8' }).end(JSON.stringify(body)); return true; };
|
|
862
981
|
try {
|
|
863
982
|
if (request.method === 'GET' && pathname === '/api/boxes') return send(200, boxes.all());
|
|
983
|
+
const asked = request.method === 'GET' && /^\/api\/boxes\/([0-9a-f-]{36})\/wake$/.exec(pathname);
|
|
984
|
+
if (asked) return send(200, boxes.wakeStats(asked[1]));
|
|
864
985
|
if (request.method !== 'POST') return false;
|
|
865
986
|
if (!originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' });
|
|
866
987
|
let text = '';
|
|
@@ -895,6 +1016,9 @@ export async function handleBoxes(request, response, boxes, originOk, headers =
|
|
|
895
1016
|
case 'test-mic': return send(200, await boxes.testMic(id));
|
|
896
1017
|
case 'test-result': return send(200, boxes.testResult(id));
|
|
897
1018
|
case 'reboot': return answered(await boxes.command(id, { t: 'reboot' }));
|
|
1019
|
+
case 'wake-mode': return send(200, boxes.wakeMode(id, String(body.mode ?? '')));
|
|
1020
|
+
case 'wake-erase': return send(200, boxes.wakeErase(id));
|
|
1021
|
+
case 'wake-improve': return send(202, boxes.wakeImprove(id));
|
|
898
1022
|
default: return false;
|
|
899
1023
|
}
|
|
900
1024
|
} catch (error) {
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/* THE DICTATION ENGINES ON OFFER, in one place: the providers, their speech-to-text models, and which kept
|
|
2
|
+
* secrets look like a key for each. Settings > Dictation uses it; so may anything that sets dictation up
|
|
3
|
+
* (an "integration"): `catalogue()` and `suggestions()` say what could be chosen, never a key's value.
|
|
4
|
+
*
|
|
5
|
+
* MODELS: a known base list per provider, with a short label. Once a key is chosen, the provider's own
|
|
6
|
+
* listing (GET <base>/models, the OpenAI-compatible one; OVH AI Endpoints has it too) is read with that key,
|
|
7
|
+
* kept to its speech-to-text models, and kept 24 h. Any failure: the base list, silently. */
|
|
8
|
+
|
|
9
|
+
export const PROVIDERS = {
|
|
10
|
+
ovh: { label: 'OVH AI Endpoints', short: 'OVH', url: 'https://oai.endpoints.kepler.ai.cloud.ovh.net/v1/audio/transcriptions', model: 'whisper-large-v3-turbo',
|
|
11
|
+
models: [{ id: 'whisper-large-v3-turbo', label: 'fast' }, { id: 'whisper-large-v3', label: 'more accurate' }] },
|
|
12
|
+
openai: { label: 'OpenAI', short: 'OpenAI', url: 'https://api.openai.com/v1/audio/transcriptions', model: 'whisper-1',
|
|
13
|
+
models: [{ id: 'whisper-1', label: 'fast' }, { id: 'gpt-4o-mini-transcribe', label: 'fast' }, { id: 'gpt-4o-transcribe', label: 'more accurate' }] },
|
|
14
|
+
groq: { label: 'Groq', short: 'Groq', url: 'https://api.groq.com/openai/v1/audio/transcriptions', model: 'whisper-large-v3-turbo',
|
|
15
|
+
models: [{ id: 'whisper-large-v3-turbo', label: 'fast' }, { id: 'whisper-large-v3', label: 'more accurate' }] },
|
|
16
|
+
mistral: { label: 'Mistral', short: 'Mistral', url: 'https://api.mistral.ai/v1/audio/transcriptions', model: 'voxtral-mini-latest',
|
|
17
|
+
models: [{ id: 'voxtral-mini-latest', label: 'fast' }, { id: 'voxtral-small-latest', label: 'more accurate' }] },
|
|
18
|
+
other: { label: 'Other (compatible)', url: '', model: '', models: [] },
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/* A secret's name that reads as a key of this provider. */
|
|
22
|
+
export const KEY_NAMES = { ovh: /^OVH_AI_ENDPOINTS/, mistral: /^MISTRAL/, groq: /^GROQ/, openai: /^OPENAI/ };
|
|
23
|
+
/* The order a suggestion is made in: the first provider with a key. */
|
|
24
|
+
const ORDER = ['ovh', 'mistral', 'groq', 'openai'];
|
|
25
|
+
|
|
26
|
+
/* A speech-to-text model, by its name: never a voice (tts), nor a live stream one (realtime). */
|
|
27
|
+
export const isSpeechToText = (id) => /whisper|voxtral|transcribe|speech-to-text/i.test(id) && !/tts|realtime/i.test(id);
|
|
28
|
+
export const MODELS_TTL_MS = 24 * 3600_000;
|
|
29
|
+
|
|
30
|
+
export function keysFor(provider, names) {
|
|
31
|
+
const re = KEY_NAMES[provider];
|
|
32
|
+
return re ? names.filter((n) => re.test(n)) : [];
|
|
33
|
+
}
|
|
34
|
+
/* The name offered for a new key: MISTRAL_DICTATION_KEY, then _2... when taken. */
|
|
35
|
+
export function newKeyName(provider, names = []) {
|
|
36
|
+
const base = `${provider === 'ovh' ? 'OVH_AI_ENDPOINTS' : String(provider).toUpperCase()}_DICTATION_KEY`;
|
|
37
|
+
if (!names.includes(base)) return base;
|
|
38
|
+
for (let i = 2; ; i++) if (!names.includes(`${base}_${i}`)) return `${base}_${i}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export class Engines {
|
|
42
|
+
#fetcher; #now; #cache = new Map();
|
|
43
|
+
constructor({ fetcher = fetch, now = Date.now } = {}) { this.#fetcher = fetcher; this.#now = now; }
|
|
44
|
+
static base(provider) { return (PROVIDERS[provider]?.models ?? []).map((m) => ({ ...m })); }
|
|
45
|
+
/* The models of `provider`, read with `key` (a value, opened by the caller) when there is one. */
|
|
46
|
+
async models(provider, key, cacheKey = provider) {
|
|
47
|
+
const p = PROVIDERS[provider];
|
|
48
|
+
if (!p || !p.url) return [];
|
|
49
|
+
if (!key) return Engines.base(provider);
|
|
50
|
+
const kept = this.#cache.get(cacheKey);
|
|
51
|
+
if (kept && this.#now() - kept.at < MODELS_TTL_MS) return kept.models.map((m) => ({ ...m }));
|
|
52
|
+
let models;
|
|
53
|
+
try {
|
|
54
|
+
const r = await this.#fetcher(p.url.replace(/\/audio\/transcriptions\/?$/, '/models'), { redirect: 'error', headers: { authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(8000) });
|
|
55
|
+
if (!r.ok) throw new Error(String(r.status));
|
|
56
|
+
const body = await r.json();
|
|
57
|
+
const ids = [...new Set((Array.isArray(body?.data) ? body.data : []).map((m) => String(m?.id ?? '')).filter(isSpeechToText))];
|
|
58
|
+
const known = new Map(p.models.map((m) => [m.id, m.label]));
|
|
59
|
+
/* The known ones first, in their order; then the provider's others. */
|
|
60
|
+
models = [...p.models.filter((m) => ids.includes(m.id)), ...ids.filter((id) => !known.has(id)).sort().map((id) => ({ id, label: '' }))];
|
|
61
|
+
if (models.length === 0) throw new Error('none');
|
|
62
|
+
} catch { return Engines.base(provider); } /* not kept: tried again next time */
|
|
63
|
+
this.#cache.set(cacheKey, { at: this.#now(), models });
|
|
64
|
+
return models.map((m) => ({ ...m }));
|
|
65
|
+
}
|
|
66
|
+
/* Every provider, its models (read with the first key that looks like its own) and those keys. */
|
|
67
|
+
async catalogue(names, reveal = () => undefined) {
|
|
68
|
+
return Promise.all(Object.entries(PROVIDERS).map(async ([id, p]) => {
|
|
69
|
+
const keys = keysFor(id, names);
|
|
70
|
+
const models = await this.models(id, keys[0] ? reveal(keys[0]) : undefined, `${id} ${keys[0] ?? ''}`);
|
|
71
|
+
return { id, label: p.label, url: p.url, model: p.model, models, keys };
|
|
72
|
+
}));
|
|
73
|
+
}
|
|
74
|
+
/* For the slots not set yet ("main", "backup"): a provider with a key, its first model. The backup is
|
|
75
|
+
another provider than the main's. */
|
|
76
|
+
async suggestions({ main, backup }, names, reveal) {
|
|
77
|
+
const all = await this.catalogue(names, reveal);
|
|
78
|
+
const usable = ORDER.map((id) => all.find((p) => p.id === id)).filter((p) => p.keys.length > 0);
|
|
79
|
+
const out = [];
|
|
80
|
+
let mainProvider = main?.provider;
|
|
81
|
+
if (!main) {
|
|
82
|
+
const p = usable[0];
|
|
83
|
+
if (p) { out.push({ slot: 'main', provider: p.id, model: p.models[0]?.id ?? p.model, secret: p.keys[0] }); mainProvider = p.id; }
|
|
84
|
+
}
|
|
85
|
+
if (!backup) {
|
|
86
|
+
const p = usable.find((x) => x.id !== mainProvider);
|
|
87
|
+
if (p) out.push({ slot: 'backup', provider: p.id, model: p.models[0]?.id ?? p.model, secret: p.keys[0] });
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
}
|