clavarium 0.2.117-beta.1 → 0.2.118-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/README.md +4 -0
- package/deploy/install.sh +7 -1
- package/deploy/updater.mjs +26 -7
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/server/boxes.mjs +76 -9
- package/server/main.mjs +6 -1
- package/server/pocket.mjs +128 -0
- package/server/speech.mjs +8 -3
- package/server/voice.mjs +24 -0
package/README.md
CHANGED
|
@@ -301,3 +301,7 @@ Without a guard, nothing commits. That is on purpose.
|
|
|
301
301
|
## Licence
|
|
302
302
|
|
|
303
303
|
MIT. See `LICENSE`.
|
|
304
|
+
|
|
305
|
+
## Credits
|
|
306
|
+
|
|
307
|
+
The voice boxes speak with **Pocket TTS** by **Kyutai** (program MIT, weights CC-BY-4.0), fetched at run time; Piper voices (sherpa-onnx) are the fallback. See CREDITS.md in the repository.
|
package/deploy/install.sh
CHANGED
|
@@ -317,8 +317,14 @@ chmod 0755 /usr/local/bin/clavarium
|
|
|
317
317
|
install -d -o root -g root -m 0755 "$ETC"
|
|
318
318
|
printf 'DATA=%s\nMNT=%s\n' "$DATA" "$MNT" > "$ETC/host.conf"; chmod 0644 "$ETC/host.conf"
|
|
319
319
|
rule="$(mktemp)"
|
|
320
|
-
printf '# Clavarium: the server account may run ONE program as root, and nothing else.\n%s ALL=(root) NOPASSWD: %s\n
|
|
320
|
+
printf '# Clavarium: the server account may run ONE program as root, and nothing else.\n%s ALL=(root) NOPASSWD: %s\n' "$ACCOUNT" "$HOST_PROGRAM" > "$rule"
|
|
321
321
|
visudo -cf "$rule" >/dev/null || refuse "the sudo rule did not pass its check"
|
|
322
|
+
# Its probes every few seconds kept out of the system log, with what this sudo takes (the updater does the same).
|
|
323
|
+
for quiet in '!syslog, !pam_session' '!pam_session'; do
|
|
324
|
+
cp "$rule" "$rule.q"; printf 'Defaults:%s %s\n' "$ACCOUNT" "$quiet" >> "$rule.q"
|
|
325
|
+
if out="$(visudo -cf "$rule.q" 2>&1)" && ! printf '%s' "$out" | grep -qiE 'unknown setting|syntax error|parse error'; then mv "$rule.q" "$rule"; break; fi
|
|
326
|
+
rm -f "$rule.q"
|
|
327
|
+
done
|
|
322
328
|
install -o root -g root -m 0440 "$rule" /etc/sudoers.d/clavarium; rm -f -- "$rule"
|
|
323
329
|
|
|
324
330
|
step "what the machines are given, on root's chain"
|
package/deploy/updater.mjs
CHANGED
|
@@ -119,17 +119,36 @@ export async function ensureProxySettings({ file = PROXY_CFG, run = runCommand }
|
|
|
119
119
|
each call -- some 800 lines in ten minutes, nothing to read in them (found 31-10). The account may run
|
|
120
120
|
that one program and nothing else; what changes something, the program logs itself (clavarium-host). */
|
|
121
121
|
export const SUDOERS = '/etc/sudoers.d/clavarium';
|
|
122
|
-
|
|
122
|
+
/* What sudo is told, tried in this order: the first its version takes without a word wins. Some sudo builds do
|
|
123
|
+
not know « syslog » (found 01-11 on a real server: « unknown setting: 'syslog' » on every call); they keep
|
|
124
|
+
the session lines quiet at least. A line of ours their sudo does not take is replaced. */
|
|
125
|
+
export const QUIET_SETTINGS = ['!syslog, !pam_session', '!pam_session'];
|
|
126
|
+
export const quietLine = (account, setting = QUIET_SETTINGS[0]) => `Defaults:${account} ${setting}`;
|
|
127
|
+
const QUIET_COMMENT = '# Added by the Clavarium updater: its probes every few seconds are not written to the system log.';
|
|
123
128
|
export async function ensureQuietSudo({ file = SUDOERS, run = runCommand } = {}) {
|
|
124
129
|
let text;
|
|
125
130
|
try { text = readFileSync(file, 'utf8'); } catch { return false; }
|
|
126
131
|
const account = text.match(/^([a-z_][a-z0-9_-]*)\s+ALL=\(root\)\s+NOPASSWD:/m)?.[1];
|
|
127
|
-
if (!account
|
|
128
|
-
const
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
132
|
+
if (!account) return false;
|
|
133
|
+
const accepted = async (candidate) => {
|
|
134
|
+
rmSync(`${file}.new`, { force: true });
|
|
135
|
+
writeFileSync(`${file}.new`, candidate, { mode: 0o440 });
|
|
136
|
+
const r = await run(['visudo', '-cf', `${file}.new`], { timeoutMs: 30_000 });
|
|
137
|
+
return r.code === 0 && !/unknown setting|syntax error|parse error/i.test(`${r.stdout}\n${r.stderr}`);
|
|
138
|
+
};
|
|
139
|
+
/* The rule as it is, without any line of ours. */
|
|
140
|
+
const base = text.split('\n').filter((l) => l !== QUIET_COMMENT && !l.startsWith(`Defaults:${account} `)).join('\n').replace(/\n*$/, '\n');
|
|
141
|
+
const current = QUIET_SETTINGS.map((q) => quietLine(account, q)).find((l) => text.includes(l));
|
|
142
|
+
try {
|
|
143
|
+
if (current && await accepted(text)) return false; /* ours, and taken as it is */
|
|
144
|
+
for (const setting of QUIET_SETTINGS) {
|
|
145
|
+
const next = `${base}${QUIET_COMMENT}\n${quietLine(account, setting)}\n`;
|
|
146
|
+
if (await accepted(next)) { renameSync(`${file}.new`, file); return true; }
|
|
147
|
+
}
|
|
148
|
+
/* None taken: the rule alone, as install.sh wrote it -- never a file sudo complains about. */
|
|
149
|
+
if (current && await accepted(base)) { renameSync(`${file}.new`, file); return true; }
|
|
150
|
+
return false;
|
|
151
|
+
} finally { rmSync(`${file}.new`, { force: true }); }
|
|
133
152
|
}
|
|
134
153
|
|
|
135
154
|
/* FFMPEG, kept by the updater: the voice boxes play a radio, a podcast, a music file through it
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.118-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.118-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
14
|
"clavarium-binder": "0.1.43-next.1",
|
|
15
15
|
"clavarium-docket": "0.1.1",
|
|
16
|
-
"clavarium-parley": "0.17.
|
|
16
|
+
"clavarium-parley": "0.17.35-next.1",
|
|
17
17
|
"clavarium-tether": "0.1.0-next.46",
|
|
18
18
|
"mermaid": "11.17.2",
|
|
19
19
|
"node-pty": "^1.1.0",
|
|
@@ -747,9 +747,9 @@
|
|
|
747
747
|
}
|
|
748
748
|
},
|
|
749
749
|
"node_modules/clavarium-parley": {
|
|
750
|
-
"version": "0.17.
|
|
751
|
-
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.
|
|
752
|
-
"integrity": "sha512-
|
|
750
|
+
"version": "0.17.35-next.1",
|
|
751
|
+
"resolved": "https://registry.npmjs.org/clavarium-parley/-/clavarium-parley-0.17.35-next.1.tgz",
|
|
752
|
+
"integrity": "sha512-bUR/1I9ZqEXWJ7SoxPYdkjlOHJ8dnML5A0ZQGfuEOl4YNuB6ULT4PoWqHfj0fVhY2j6BjDLvHJKZJ8WouEGXig==",
|
|
753
753
|
"license": "MIT",
|
|
754
754
|
"bin": {
|
|
755
755
|
"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.118-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.",
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"@xterm/xterm": "^6.0.0",
|
|
47
47
|
"clavarium-binder": "0.1.43-next.1",
|
|
48
48
|
"clavarium-docket": "0.1.1",
|
|
49
|
-
"clavarium-parley": "0.17.
|
|
49
|
+
"clavarium-parley": "0.17.35-next.1",
|
|
50
50
|
"clavarium-tether": "0.1.0-next.46",
|
|
51
51
|
"mermaid": "11.17.2",
|
|
52
52
|
"node-pty": "^1.1.0",
|
package/server/boxes.mjs
CHANGED
|
@@ -123,6 +123,27 @@ export function offsetOf(zone, now) {
|
|
|
123
123
|
}
|
|
124
124
|
|
|
125
125
|
export const RELAY_WITHIN_MS = 20_000;
|
|
126
|
+
/* Sentences to say one by one: cut after . ! ? … and kept at 40 characters at least (a tiny one joins the next). */
|
|
127
|
+
export function sentencesOf(text) {
|
|
128
|
+
const out = [];
|
|
129
|
+
for (const piece of String(text).split(/(?<=[.!?…])\s+/)) {
|
|
130
|
+
if (out.length && out[out.length - 1].length < 40) out[out.length - 1] += ` ${piece}`; else out.push(piece);
|
|
131
|
+
}
|
|
132
|
+
return out.filter(Boolean);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export const THINKING_AFTER_MS = 3_500;
|
|
136
|
+
export const LONGER_AFTER_MS = 12_000;
|
|
137
|
+
export const THINKING = ['Hmm…', 'Voyons…', 'Hmm, voyons voir…'];
|
|
138
|
+
/* WHY A BOX LISTENED, in a few words beside the message (01-11): what woke it (and the wake word's score), and
|
|
139
|
+
what it cut short. */
|
|
140
|
+
export function whyOf(m) {
|
|
141
|
+
const reason = { wake: 'mot d\'éveil', button: 'bouton', follow: 'suite de la conversation', knock: 'toc-toc' }[m?.reason] ?? (m?.reason ? String(m.reason).slice(0, 30) : 'inconnu');
|
|
142
|
+
const score = Number.isFinite(m?.score) ? ` (${Math.round(m.score * 100)} %)` : '';
|
|
143
|
+
const cut = m?.cut ? ` ; a interrompu ${String(m.cut) === 'its own speech' ? 'sa propre phrase' : 'un son'}` : '';
|
|
144
|
+
return `réveil : ${reason}${score}${cut}`;
|
|
145
|
+
}
|
|
146
|
+
|
|
126
147
|
export const DOING_WITHIN_MS = 120_000;
|
|
127
148
|
/* A LONG RECORDING (a meeting, a class): asked in words, stopped by the button or the wake word. */
|
|
128
149
|
export const RECORD_ASKED = /\b(?:lance|d[ée]marre|commence|d[ée]bute)\w*\b.{0,25}\benregistrement\b|\benregistre\b.{0,20}\b(?:r[ée]union|conversation|cours|discussion|consultation)\b/i;
|
|
@@ -131,6 +152,22 @@ export const mmss = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${Str
|
|
|
131
152
|
/* THE MIXER of a box that plays a stream: words said meanwhile go over it, the stream lowered to DUCK while
|
|
132
153
|
they last, with a fade down and up (a quarter of a second) rather than a jump. One 20 ms chunk at a time. */
|
|
133
154
|
export const DUCK = 0.2;
|
|
155
|
+
/* LEVELS (01-11): like a phone, one volume for the whole box (set, and eased to the room by the box itself),
|
|
156
|
+
and under it each kind of sound brought to its own steady level -- a loud radio and a quiet one played alike
|
|
157
|
+
(ffmpeg's loudnorm, EBU R128), the radio a step below the box's voice, its voice always at one loudness. */
|
|
158
|
+
export const STREAM_LUFS = -26;
|
|
159
|
+
export const STREAM_LEVEL = 1;
|
|
160
|
+
export const VOICE_RMS = 3300; /* about -20 dBFS: the loudness the voice was found right at */
|
|
161
|
+
export function levelled(pcm, target = VOICE_RMS) {
|
|
162
|
+
let sum = 0; let n = 0;
|
|
163
|
+
for (let i = 0; i + 1 < pcm.length; i += 2) { const v = pcm.readInt16LE(i); if (Math.abs(v) > 300) { sum += v * v; n++; } }
|
|
164
|
+
if (n < 100) return pcm;
|
|
165
|
+
const gain = Math.min(4, target / Math.sqrt(sum / n));
|
|
166
|
+
if (Math.abs(gain - 1) < 0.05) return pcm;
|
|
167
|
+
const out = Buffer.alloc(pcm.length & ~1);
|
|
168
|
+
for (let i = 0; i + 1 < pcm.length; i += 2) out.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(pcm.readInt16LE(i) * gain))), i);
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
134
171
|
export function mix(stream, chunk) {
|
|
135
172
|
const words = stream.over[0];
|
|
136
173
|
const target = words ? DUCK : 1;
|
|
@@ -138,7 +175,7 @@ export function mix(stream, chunk) {
|
|
|
138
175
|
const step = (1 - DUCK) / (0.25 * 16_000);
|
|
139
176
|
for (let i = 0; i < chunk.length; i += 2) {
|
|
140
177
|
stream.gain += Math.max(-step, Math.min(step, target - stream.gain));
|
|
141
|
-
let v = chunk.readInt16LE(i) * stream.gain;
|
|
178
|
+
let v = chunk.readInt16LE(i) * stream.gain * STREAM_LEVEL;
|
|
142
179
|
if (words && stream.gain <= DUCK + 0.05) {
|
|
143
180
|
stream.at ??= 0;
|
|
144
181
|
if (stream.at + 1 < words.length) { v += words.readInt16LE(stream.at); stream.at += 2; }
|
|
@@ -175,11 +212,12 @@ export function piecesOf(pcm, { least = 8, most = 14 } = {}) {
|
|
|
175
212
|
|
|
176
213
|
export class Boxes {
|
|
177
214
|
#file; #codes = new Map(); #links = new Map(); #tries = []; #now;
|
|
178
|
-
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep;
|
|
215
|
+
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep; #react;
|
|
179
216
|
|
|
180
217
|
/* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
|
|
181
218
|
exists(conversation), hear(wav) -> text, say(conversation, text, room), speak(text) -> PCM 16 kHz. */
|
|
182
|
-
constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch, recordDir = null, parts = null, keep = null }) {
|
|
219
|
+
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 }) {
|
|
220
|
+
this.#react = react;
|
|
183
221
|
this.#spawn = spawn; this.#fetch = fetcher; this.#recordDir = recordDir; this.#parts = parts; this.#keep = keep;
|
|
184
222
|
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;
|
|
185
223
|
}
|
|
@@ -307,7 +345,7 @@ export class Boxes {
|
|
|
307
345
|
this.stop(id);
|
|
308
346
|
const source = await this.#resolve(url);
|
|
309
347
|
let child;
|
|
310
|
-
try { child = this.#spawn('ffmpeg', ['-nostdin', '-loglevel', 'error', '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5', '-i', source, '-vn', '-ac', '1', '-ar', '16000', '-f', 's16le', '-'], { stdio: ['ignore', 'pipe', 'pipe'] }); }
|
|
348
|
+
try { child = this.#spawn('ffmpeg', ['-nostdin', '-loglevel', 'error', '-reconnect', '1', '-reconnect_streamed', '1', '-reconnect_delay_max', '5', '-i', source, '-vn', '-af', `loudnorm=I=${STREAM_LUFS}:TP=-3:LRA=11`, '-ac', '1', '-ar', '16000', '-f', 's16le', '-'], { stdio: ['ignore', 'pipe', 'pipe'] }); }
|
|
311
349
|
catch { throw new Refusal(501, 'This server cannot read sounds: ffmpeg is not installed (an update installs it).'); }
|
|
312
350
|
const box = link.box(); const label = name || new URL(url).host;
|
|
313
351
|
const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '', over: [], gain: 1 };
|
|
@@ -404,6 +442,23 @@ export class Boxes {
|
|
|
404
442
|
/* The tool said or asked something in a conversation: said aloud only by the boxes it is
|
|
405
443
|
addressed to (`to`: box ids, #215). Anything else stays in the thread, silent -- a box
|
|
406
444
|
read a whole technical message aloud once (31-10), which nobody wants. */
|
|
445
|
+
/* WHILE THE ANSWER IS THOUGHT (01-11): no long silence after a sentence. A short « hmm » if nothing has
|
|
446
|
+
come after a little while, then a word that it takes longer; whatever the assistant says first (an answer,
|
|
447
|
+
what it is doing) ends the wait. A longer question (many words) is told sooner that it takes a moment. */
|
|
448
|
+
#waitFor(link, text = '') {
|
|
449
|
+
clearTimeout(link.thinkingA); clearTimeout(link.thinkingB);
|
|
450
|
+
const said = link.heardAt;
|
|
451
|
+
const still = () => link.heardAt === said && !((link.answeredAt ?? 0) >= said);
|
|
452
|
+
const long = String(text).length > 160; /* a long question: told sooner that it takes a moment */
|
|
453
|
+
const say = async (words) => { if (!still() || link.recording || this.#streams.has(link.box().id)) return; try { link.play(await this.#speak(words)); } catch { /* the light says it */ } };
|
|
454
|
+
/* Made at once, used if the answer is still not there: a reaction to THIS sentence, in its language. */
|
|
455
|
+
let made = null;
|
|
456
|
+
this.#react(text).then((t) => { made = t; }).catch(() => {});
|
|
457
|
+
link.thinkingA = setTimeout(() => { void say(made || THINKING[Math.floor(Math.random() * THINKING.length)]); }, THINKING_AFTER_MS);
|
|
458
|
+
link.thinkingB = setTimeout(() => { void say(long ? 'Ta question est riche, je regarde, un instant.' : 'Ça me demande un peu plus de temps, je regarde.'); }, long ? LONGER_AFTER_MS * 0.6 : LONGER_AFTER_MS);
|
|
459
|
+
link.thinkingA.unref?.(); link.thinkingB.unref?.();
|
|
460
|
+
}
|
|
461
|
+
|
|
407
462
|
async agentSaid(conversation, text, to = null, { doing = false, asked = false } = {}) {
|
|
408
463
|
/* What it is doing is written for a screen ("Tâche de fond : bêta 0.2.113…"): read aloud, it was words
|
|
409
464
|
from nowhere (31-10). Aloud, only a short plain one; otherwise a word that it is at work. */
|
|
@@ -424,6 +479,7 @@ export class Boxes {
|
|
|
424
479
|
asked for ("mode conversation"), or by itself after two sentences within three minutes (31-10);
|
|
425
480
|
it ends when nobody answers, or on "fin de la conversation". */
|
|
426
481
|
const question = !doing && (asked || /\?\s*$/.test(words));
|
|
482
|
+
for (const l of boxes) { l.answeredAt = this.#now(); clearTimeout(l.thinkingA); clearTimeout(l.thinkingB); }
|
|
427
483
|
for (const l of boxes) {
|
|
428
484
|
/* An answer -- to a sentence heard within a minute -- may open the conversation; something said
|
|
429
485
|
of itself (a news item, a reminder) does not: the box listened after it for nothing (31-10). */
|
|
@@ -431,9 +487,16 @@ export class Boxes {
|
|
|
431
487
|
const chatting = !doing && answering && this.#chatting(l);
|
|
432
488
|
const opening = chatting && !l.chat;
|
|
433
489
|
if (chatting) l.chat = true;
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
490
|
+
/* SENTENCE BY SENTENCE: the first is said while the next ones are made -- the answer starts sooner
|
|
491
|
+
(31-10: a few seconds of silence before each answer). The box queues them, one after the other. */
|
|
492
|
+
const parts = sentencesOf(opening ? `Je passe en mode conversation : je reste à l'écoute. ${words}` : words);
|
|
493
|
+
let next = this.#speak(parts[0]);
|
|
494
|
+
for (const [i, part] of parts.entries()) {
|
|
495
|
+
let pcm;
|
|
496
|
+
try { pcm = await next; } catch (error) { this.#log(`voice box: no voice for the answer (${error.message})`); l.send({ t: 'cue', name: 'error' }); break; }
|
|
497
|
+
if (i + 1 < parts.length) { next = this.#speak(parts[i + 1]); next.catch(() => {}); }
|
|
498
|
+
l.play(pcm, i + 1 === parts.length && (question || chatting) ? 'listen' : null); /* a question is always listened after: an answer is expected */
|
|
499
|
+
}
|
|
437
500
|
}
|
|
438
501
|
}
|
|
439
502
|
#chatting(link) {
|
|
@@ -451,7 +514,7 @@ export class Boxes {
|
|
|
451
514
|
socket, send, waiting: new Map(), heardAt: 0, muted: null, volume: null,
|
|
452
515
|
box: () => this.#all().find((b) => b.id === box.id) ?? box,
|
|
453
516
|
play: (pcm, then = null) => {
|
|
454
|
-
pcm = pcm.subarray(0, pcm.length & ~1); /* whole samples only
|
|
517
|
+
pcm = levelled(pcm.subarray(0, pcm.length & ~1)); /* whole samples only (an odd byte shifts every sample after it), at the voice's level */
|
|
455
518
|
/* Something is playing (a radio): the words go over it, the radio lowered meanwhile (the mixer, listen()). */
|
|
456
519
|
const playing = this.#streams.get(box.id);
|
|
457
520
|
if (playing) { playing.over.push(pcm); return; }
|
|
@@ -503,6 +566,9 @@ export class Boxes {
|
|
|
503
566
|
r.out.end(() => { void this.#recorded(link, r); });
|
|
504
567
|
return;
|
|
505
568
|
}
|
|
569
|
+
if (m.t === 'event' && m.name === 'wake.own') { this.#log(`voice box ${box.name}: heard its own voice say the wake word, ignored`); return; }
|
|
570
|
+
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; }
|
|
571
|
+
if (m.t === 'listen.start') link.why = whyOf(m);
|
|
506
572
|
if (m.t === 'listen.start') { if (this.stop(box.id)) this.#log(`voice box ${box.name}: stopped playing, someone speaks`); sentence = []; size = 0; return; }
|
|
507
573
|
if (m.t === 'listen.end' && sentence && m.reason === 'nobody') {
|
|
508
574
|
/* Listened again, nobody spoke: a conversation ends there, in silence. */
|
|
@@ -598,9 +664,10 @@ export class Boxes {
|
|
|
598
664
|
link.relay = 0;
|
|
599
665
|
text = `(réponse entendue de l'appareil, pas de la personne) ${text}`;
|
|
600
666
|
}
|
|
601
|
-
try { await this.#say(box.conversation, text, { id: box.id, name: box.name, ...(box.place ? { place: box.place } : {}) }); } catch (error) { this.#log(`voice box ${box.name}: ${seconds} s heard and dictated, but not said in ${box.conversation} (${error.message})`); await lost("Pardon, je n'ai pas pu transmettre ta phrase. Tu peux répéter ?"); return; }
|
|
667
|
+
try { await this.#say(box.conversation, text, { id: box.id, name: box.name, ...(box.place ? { place: box.place } : {}), ...(link.why ? { why: link.why } : {}) }); } catch (error) { this.#log(`voice box ${box.name}: ${seconds} s heard and dictated, but not said in ${box.conversation} (${error.message})`); await lost("Pardon, je n'ai pas pu transmettre ta phrase. Tu peux répéter ?"); return; }
|
|
602
668
|
this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
|
|
603
669
|
link.heardAt = this.#now();
|
|
670
|
+
this.#waitFor(link, text);
|
|
604
671
|
link.recent = [...(link.recent ?? []), link.heardAt];
|
|
605
672
|
if (/\bmode conversation\b/i.test(text)) link.chat = true;
|
|
606
673
|
if (/\b(?:fin|arr[eê]te|stop)\w*\b.{0,20}\b(?:conversation|[ée]couter)\b/i.test(text)) { link.chat = false; link.recent = []; }
|
package/server/main.mjs
CHANGED
|
@@ -77,6 +77,7 @@ import { Bundles } from './bundle.mjs';
|
|
|
77
77
|
import { migrateData } from './dataformat.mjs';
|
|
78
78
|
import { VmWatch } from './vmwatch.mjs';
|
|
79
79
|
import { Boxes, handleBoxes, voiceboxConnector, syncTargets, PAIR_PATH as BOX_PAIR_PATH, FIRMWARE_PATH as BOX_FIRMWARE_PATH } from './boxes.mjs';
|
|
80
|
+
import { Pocket } from './pocket.mjs';
|
|
80
81
|
import { Speech } from './speech.mjs';
|
|
81
82
|
import { WebSocketServer } from 'ws';
|
|
82
83
|
|
|
@@ -602,10 +603,14 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
602
603
|
void team.refresh().catch((error) => console.error(`operators: ${error.message}`));
|
|
603
604
|
const watching = setInterval(() => { void team.watch().catch(() => {}); }, 60_000); watching.unref?.();
|
|
604
605
|
}
|
|
605
|
-
const
|
|
606
|
+
const speechLog = (line) => events.add({ kind: 'server', text: line });
|
|
607
|
+
const speech = new Speech({ dir: `${dataDir}/voices`, log: speechLog, secret: (name) => { try { return secrets.reveal(name) ?? undefined; } catch { return undefined; } },
|
|
608
|
+
/* The voice by default: Kyutai's Pocket TTS, run here (pocket.mjs); CLAVARIUM_POCKET=0 to leave it out. */
|
|
609
|
+
pocket: process.env.CLAVARIUM_POCKET === '0' ? null : new Pocket({ dir: `${dataDir}/voices`, log: speechLog }) });
|
|
606
610
|
boxes = new Boxes({ file: new JsonFile(`${dataDir}/boxes.json`, []),
|
|
607
611
|
exists: (name) => all.list().some((c) => c.name === name),
|
|
608
612
|
/* A long recording (a meeting): transcribed in parts, kept beside the conversation for its assistant. */
|
|
613
|
+
react: (said) => voice.reaction(said),
|
|
609
614
|
recordDir: `${dataDir}/recordings`, parts: (wav) => voice.transcribeParts(wav), keep: (name, file, text) => talk.keepText(name, file, text),
|
|
610
615
|
hear: (wav) => voice.transcribe(wav, undefined, { oneVoice: true }), /* the language of the dictation settings, or found by the engine: no language is assumed (a box has no browser to tell one) */
|
|
611
616
|
/* Said as the person's own message, the room named (one speaker for now). */
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/* THE VOICE BY DEFAULT: Kyutai's Pocket TTS (chosen by ear on the real box, 01-11, over Piper, Kokoro and
|
|
2
|
+
* ElevenLabs' free credits). Open: its program is MIT, its weights CC-BY-4.0 -- Kyutai is credited
|
|
3
|
+
* (docs/CREDITS). Runs on this server, nothing sent anywhere: the program is fetched once from Kyutai's
|
|
4
|
+
* releases (its sha256 checked), its French model once from Hugging Face, then it serves on loopback.
|
|
5
|
+
*
|
|
6
|
+
* Said "posée" (01-11: « elle parle un peu vite et marque peu les espaces »): each clause made on its own,
|
|
7
|
+
* slowed by a tenth at the same pitch (ffmpeg atempo), with a silence after it -- longer after a sentence.
|
|
8
|
+
* Out: PCM 16 kHz, 16-bit, mono. */
|
|
9
|
+
import { existsSync, mkdirSync, createWriteStream, rmSync, readFileSync, renameSync } from 'node:fs';
|
|
10
|
+
import { pipeline } from 'node:stream/promises';
|
|
11
|
+
import { Readable } from 'node:stream';
|
|
12
|
+
import { createHash } from 'node:crypto';
|
|
13
|
+
import { execFile, spawn as spawnProcess } from 'node:child_process';
|
|
14
|
+
import { promisify } from 'node:util';
|
|
15
|
+
import { createServer } from 'node:net';
|
|
16
|
+
|
|
17
|
+
export const POCKET_VERSION = '3.3.0';
|
|
18
|
+
export const POCKET_RELEASE = 'https://github.com/kyutai-labs/pocket-tts/releases/download/v4.0.1';
|
|
19
|
+
export const POCKET_SHA256 = Object.freeze({
|
|
20
|
+
x64: '9abff0aa138a804e44052952d8c3bdaae247fb267ca8f4b83fe178897d1a0559',
|
|
21
|
+
arm64: '2b9a727bffd86ea6d73370d675cbd91a7db118f11b7f5a60343c2d5da12b187a',
|
|
22
|
+
});
|
|
23
|
+
export const TEMPO = 0.96; /* 01-11: 0.9 sounded sleepy; a touch slower than its own pace */
|
|
24
|
+
export const GAP_S = Object.freeze({ sentence: 0.42, pause: 0.25, comma: 0.16 });
|
|
25
|
+
|
|
26
|
+
/* A text in clauses, each with the silence that follows it. */
|
|
27
|
+
export function clausesOf(text) {
|
|
28
|
+
const out = [];
|
|
29
|
+
for (const piece of String(text).match(/[^.!?…;:,]+[.!?…;:,]*/g) ?? []) {
|
|
30
|
+
const t = piece.trim();
|
|
31
|
+
if (!t || !/[\p{L}\p{N}]/u.test(t)) continue;
|
|
32
|
+
const end = t.at(-1);
|
|
33
|
+
out.push({ text: t, gap: '.!?…'.includes(end) ? GAP_S.sentence : ';:'.includes(end) ? GAP_S.pause : end === ',' ? GAP_S.comma : GAP_S.sentence });
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/* Quiet at both ends cut, a little kept so no word is clipped. */
|
|
39
|
+
export function trimmed(pcm, { floor = 200, before = 800, after = 1600 } = {}) {
|
|
40
|
+
const n = pcm.length >> 1; let a = -1; let b = -1;
|
|
41
|
+
for (let i = 0; i < n; i++) if (Math.abs(pcm.readInt16LE(i * 2)) > floor) { if (a < 0) a = i; b = i; }
|
|
42
|
+
if (a < 0) return Buffer.alloc(0);
|
|
43
|
+
return pcm.subarray(Math.max(0, a - before) * 2, Math.min(n, b + after) * 2);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const free = () => new Promise((ok, ko) => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => ok(port)); }); s.on('error', ko); });
|
|
47
|
+
|
|
48
|
+
export class Pocket {
|
|
49
|
+
#dir; #fetch; #log; #spawn; #ffmpeg; #port = 0; #child = null; #starting = null; #language;
|
|
50
|
+
|
|
51
|
+
constructor({ dir, fetcher = fetch, log = () => {}, spawn = spawnProcess, ffmpeg = 'ffmpeg', language = 'french' }) {
|
|
52
|
+
this.#dir = dir; this.#fetch = fetcher; this.#log = log; this.#spawn = spawn; this.#ffmpeg = ffmpeg; this.#language = language;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/* The program, fetched once and checked: only Linux on x64 or arm64. */
|
|
56
|
+
async #program() {
|
|
57
|
+
const arch = process.arch === 'x64' ? 'x86_64' : process.arch === 'arm64' ? 'aarch64' : null;
|
|
58
|
+
if (process.platform !== 'linux' || !arch) throw new Error('Pocket TTS runs on Linux x64 or arm64 only');
|
|
59
|
+
const name = `pocket-tts-${POCKET_VERSION}-${arch}-unknown-linux-gnu`;
|
|
60
|
+
const bin = `${this.#dir}/${name}/pocket-tts`;
|
|
61
|
+
if (existsSync(bin)) return bin;
|
|
62
|
+
mkdirSync(this.#dir, { recursive: true });
|
|
63
|
+
const archive = `${this.#dir}/${name}.tar.gz`;
|
|
64
|
+
this.#log('speech: fetching Kyutai\'s Pocket TTS');
|
|
65
|
+
const r = await this.#fetch(`${POCKET_RELEASE}/${name}.tar.gz`);
|
|
66
|
+
if (!r.ok || !r.body) throw new Error(`Pocket TTS could not be fetched (${r.status})`);
|
|
67
|
+
await pipeline(Readable.fromWeb(r.body), createWriteStream(archive));
|
|
68
|
+
const sum = createHash('sha256').update(readFileSync(archive)).digest('hex');
|
|
69
|
+
if (sum !== POCKET_SHA256[process.arch]) { rmSync(archive, { force: true }); throw new Error('Pocket TTS: the download is not the expected one (sha256)'); }
|
|
70
|
+
const unpacking = `${this.#dir}/.unpacking-pocket`;
|
|
71
|
+
rmSync(unpacking, { recursive: true, force: true }); mkdirSync(unpacking);
|
|
72
|
+
await promisify(execFile)('tar', ['xzf', archive, '-C', unpacking]);
|
|
73
|
+
renameSync(`${unpacking}/${name}`, `${this.#dir}/${name}`);
|
|
74
|
+
rmSync(unpacking, { recursive: true, force: true }); rmSync(archive, { force: true });
|
|
75
|
+
return bin;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/* Its server on loopback, started once, kept; ready when it answers. */
|
|
79
|
+
async #ready() {
|
|
80
|
+
if (this.#child && this.#port) return this.#port;
|
|
81
|
+
this.#starting ??= (async () => {
|
|
82
|
+
const bin = await this.#program();
|
|
83
|
+
const port = await free();
|
|
84
|
+
const child = this.#spawn(bin, ['serve', '--host', '127.0.0.1', '--port', String(port), '--language', this.#language, '--quantize'], { env: { ...process.env, HF_HOME: `${this.#dir}/pocket-hf` }, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
85
|
+
let said = ''; child.stderr?.on('data', (d) => { said = `${said}${d}`.slice(-500); });
|
|
86
|
+
child.on('exit', () => { if (this.#child === child) { this.#child = null; this.#port = 0; } });
|
|
87
|
+
for (let i = 0; i < 300; i++) { /* the first time, its model comes from Hugging Face: a few minutes */
|
|
88
|
+
await new Promise((ok) => setTimeout(ok, 1000));
|
|
89
|
+
if (child.exitCode !== null) throw new Error(`Pocket TTS stopped: ${said.trim().split('\n').pop() ?? ''}`);
|
|
90
|
+
try { if ((await this.#fetch(`http://127.0.0.1:${port}/`, { signal: AbortSignal.timeout(2000) })).ok) { this.#child = child; this.#port = port; this.#log('speech: Pocket TTS ready'); return port; } } catch { /* not yet */ }
|
|
91
|
+
}
|
|
92
|
+
child.kill(); throw new Error('Pocket TTS did not start');
|
|
93
|
+
})().finally(() => { this.#starting = null; });
|
|
94
|
+
return this.#starting;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async #clause(text) {
|
|
98
|
+
const port = await this.#ready();
|
|
99
|
+
const form = new FormData(); form.append('text', text);
|
|
100
|
+
const r = await this.#fetch(`http://127.0.0.1:${port}/tts`, { method: 'POST', body: form, signal: AbortSignal.timeout(30_000) });
|
|
101
|
+
if (!r.ok) throw new Error(`Pocket TTS answered ${r.status}`);
|
|
102
|
+
const wav = Buffer.from(await r.arrayBuffer());
|
|
103
|
+
const rate = wav.readUInt32LE(24);
|
|
104
|
+
const pcm = wav.subarray(44, 44 + ((wav.length - 44) & ~1));
|
|
105
|
+
return trimmed(await this.#slowed(pcm, rate));
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/* Slower by a tenth, at the same pitch, to 16 kHz (ffmpeg, which the voice boxes use already). */
|
|
109
|
+
#slowed(pcm, rate) {
|
|
110
|
+
return new Promise((resolve, reject) => {
|
|
111
|
+
const c = this.#spawn(this.#ffmpeg, ['-nostdin', '-loglevel', 'error', '-f', 's16le', '-ar', String(rate), '-ac', '1', '-i', '-', '-af', `atempo=${TEMPO}`, '-ar', '16000', '-f', 's16le', '-'], { stdio: ['pipe', 'pipe', 'ignore'] });
|
|
112
|
+
const out = [];
|
|
113
|
+
c.stdout.on('data', (d) => out.push(d));
|
|
114
|
+
c.on('error', reject);
|
|
115
|
+
c.on('close', (code) => (code === 0 ? resolve(Buffer.concat(out)) : reject(new Error('ffmpeg could not slow the voice'))));
|
|
116
|
+
c.stdin.end(pcm);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/* Text -> PCM 16 kHz, clause by clause, with its silences. */
|
|
121
|
+
async speak(text) {
|
|
122
|
+
const parts = [];
|
|
123
|
+
for (const c of clausesOf(text)) { parts.push(await this.#clause(c.text), Buffer.alloc(Math.round(c.gap * 16_000) * 2)); }
|
|
124
|
+
return Buffer.concat(parts);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
stop() { this.#child?.kill(); this.#child = null; this.#port = 0; }
|
|
128
|
+
}
|
package/server/speech.mjs
CHANGED
|
@@ -44,10 +44,11 @@ export const ELEVEN_MODEL = 'eleven_multilingual_v2';
|
|
|
44
44
|
export const SPEED = 1.1; /* a little quicker than the voices' own pace: found slow on the real box (31-10) */
|
|
45
45
|
|
|
46
46
|
export class Speech {
|
|
47
|
-
#dir; #lang; #engine = null; #loading = null; #fetch; #log; #secret;
|
|
47
|
+
#dir; #lang; #engine = null; #loading = null; #fetch; #log; #secret; #pocket; #pocketDown = 0;
|
|
48
48
|
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
/* `pocket`: the default voice (pocket.mjs), else null. Then ElevenLabs when its key is set, then Piper. */
|
|
50
|
+
constructor({ dir, lang = 'fr', fetcher = fetch, log = () => {}, secret = () => undefined, pocket = null }) {
|
|
51
|
+
this.#dir = dir; this.#lang = VOICES[lang] ? lang : 'fr'; this.#fetch = fetcher; this.#log = log; this.#secret = secret; this.#pocket = pocket;
|
|
51
52
|
}
|
|
52
53
|
|
|
53
54
|
async #eleven(text) {
|
|
@@ -102,6 +103,10 @@ export class Speech {
|
|
|
102
103
|
|
|
103
104
|
/* Text -> PCM 16 kHz. */
|
|
104
105
|
async speak(text) {
|
|
106
|
+
/* Pocket first; failed, it rests five minutes and the next voice answers meanwhile. */
|
|
107
|
+
if (this.#pocket && Date.now() - this.#pocketDown > 5 * 60_000) {
|
|
108
|
+
try { const pcm = await this.#pocket.speak(text); if (pcm.length) return pcm; } catch (error) { this.#pocketDown = Date.now(); this.#log(`speech: Pocket TTS failed (${error.message}), another voice meanwhile`); }
|
|
109
|
+
}
|
|
105
110
|
const online = await this.#eleven(text);
|
|
106
111
|
if (online && online.length) return online;
|
|
107
112
|
const engine = await this.#load();
|
package/server/voice.mjs
CHANGED
|
@@ -191,6 +191,26 @@ export async function transcribeParts(config, audio, fetcher = fetch) {
|
|
|
191
191
|
return text ? [{ speaker: null, start: 0, text }] : [];
|
|
192
192
|
}
|
|
193
193
|
|
|
194
|
+
/* A SHORT REACTION while the answer is thought (a voice box, 01-11): a few words in the person's language that
|
|
195
|
+
acknowledge what was said without answering it -- « bonne question, voyons… ». Only where the dictation's
|
|
196
|
+
service also offers a fast chat model (OVH AI Endpoints); null otherwise, or when it is not quick. */
|
|
197
|
+
export const REACTION_MODEL = 'Mistral-Small-3.2-24B-Instruct-2506';
|
|
198
|
+
export async function quickReaction(config, said, fetcher = fetch) {
|
|
199
|
+
if (!config?.key || !DIARIZES.test(String(config.url))) return null;
|
|
200
|
+
const base = String(config.url).replace(/\/audio\/transcriptions\/?$/, '');
|
|
201
|
+
try {
|
|
202
|
+
const r = await fetcher(`${base}/chat/completions`, {
|
|
203
|
+
method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json', authorization: `Bearer ${config.key}` }, signal: AbortSignal.timeout(3000),
|
|
204
|
+
body: JSON.stringify({ model: REACTION_MODEL, temperature: 0.8, max_tokens: 24, messages: [
|
|
205
|
+
{ role: 'system', content: 'Someone just spoke to a voice assistant, which needs a few seconds to answer. Write ONE very short spoken reaction (2 to 7 words) in the SAME language as what they said, natural and warm, that acknowledges it without answering it and without promising anything: e.g. "Bonne question, voyons…", "Ah, intéressant, je regarde.", "Hmm, let me see…". No quotes, no emoji. Answer with the reaction only.' },
|
|
206
|
+
{ role: 'user', content: String(said).slice(0, 600) }] }),
|
|
207
|
+
});
|
|
208
|
+
if (!r.ok) return null;
|
|
209
|
+
const t = String((await r.json())?.choices?.[0]?.message?.content ?? '').replace(/["«»]/g, '').trim();
|
|
210
|
+
return t && t.length <= 60 && !/\n/.test(t) ? t : null;
|
|
211
|
+
} catch { return null; }
|
|
212
|
+
}
|
|
213
|
+
|
|
194
214
|
/* ---------- THE ENGINE CHOSEN IN SETTINGS ----------
|
|
195
215
|
* Settings > Dictation: a provider fills in the address and the model (both
|
|
196
216
|
* may be changed); the key is one of the SECRETS already kept (Assets >
|
|
@@ -324,6 +344,10 @@ export class Dictation {
|
|
|
324
344
|
/* An expired key is never sent: said in one line instead (still offered, so the line is seen). */
|
|
325
345
|
#fresh(c) { if (c?.secret && this.#expired(c.secret)) throw new Refusal(409, KEY_EXPIRED); }
|
|
326
346
|
/* `device`: the language of the device that dictates (a tag such as fr-FR), if it said. */
|
|
347
|
+
async reaction(said) {
|
|
348
|
+
const config = this.current();
|
|
349
|
+
return config ? quickReaction(config, said, this.#fetcher) : null;
|
|
350
|
+
}
|
|
327
351
|
async transcribeParts(audio) {
|
|
328
352
|
this.#fresh(this.#saved());
|
|
329
353
|
const config = this.current();
|