clavarium 0.2.192-next.1 → 0.2.194-next.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 +2 -2
- package/package.json +1 -1
- package/server/boxes.mjs +90 -7
- package/server/main.mjs +2 -0
- package/server/voice.mjs +30 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.194-next.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.194-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/boxes.mjs
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
* device door. Nothing is kept of the audio, here or on the box.
|
|
18
18
|
*/
|
|
19
19
|
import { spawn as spawnProcess } from 'node:child_process';
|
|
20
|
+
import { createWriteStream, mkdirSync, readFileSync, rmSync, statSync } from 'node:fs';
|
|
20
21
|
import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
|
|
21
22
|
import { Refusal } from './conversations.mjs';
|
|
22
23
|
|
|
@@ -26,7 +27,7 @@ export const LINK_PATH = '/c/api/box/ws';
|
|
|
26
27
|
/* A firmware a box downloads to update itself: a one-use address, kept a few minutes. */
|
|
27
28
|
export const FIRMWARE_PATH = '/c/api/box/firmware/';
|
|
28
29
|
export const FIRMWARE_MINUTES = 10;
|
|
29
|
-
export const SENTENCE_MAX =
|
|
30
|
+
export const SENTENCE_MAX = 300 * 32_000 + 32_000; /* 5 min of 16 kHz 16-bit mono, and some slack */
|
|
30
31
|
export const TRIES_PER_MINUTE = 10;
|
|
31
32
|
export const NAME_MAX = 40;
|
|
32
33
|
/* The volume a box is given when it connects, until someone sets another (its own default was soft). */
|
|
@@ -102,6 +103,31 @@ export function forSpeech(text) {
|
|
|
102
103
|
}
|
|
103
104
|
|
|
104
105
|
export const DOING_WITHIN_MS = 120_000;
|
|
106
|
+
/* A LONG RECORDING (a meeting, a class): asked in words, stopped by the button or the wake word. */
|
|
107
|
+
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;
|
|
108
|
+
export const RECORD_MAX_BYTES = 4 * 3600 * 32_000; /* four hours */
|
|
109
|
+
export const mmss = (s) => `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(Math.floor(s % 60)).padStart(2, '0')}`;
|
|
110
|
+
/* THE MIXER of a box that plays a stream: words said meanwhile go over it, the stream lowered to DUCK while
|
|
111
|
+
they last, with a fade down and up (a quarter of a second) rather than a jump. One 20 ms chunk at a time. */
|
|
112
|
+
export const DUCK = 0.2;
|
|
113
|
+
export function mix(stream, chunk) {
|
|
114
|
+
const words = stream.over[0];
|
|
115
|
+
const target = words ? DUCK : 1;
|
|
116
|
+
const out = Buffer.alloc(chunk.length);
|
|
117
|
+
const step = (1 - DUCK) / (0.25 * 16_000);
|
|
118
|
+
for (let i = 0; i < chunk.length; i += 2) {
|
|
119
|
+
stream.gain += Math.max(-step, Math.min(step, target - stream.gain));
|
|
120
|
+
let v = chunk.readInt16LE(i) * stream.gain;
|
|
121
|
+
if (words && stream.gain <= DUCK + 0.05) {
|
|
122
|
+
stream.at ??= 0;
|
|
123
|
+
if (stream.at + 1 < words.length) { v += words.readInt16LE(stream.at); stream.at += 2; }
|
|
124
|
+
}
|
|
125
|
+
out.writeInt16LE(Math.max(-32768, Math.min(32767, Math.round(v))), i);
|
|
126
|
+
}
|
|
127
|
+
if (words && stream.at + 1 >= words.length) { stream.over.shift(); stream.at = 0; }
|
|
128
|
+
return out;
|
|
129
|
+
}
|
|
130
|
+
|
|
105
131
|
export const CHAT_WITHIN_MS = 3 * 60_000;
|
|
106
132
|
export const LISTEN_AHEAD = 3 * 32_000; /* bytes: what a box is sent ahead of what it plays (its buffer holds 16 s) */
|
|
107
133
|
|
|
@@ -127,12 +153,12 @@ export function piecesOf(pcm, { least = 8, most = 14 } = {}) {
|
|
|
127
153
|
|
|
128
154
|
export class Boxes {
|
|
129
155
|
#file; #codes = new Map(); #links = new Map(); #tries = []; #now;
|
|
130
|
-
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map();
|
|
156
|
+
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep;
|
|
131
157
|
|
|
132
158
|
/* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
|
|
133
159
|
exists(conversation), hear(wav) -> text, say(conversation, text, room), speak(text) -> PCM 16 kHz. */
|
|
134
|
-
constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch }) {
|
|
135
|
-
this.#spawn = spawn; this.#fetch = fetcher;
|
|
160
|
+
constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch, recordDir = null, parts = null, keep = null }) {
|
|
161
|
+
this.#spawn = spawn; this.#fetch = fetcher; this.#recordDir = recordDir; this.#parts = parts; this.#keep = keep;
|
|
136
162
|
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;
|
|
137
163
|
}
|
|
138
164
|
|
|
@@ -247,7 +273,7 @@ export class Boxes {
|
|
|
247
273
|
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'] }); }
|
|
248
274
|
catch { throw new Refusal(501, 'This server cannot read sounds: ffmpeg is not installed (an update installs it).'); }
|
|
249
275
|
const box = link.box(); const label = name || new URL(url).host;
|
|
250
|
-
const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '' };
|
|
276
|
+
const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '', over: [], gain: 1 };
|
|
251
277
|
this.#streams.set(id, stream);
|
|
252
278
|
link.send({ t: 'speak.start', rate: 16_000 });
|
|
253
279
|
child.stdout.on('data', (d) => { stream.queue.push(d); stream.queued += d.length; if (stream.queued > LISTEN_AHEAD * 4) child.stdout.pause(); });
|
|
@@ -260,7 +286,7 @@ export class Boxes {
|
|
|
260
286
|
const due = (this.#now() - stream.started) * 32 + LISTEN_AHEAD; /* bytes the box should have by now, a few seconds ahead */
|
|
261
287
|
while (stream.sent + 640 <= due && (carry.length >= 640 || stream.queue.length)) {
|
|
262
288
|
if (carry.length < 640) { const d = stream.queue.shift(); stream.queued -= d.length; carry = Buffer.concat([carry, d]); continue; }
|
|
263
|
-
if (link.socket.readyState === 1) link.socket.send(carry.subarray(0, 640));
|
|
289
|
+
if (link.socket.readyState === 1) link.socket.send(mix(stream, carry.subarray(0, 640)));
|
|
264
290
|
carry = carry.subarray(640); stream.sent += 640;
|
|
265
291
|
}
|
|
266
292
|
if (stream.queued < LISTEN_AHEAD) child.stdout.resume();
|
|
@@ -380,6 +406,9 @@ export class Boxes {
|
|
|
380
406
|
box: () => this.#all().find((b) => b.id === box.id) ?? box,
|
|
381
407
|
play: (pcm, then = null) => {
|
|
382
408
|
pcm = pcm.subarray(0, pcm.length & ~1); /* whole samples only: an odd byte shifts every sample after it */
|
|
409
|
+
/* Something is playing (a radio): the words go over it, the radio lowered meanwhile (the mixer, listen()). */
|
|
410
|
+
const playing = this.#streams.get(box.id);
|
|
411
|
+
if (playing) { playing.over.push(pcm); return; }
|
|
383
412
|
send({ t: 'speak.start', rate: 16_000 });
|
|
384
413
|
for (let at = 0; at < pcm.length; at += 640) if (socket.readyState === 1) socket.send(pcm.subarray(at, at + 640));
|
|
385
414
|
send({ t: 'speak.end', ...(then ? { then } : {}) });
|
|
@@ -392,6 +421,12 @@ export class Boxes {
|
|
|
392
421
|
seen();
|
|
393
422
|
socket.on('message', (data, binary) => {
|
|
394
423
|
if (binary) {
|
|
424
|
+
if (link.recording) {
|
|
425
|
+
const r = link.recording;
|
|
426
|
+
if (r.bytes + data.length > RECORD_MAX_BYTES) { if (!r.full) { r.full = true; send({ t: 'record', on: false }); } return; }
|
|
427
|
+
r.out.write(data); r.bytes += data.length;
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
395
430
|
if (!sentence || link.muted) return;
|
|
396
431
|
size += data.length;
|
|
397
432
|
if (size <= SENTENCE_MAX) sentence.push(Buffer.from(data));
|
|
@@ -408,6 +443,18 @@ export class Boxes {
|
|
|
408
443
|
if (m.volume !== wanted) { send({ t: 'volume', id: randomUUID(), level: wanted }); m.volume = wanted; }
|
|
409
444
|
}
|
|
410
445
|
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; }
|
|
446
|
+
if (m.t === 'record.start' && this.#recordDir) {
|
|
447
|
+
mkdirSync(this.#recordDir, { recursive: true });
|
|
448
|
+
const file = `${this.#recordDir}/${box.id}-${this.#now()}.pcm`;
|
|
449
|
+
link.recording = { file, out: createWriteStream(file), bytes: 0, at: this.#now() };
|
|
450
|
+
this.#log(`voice box ${box.name}: recording`);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (m.t === 'record.end' && link.recording) {
|
|
454
|
+
const r = link.recording; link.recording = null;
|
|
455
|
+
r.out.end(() => { void this.#recorded(link, r); });
|
|
456
|
+
return;
|
|
457
|
+
}
|
|
411
458
|
if (m.t === 'listen.start') { if (this.stop(box.id)) this.#log(`voice box ${box.name}: stopped playing, someone speaks`); sentence = []; size = 0; return; }
|
|
412
459
|
if (m.t === 'listen.end' && sentence && m.reason === 'nobody') {
|
|
413
460
|
/* Listened again, nobody spoke: a conversation ends there, in silence. */
|
|
@@ -430,10 +477,40 @@ export class Boxes {
|
|
|
430
477
|
}
|
|
431
478
|
if ((m.t === 'ack' || m.t === 'wifi.scan.result') && typeof m.id === 'string') { link.waiting.get(m.id)?.(m); link.waiting.delete(m.id); }
|
|
432
479
|
});
|
|
433
|
-
socket.on('close', () => { if (
|
|
480
|
+
socket.on('close', () => { if (link.recording) { const r = link.recording; link.recording = null; r.out.end(() => { void this.#recorded(link, r); }); }
|
|
481
|
+
if (this.#links.get(box.id) === link) { this.stop(box.id); this.#links.delete(box.id); this.#log(`voice box ${box.name}: disconnected`); } });
|
|
434
482
|
socket.on('error', () => {});
|
|
435
483
|
}
|
|
436
484
|
|
|
485
|
+
/* A recording ended: transcribed in parts of five minutes (cut at a quiet moment), who speaks noted when the
|
|
486
|
+
engine tells voices apart; the text kept beside the conversation, and said there in a short line, so its
|
|
487
|
+
assistant writes what was asked of it. The sound itself is not kept. */
|
|
488
|
+
async #recorded(link, r) {
|
|
489
|
+
const box = link.box();
|
|
490
|
+
const minutes = Math.round(r.bytes / 32_000 / 60);
|
|
491
|
+
this.#log(`voice box ${box.name}: recording ended, ${minutes} min, transcribing`);
|
|
492
|
+
try { if (link.socket.readyState === 1) link.play(await this.#speak(`Enregistrement terminé, ${minutes} minute${minutes > 1 ? 's' : ''}. Je transcris, je te dis quand c'est prêt.`)); } catch { /* the light says it */ }
|
|
493
|
+
let pcm;
|
|
494
|
+
try { pcm = readFileSync(r.file); } catch (error) { this.#log(`voice box ${box.name}: the recording cannot be read (${error.message})`); return; }
|
|
495
|
+
const lines = []; let offset = 0; let failed = 0;
|
|
496
|
+
const pieces = piecesOf(pcm, { least: 270, most: 300 });
|
|
497
|
+
for (const [i, piece] of pieces.entries()) {
|
|
498
|
+
try {
|
|
499
|
+
const parts = await this.#parts(wavOf(piece));
|
|
500
|
+
for (const p of parts) lines.push(`[${mmss(offset + p.start)}]${p.speaker === null ? '' : ` Voix ${p.speaker + 1}${pieces.length > 1 ? ` (partie ${i + 1})` : ''}`} : ${p.text}`);
|
|
501
|
+
} catch (error) { failed++; lines.push(`[${mmss(offset)}] (cette partie n'a pas pu être transcrite : ${error.message})`); }
|
|
502
|
+
offset += piece.length / 32_000;
|
|
503
|
+
}
|
|
504
|
+
rmSync(r.file, { force: true });
|
|
505
|
+
const stamp = new Date(r.at).toISOString().slice(0, 16).replace(/[-:T]/g, '');
|
|
506
|
+
const head = `Enregistrement du boîtier ${box.name}${box.place ? ` (${box.place})` : ''}, ${new Date(r.at).toISOString().slice(0, 16).replace('T', ' ')} UTC, ${minutes} min.\nLes voix sont numérotées par partie de 5 minutes : une même personne peut changer de numéro d'une partie à l'autre.\n\n`;
|
|
507
|
+
let path = null;
|
|
508
|
+
try { path = this.#keep?.(box.conversation, `enregistrement-${stamp}.txt`, head + lines.join('\n')) ?? null; } catch (error) { this.#log(`voice box ${box.name}: the transcript cannot be kept (${error.message})`); }
|
|
509
|
+
this.#log(`voice box ${box.name}: recording transcribed (${lines.length} lines${failed ? `, ${failed} part(s) failed` : ''})`);
|
|
510
|
+
const note = path ? `Enregistrement de ${minutes} min terminé et transcrit (qui parle, minute par minute) : ${path}. Fais-en ce que la personne demande ; sinon un compte rendu court : sujets, décisions, choses à faire.` : `Enregistrement de ${minutes} min terminé, mais la transcription n'a pas pu être rangée.`;
|
|
511
|
+
try { await this.#say(box.conversation, note, { id: box.id, name: box.name, ...(box.place ? { place: box.place } : {}) }); } catch (error) { this.#log(`voice box ${box.name}: the recording's line not said (${error.message})`); }
|
|
512
|
+
}
|
|
513
|
+
|
|
437
514
|
/* Each step said in the server's log, never what was said: its length only. */
|
|
438
515
|
async #heard(link, pcm) {
|
|
439
516
|
const box0 = link.box();
|
|
@@ -452,6 +529,12 @@ export class Boxes {
|
|
|
452
529
|
} catch (error) { this.#log(`voice box ${box0.name}: ${seconds} s heard, dictation failed (${error.message})`); await lost('Pardon, la dictée ne répond pas. Tu peux répéter ?'); return; }
|
|
453
530
|
if (!text) { this.#log(`voice box ${box0.name}: ${seconds} s heard, nothing recognised (silence?)`); await lost("Pardon, je n'ai rien compris. Tu peux répéter ?"); return; }
|
|
454
531
|
const box = link.box();
|
|
532
|
+
if (RECORD_ASKED.test(text) && this.#recordDir && this.#parts) {
|
|
533
|
+
this.#log(`voice box ${box.name}: a recording asked`);
|
|
534
|
+
try { link.play(await this.#speak("J'enregistre. Pour arrêter, appuie sur le bouton ou dis le mot d'éveil.")); } catch { /* no voice: the light says it */ }
|
|
535
|
+
link.send({ t: 'record', on: true });
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
455
538
|
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; }
|
|
456
539
|
this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
|
|
457
540
|
link.heardAt = this.#now();
|
package/server/main.mjs
CHANGED
|
@@ -605,6 +605,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
605
605
|
const speech = new Speech({ dir: `${dataDir}/voices`, log: (line) => events.add({ kind: 'server', text: line }), secret: (name) => { try { return secrets.reveal(name) ?? undefined; } catch { return undefined; } } });
|
|
606
606
|
boxes = new Boxes({ file: new JsonFile(`${dataDir}/boxes.json`, []),
|
|
607
607
|
exists: (name) => all.list().some((c) => c.name === name),
|
|
608
|
+
/* A long recording (a meeting): transcribed in parts, kept beside the conversation for its assistant. */
|
|
609
|
+
recordDir: `${dataDir}/recordings`, parts: (wav) => voice.transcribeParts(wav), keep: (name, file, text) => talk.keepText(name, file, text),
|
|
608
610
|
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) */
|
|
609
611
|
/* Said as the person's own message, the room named (one speaker for now). */
|
|
610
612
|
say: (name, text, by) => talk.say(name, text, undefined, undefined, 'voice', { by }),
|
package/server/voice.mjs
CHANGED
|
@@ -167,6 +167,30 @@ export async function transcribe(config, audio, fetcher = fetch, { oneVoice = fa
|
|
|
167
167
|
return cleanDictation((oneVoice && firstVoice(body)) || body.text, wavSeconds(audio));
|
|
168
168
|
}
|
|
169
169
|
|
|
170
|
+
/* A LONG RECORDING, in parts of a few minutes (a voice box records a meeting): each part's text, with who
|
|
171
|
+
speaks when the engine tells voices apart (OVH: diarize). Parts up to 24 MB: what the engines take. */
|
|
172
|
+
export const PART_MAX = 24 * 1024 * 1024;
|
|
173
|
+
export async function transcribeParts(config, audio, fetcher = fetch) {
|
|
174
|
+
if (!config) throw new Refusal(503, 'No speech-to-text engine is configured.');
|
|
175
|
+
if (audio.length > PART_MAX) throw new Refusal(413, 'The part is too long.');
|
|
176
|
+
const diarize = DIARIZES.test(String(config.url));
|
|
177
|
+
const form = new FormData();
|
|
178
|
+
form.append('file', new Blob([audio], { type: 'audio/wav' }), 'recording.wav');
|
|
179
|
+
form.append('model', config.model);
|
|
180
|
+
if (config.language) form.append('language', config.language);
|
|
181
|
+
form.append('response_format', diarize ? 'verbose_json' : 'json');
|
|
182
|
+
if (diarize) form.append('diarize', 'true');
|
|
183
|
+
let response;
|
|
184
|
+
try { response = await fetcher(config.url, { method: 'POST', redirect: 'error', headers: config.key ? { authorization: `Bearer ${config.key}` } : {}, body: form, signal: AbortSignal.timeout(10 * 60_000) }); }
|
|
185
|
+
catch { throw new Refusal(502, 'The speech-to-text engine cannot be reached.'); }
|
|
186
|
+
if (!response.ok) throw new Refusal(502, `The speech-to-text engine answered ${response.status}.`);
|
|
187
|
+
const body = await response.json().catch(() => undefined);
|
|
188
|
+
if (Array.isArray(body?.diarization) && body.diarization.length) return body.diarization.map((p) => ({ speaker: Number(p.speaker) || 0, start: Number(p.start) || 0, text: withoutPhantoms(String(p.text ?? '')) })).filter((p) => p.text);
|
|
189
|
+
if (typeof body?.text !== 'string') throw new Refusal(502, 'The speech-to-text engine gave no text.');
|
|
190
|
+
const text = withoutPhantoms(body.text);
|
|
191
|
+
return text ? [{ speaker: null, start: 0, text }] : [];
|
|
192
|
+
}
|
|
193
|
+
|
|
170
194
|
/* ---------- THE ENGINE CHOSEN IN SETTINGS ----------
|
|
171
195
|
* Settings > Dictation: a provider fills in the address and the model (both
|
|
172
196
|
* may be changed); the key is one of the SECRETS already kept (Assets >
|
|
@@ -300,6 +324,12 @@ export class Dictation {
|
|
|
300
324
|
/* An expired key is never sent: said in one line instead (still offered, so the line is seen). */
|
|
301
325
|
#fresh(c) { if (c?.secret && this.#expired(c.secret)) throw new Refusal(409, KEY_EXPIRED); }
|
|
302
326
|
/* `device`: the language of the device that dictates (a tag such as fr-FR), if it said. */
|
|
327
|
+
async transcribeParts(audio) {
|
|
328
|
+
this.#fresh(this.#saved());
|
|
329
|
+
const config = this.current();
|
|
330
|
+
if (config) await this.#guard(config);
|
|
331
|
+
return transcribeParts(config && { ...config, language: languageOf(config.language, undefined) }, audio, this.#fetcher);
|
|
332
|
+
}
|
|
303
333
|
async transcribe(audio, device, how = {}) {
|
|
304
334
|
this.#fresh(this.#saved());
|
|
305
335
|
const config = this.current();
|