clavarium 0.2.192-next.1 → 0.2.195-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 +96 -9
- package/server/files.mjs +14 -5
- 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.195-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.195-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,32 @@ 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
|
+
|
|
131
|
+
export const ANSWER_WITHIN_MS = 90_000;
|
|
105
132
|
export const CHAT_WITHIN_MS = 3 * 60_000;
|
|
106
133
|
export const LISTEN_AHEAD = 3 * 32_000; /* bytes: what a box is sent ahead of what it plays (its buffer holds 16 s) */
|
|
107
134
|
|
|
@@ -127,12 +154,12 @@ export function piecesOf(pcm, { least = 8, most = 14 } = {}) {
|
|
|
127
154
|
|
|
128
155
|
export class Boxes {
|
|
129
156
|
#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();
|
|
157
|
+
#exists; #hear; #say; #speak; #log; #changed; #images = new Map(); #origin; #spawn; #fetch; #streams = new Map(); #recordDir; #parts; #keep;
|
|
131
158
|
|
|
132
159
|
/* file: a JsonFile holding [{ id, name, conversation, keyHash, firmware, createdAt, seenAt }].
|
|
133
160
|
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;
|
|
161
|
+
constructor({ file, exists = () => true, hear, say, speak, changed = () => {}, origin = () => null, now = () => Date.now(), log = () => {}, spawn = spawnProcess, fetcher = fetch, recordDir = null, parts = null, keep = null }) {
|
|
162
|
+
this.#spawn = spawn; this.#fetch = fetcher; this.#recordDir = recordDir; this.#parts = parts; this.#keep = keep;
|
|
136
163
|
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
164
|
}
|
|
138
165
|
|
|
@@ -247,7 +274,7 @@ export class Boxes {
|
|
|
247
274
|
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
275
|
catch { throw new Refusal(501, 'This server cannot read sounds: ffmpeg is not installed (an update installs it).'); }
|
|
249
276
|
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: '' };
|
|
277
|
+
const stream = { child, queue: [], queued: 0, sent: 0, started: this.#now(), timer: null, ended: false, failed: '', over: [], gain: 1 };
|
|
251
278
|
this.#streams.set(id, stream);
|
|
252
279
|
link.send({ t: 'speak.start', rate: 16_000 });
|
|
253
280
|
child.stdout.on('data', (d) => { stream.queue.push(d); stream.queued += d.length; if (stream.queued > LISTEN_AHEAD * 4) child.stdout.pause(); });
|
|
@@ -260,7 +287,7 @@ export class Boxes {
|
|
|
260
287
|
const due = (this.#now() - stream.started) * 32 + LISTEN_AHEAD; /* bytes the box should have by now, a few seconds ahead */
|
|
261
288
|
while (stream.sent + 640 <= due && (carry.length >= 640 || stream.queue.length)) {
|
|
262
289
|
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));
|
|
290
|
+
if (link.socket.readyState === 1) link.socket.send(mix(stream, carry.subarray(0, 640)));
|
|
264
291
|
carry = carry.subarray(640); stream.sent += 640;
|
|
265
292
|
}
|
|
266
293
|
if (stream.queued < LISTEN_AHEAD) child.stdout.resume();
|
|
@@ -356,12 +383,15 @@ export class Boxes {
|
|
|
356
383
|
it ends when nobody answers, or on "fin de la conversation". */
|
|
357
384
|
const question = !doing && (asked || /\?\s*$/.test(words));
|
|
358
385
|
for (const l of boxes) {
|
|
359
|
-
|
|
386
|
+
/* An answer -- to a sentence heard within a minute -- may open the conversation; something said
|
|
387
|
+
of itself (a news item, a reminder) does not: the box listened after it for nothing (31-10). */
|
|
388
|
+
const answering = l.heardAt && this.#now() - l.heardAt < ANSWER_WITHIN_MS;
|
|
389
|
+
const chatting = !doing && answering && this.#chatting(l);
|
|
360
390
|
const opening = chatting && !l.chat;
|
|
361
391
|
if (chatting) l.chat = true;
|
|
362
392
|
let pcm;
|
|
363
393
|
try { pcm = await this.#speak(opening ? `Je passe en mode conversation : je reste à l'écoute. ${words}` : words); } catch (error) { this.#log(`voice box: no voice for the answer (${error.message})`); l.send({ t: 'cue', name: 'error' }); continue; }
|
|
364
|
-
l.play(pcm, question || chatting ? 'listen' : null);
|
|
394
|
+
l.play(pcm, question || chatting ? 'listen' : null); /* a question is always listened after: an answer is expected */
|
|
365
395
|
}
|
|
366
396
|
}
|
|
367
397
|
#chatting(link) {
|
|
@@ -380,6 +410,9 @@ export class Boxes {
|
|
|
380
410
|
box: () => this.#all().find((b) => b.id === box.id) ?? box,
|
|
381
411
|
play: (pcm, then = null) => {
|
|
382
412
|
pcm = pcm.subarray(0, pcm.length & ~1); /* whole samples only: an odd byte shifts every sample after it */
|
|
413
|
+
/* Something is playing (a radio): the words go over it, the radio lowered meanwhile (the mixer, listen()). */
|
|
414
|
+
const playing = this.#streams.get(box.id);
|
|
415
|
+
if (playing) { playing.over.push(pcm); return; }
|
|
383
416
|
send({ t: 'speak.start', rate: 16_000 });
|
|
384
417
|
for (let at = 0; at < pcm.length; at += 640) if (socket.readyState === 1) socket.send(pcm.subarray(at, at + 640));
|
|
385
418
|
send({ t: 'speak.end', ...(then ? { then } : {}) });
|
|
@@ -392,6 +425,12 @@ export class Boxes {
|
|
|
392
425
|
seen();
|
|
393
426
|
socket.on('message', (data, binary) => {
|
|
394
427
|
if (binary) {
|
|
428
|
+
if (link.recording) {
|
|
429
|
+
const r = link.recording;
|
|
430
|
+
if (r.bytes + data.length > RECORD_MAX_BYTES) { if (!r.full) { r.full = true; send({ t: 'record', on: false }); } return; }
|
|
431
|
+
r.out.write(data); r.bytes += data.length;
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
395
434
|
if (!sentence || link.muted) return;
|
|
396
435
|
size += data.length;
|
|
397
436
|
if (size <= SENTENCE_MAX) sentence.push(Buffer.from(data));
|
|
@@ -408,6 +447,18 @@ export class Boxes {
|
|
|
408
447
|
if (m.volume !== wanted) { send({ t: 'volume', id: randomUUID(), level: wanted }); m.volume = wanted; }
|
|
409
448
|
}
|
|
410
449
|
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; }
|
|
450
|
+
if (m.t === 'record.start' && this.#recordDir) {
|
|
451
|
+
mkdirSync(this.#recordDir, { recursive: true });
|
|
452
|
+
const file = `${this.#recordDir}/${box.id}-${this.#now()}.pcm`;
|
|
453
|
+
link.recording = { file, out: createWriteStream(file), bytes: 0, at: this.#now() };
|
|
454
|
+
this.#log(`voice box ${box.name}: recording`);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
if (m.t === 'record.end' && link.recording) {
|
|
458
|
+
const r = link.recording; link.recording = null;
|
|
459
|
+
r.out.end(() => { void this.#recorded(link, r); });
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
411
462
|
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
463
|
if (m.t === 'listen.end' && sentence && m.reason === 'nobody') {
|
|
413
464
|
/* Listened again, nobody spoke: a conversation ends there, in silence. */
|
|
@@ -430,10 +481,40 @@ export class Boxes {
|
|
|
430
481
|
}
|
|
431
482
|
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
483
|
});
|
|
433
|
-
socket.on('close', () => { if (
|
|
484
|
+
socket.on('close', () => { if (link.recording) { const r = link.recording; link.recording = null; r.out.end(() => { void this.#recorded(link, r); }); }
|
|
485
|
+
if (this.#links.get(box.id) === link) { this.stop(box.id); this.#links.delete(box.id); this.#log(`voice box ${box.name}: disconnected`); } });
|
|
434
486
|
socket.on('error', () => {});
|
|
435
487
|
}
|
|
436
488
|
|
|
489
|
+
/* A recording ended: transcribed in parts of five minutes (cut at a quiet moment), who speaks noted when the
|
|
490
|
+
engine tells voices apart; the text kept beside the conversation, and said there in a short line, so its
|
|
491
|
+
assistant writes what was asked of it. The sound itself is not kept. */
|
|
492
|
+
async #recorded(link, r) {
|
|
493
|
+
const box = link.box();
|
|
494
|
+
const minutes = Math.round(r.bytes / 32_000 / 60);
|
|
495
|
+
this.#log(`voice box ${box.name}: recording ended, ${minutes} min, transcribing`);
|
|
496
|
+
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 */ }
|
|
497
|
+
let pcm;
|
|
498
|
+
try { pcm = readFileSync(r.file); } catch (error) { this.#log(`voice box ${box.name}: the recording cannot be read (${error.message})`); return; }
|
|
499
|
+
const lines = []; let offset = 0; let failed = 0;
|
|
500
|
+
const pieces = piecesOf(pcm, { least: 270, most: 300 });
|
|
501
|
+
for (const [i, piece] of pieces.entries()) {
|
|
502
|
+
try {
|
|
503
|
+
const parts = await this.#parts(wavOf(piece));
|
|
504
|
+
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}`);
|
|
505
|
+
} catch (error) { failed++; lines.push(`[${mmss(offset)}] (cette partie n'a pas pu être transcrite : ${error.message})`); }
|
|
506
|
+
offset += piece.length / 32_000;
|
|
507
|
+
}
|
|
508
|
+
rmSync(r.file, { force: true });
|
|
509
|
+
const stamp = new Date(r.at).toISOString().slice(0, 16).replace(/[-:T]/g, '');
|
|
510
|
+
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`;
|
|
511
|
+
let path = null;
|
|
512
|
+
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})`); }
|
|
513
|
+
this.#log(`voice box ${box.name}: recording transcribed (${lines.length} lines${failed ? `, ${failed} part(s) failed` : ''})`);
|
|
514
|
+
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.`;
|
|
515
|
+
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})`); }
|
|
516
|
+
}
|
|
517
|
+
|
|
437
518
|
/* Each step said in the server's log, never what was said: its length only. */
|
|
438
519
|
async #heard(link, pcm) {
|
|
439
520
|
const box0 = link.box();
|
|
@@ -452,6 +533,12 @@ export class Boxes {
|
|
|
452
533
|
} 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
534
|
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
535
|
const box = link.box();
|
|
536
|
+
if (RECORD_ASKED.test(text) && this.#recordDir && this.#parts) {
|
|
537
|
+
this.#log(`voice box ${box.name}: a recording asked`);
|
|
538
|
+
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 */ }
|
|
539
|
+
link.send({ t: 'record', on: true });
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
455
542
|
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
543
|
this.#log(`voice box ${box.name}: ${seconds} s heard, said in ${box.conversation}`);
|
|
457
544
|
link.heardAt = this.#now();
|
package/server/files.mjs
CHANGED
|
@@ -162,6 +162,8 @@ export async function importFile(root, relative, name, request, { exists = 'keep
|
|
|
162
162
|
*/
|
|
163
163
|
export const EDIT_MAX = 1024 * 1024;
|
|
164
164
|
export const THUMB_MAX = 8 * 1024 * 1024;
|
|
165
|
+
/* A sound played in the thread: a few minutes of speech or music. */
|
|
166
|
+
export const SOUND_MAX = 40 * 1024 * 1024;
|
|
165
167
|
/* One drop of files or of a folder: as a whole, this many bytes and files at most. */
|
|
166
168
|
export const BATCH_MAX = 2 * 1024 * 1024 * 1024;
|
|
167
169
|
export const BATCH_FILES = 2000;
|
|
@@ -391,6 +393,11 @@ const SIGNATURES = [
|
|
|
391
393
|
['image/jpeg', (b) => b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff],
|
|
392
394
|
['image/gif', (b) => b.length >= 6 && /^GIF8[79]a$/.test(b.subarray(0, 6).toString('latin1'))],
|
|
393
395
|
['image/webp', (b) => b.length >= 12 && b.subarray(0, 4).toString('latin1') === 'RIFF' && b.subarray(8, 12).toString('latin1') === 'WEBP'],
|
|
396
|
+
/* Sounds, played in the thread as the pictures are shown (Parley's player): proved by their bytes too. */
|
|
397
|
+
['audio/wav', (b) => b.length >= 12 && b.subarray(0, 4).toString('latin1') === 'RIFF' && b.subarray(8, 12).toString('latin1') === 'WAVE'],
|
|
398
|
+
['audio/mpeg', (b) => b.length >= 3 && (b.subarray(0, 3).toString('latin1') === 'ID3' || (b[0] === 0xff && (b[1] & 0xe0) === 0xe0))],
|
|
399
|
+
['audio/ogg', (b) => b.length >= 4 && b.subarray(0, 4).toString('latin1') === 'OggS'],
|
|
400
|
+
['audio/mp4', (b) => b.length >= 12 && b.subarray(4, 8).toString('latin1') === 'ftyp'],
|
|
394
401
|
];
|
|
395
402
|
export const IMAGE_HEADERS = Object.freeze({
|
|
396
403
|
'content-security-policy': "default-src 'none'; sandbox",
|
|
@@ -401,15 +408,17 @@ export const IMAGE_HEADERS = Object.freeze({
|
|
|
401
408
|
});
|
|
402
409
|
export async function picture(root, relative) {
|
|
403
410
|
const at = await regular(root, relative);
|
|
404
|
-
|
|
405
|
-
if (
|
|
411
|
+
const sound = /\.(wav|mp3|ogg|oga|opus|m4a)$/i.test(at.name);
|
|
412
|
+
if (!sound && !/\.(png|jpe?g|gif|webp)$/i.test(at.name)) throw new Refusal(415, 'Only a PNG, JPEG, GIF or WebP picture, or a WAV, MP3, Ogg or M4A sound, is shown in the thread.');
|
|
413
|
+
const most = sound ? SOUND_MAX : THUMB_MAX;
|
|
414
|
+
if (at.info.size > most) throw new Refusal(413, sound ? 'This sound is too large to play here.' : 'This picture is too large for a thumbnail.');
|
|
406
415
|
const handle = await open(at.path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
407
416
|
try {
|
|
408
417
|
const info = await handle.stat();
|
|
409
|
-
if (!info.isFile() || info.size >
|
|
418
|
+
if (!info.isFile() || info.size > most) throw new Refusal(413, 'This file is too large to show here.');
|
|
410
419
|
const bytes = await readAll(handle, info.size);
|
|
411
|
-
const type = SIGNATURES.find(([, is]) => is(bytes))?.[0];
|
|
412
|
-
if (!type) throw new Refusal(415,
|
|
420
|
+
const type = SIGNATURES.find(([kind, is]) => kind.startsWith(sound ? 'audio/' : 'image/') && is(bytes))?.[0];
|
|
421
|
+
if (!type) throw new Refusal(415, `This file is not the ${sound ? 'sound' : 'picture'} its name says.`);
|
|
413
422
|
return { type, bytes, version: versionOf(info) };
|
|
414
423
|
} finally { await handle.close(); }
|
|
415
424
|
}
|
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();
|