clavarium 0.2.15 → 0.2.16

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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.15",
3
+ "version": "0.2.16",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.15",
9
+ "version": "0.2.16",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.15",
3
+ "version": "0.2.16",
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.",
package/server/talk.mjs CHANGED
@@ -271,12 +271,16 @@ export class Talk {
271
271
  /* What the person or the tool said -- never a line of this server (a restart, a machine put to sleep):
272
272
  those are no one using it, and would lift it in Recent. */
273
273
  const last = (now.messages ?? []).filter((m) => m.kind !== 'doing' && (m.from === 'person' || m.from === 'agent')).at(-1);
274
- /* IT NEEDS ITS OWNER only if it asked, or said it waits, AFTER the owner last wrote: answered (with
275
- the buttons or in a message of one's own), the turn is the tool's again. */
274
+ /* IT NEEDS ITS OWNER while a question of it is open (neither answered nor closed) and the owner wrote
275
+ nothing since -- but the answer to ANOTHER question, which says nothing of this one (two asked, one
276
+ answered: the other still waits, seen 22-10); or while it said it waits, and the owner wrote nothing since. */
276
277
  const messages = now.messages ?? [];
277
- const personAt = messages.filter((m) => m.from === 'person').map((m) => m.at).sort().at(-1) ?? '';
278
- const askedAt = messages.filter((m) => m.from !== 'person' && m.kind === 'ask' && !m.closed).map((m) => m.at).sort().at(-1) ?? '';
279
- const needs = (now.waiting > 0 && askedAt > personAt) || (now.status?.state === 'waiting' && String(now.status.at ?? '') > personAt);
278
+ const person = messages.filter((m) => m.from === 'person');
279
+ const personAt = person.map((m) => m.at).sort().at(-1) ?? '';
280
+ const answered = new Set(person.map((m) => m.answers).filter(Boolean));
281
+ const open = messages.filter((m) => m.from === 'agent' && m.kind === 'ask' && !m.closed && !answered.has(m.id));
282
+ const asks = open.some((q) => !person.some((p) => p.at >= q.at && !(p.answers && p.answers !== q.id)));
283
+ const needs = asks || (now.status?.state === 'waiting' && String(now.status.at ?? '') > personAt);
280
284
  /* What it said it does (status, doing): it is at work, even without a message. */
281
285
  const stepAt = (now.steps ?? []).map((m) => m.at).sort().at(-1) ?? null;
282
286
  return { waiting: now.waiting, state: now.status?.state ?? null, needs, ...(stepAt ? { stepAt } : {}), ...(last ? { lastAt: last.at, lastFrom: last.from === 'person' ? 'person' : 'agent', lastText: String(last.short || last.text || '').replace(/\s+/g, ' ').trim().slice(0, 90) } : {}) };
package/server/voice.mjs CHANGED
@@ -62,10 +62,56 @@ export function withoutLoop(text) {
62
62
  return out.join(' ');
63
63
  }
64
64
 
65
- export function cleanDictation(raw) {
66
- return withoutLoop(String(raw ?? '').replace(/[\r\n\t]+/gu, ' ').replace(NOT_TYPED, '')).slice(0, TEXT_MAX).trim();
65
+ /* A LOOP INSIDE A WORD: "l'éritéritéritérit..." has no space, so withoutLoop
66
+ cannot see it. A run of 2 to 20 characters repeated 4 times or more in a
67
+ row is kept once. */
68
+ export function withoutCharLoop(text) {
69
+ return text.replace(/(.{2,20}?)\1{3,}/gsu, '$1');
67
70
  }
68
71
 
72
+ /* WHAT WHISPER WRITES ON SILENCE: credits of the subtitles it learned from.
73
+ Nobody dictates these; they are removed wherever they appear. */
74
+ const PHANTOMS = [
75
+ /* Any sentence that credits Amara.org, in whatever language ("Sous-titres réalisés par la communauté
76
+ d'Amara.org", "Untertitel der Amara.org-Community", "Subtítulos por la comunidad de Amara.org"...). */
77
+ /[^.!?。]*amara\.org[^.!?。]*[.!?。]?/giu,
78
+ /sous[- ]titrage\s*st\s*'?\s*\d+[.!]?/giu,
79
+ /sous[- ]titr(?:age|es?)\s+(?:par\s+)?(?:la\s+)?société\s+radio[- ]canada[.!]?/giu,
80
+ /untertitel(?:ung)?\s+(?:im\s+auftrag\s+)?des\s+zdf(?:\s+für\s+funk)?,?\s*\d{0,4}[.!]?/giu,
81
+ ];
82
+ export function withoutPhantoms(text) {
83
+ let t = text;
84
+ for (const re of PHANTOMS) t = t.replace(re, ' ');
85
+ return t.replace(/\s+/gu, ' ').trim();
86
+ }
87
+
88
+ /* SPEECH HAS A SPEED: nobody says more than ~25 characters a second. More
89
+ text than the audio could hold is the engine running on; it is cut at a
90
+ word. `seconds` undefined: no cap but TEXT_MAX. */
91
+ export const CHARS_PER_SECOND = 25;
92
+ export function capToDuration(text, seconds) {
93
+ if (!Number.isFinite(seconds)) return text;
94
+ const max = Math.ceil(30 + CHARS_PER_SECOND * seconds);
95
+ if (text.length <= max) return text;
96
+ const cut = text.slice(0, max);
97
+ const space = cut.lastIndexOf(' ');
98
+ return (space > max / 2 ? cut.slice(0, space) : cut).trim();
99
+ }
100
+
101
+ /* The length of a WAV, in seconds, from its header (bytes per second at 28). */
102
+ export function wavSeconds(audio) {
103
+ const rate = audio.length >= 44 ? audio.readUInt32LE(28) : 0;
104
+ return rate > 0 ? Math.max(0, audio.length - 44) / rate : undefined;
105
+ }
106
+
107
+ export function cleanDictation(raw, seconds) {
108
+ const flat = String(raw ?? '').replace(/[\r\n\t]+/gu, ' ').replace(NOT_TYPED, '');
109
+ return capToDuration(withoutLoop(withoutPhantoms(withoutCharLoop(flat))), seconds).slice(0, TEXT_MAX).trim();
110
+ }
111
+
112
+ /* The engines (address and model) that refused "temperature": not asked with it again while this server runs. */
113
+ const noTemperature = new Set();
114
+
69
115
  /* `audio` is a WAV file, as bytes. Resolves with the text to type. */
70
116
  export async function transcribe(config, audio, fetcher = fetch) {
71
117
  if (!config) throw new Refusal(503, 'No speech-to-text engine is configured.');
@@ -74,14 +120,27 @@ export async function transcribe(config, audio, fetcher = fetch) {
74
120
  if (audio.subarray(0, 4).toString('latin1') !== 'RIFF' || audio.subarray(8, 12).toString('latin1') !== 'WAVE') {
75
121
  throw new Refusal(400, 'The recording is not a WAV file.');
76
122
  }
77
- const form = new FormData();
78
- form.append('file', new Blob([audio], { type: 'audio/wav' }), 'dictation.wav');
79
- form.append('model', config.model);
80
- if (config.language) form.append('language', config.language);
81
- form.append('response_format', 'json');
123
+ /* Greedy decoding asked of every engine: sampling is what lets a loop run. An engine that refuses the field
124
+ (a 400 or 422: not every one takes it) is asked again without it, at once, and not asked with it again --
125
+ the same for every engine, nothing known of any in advance. */
126
+ const strict = !noTemperature.has(`${config.url} ${config.model}`);
127
+ const ask = (withTemperature) => {
128
+ const form = new FormData();
129
+ form.append('file', new Blob([audio], { type: 'audio/wav' }), 'dictation.wav');
130
+ form.append('model', config.model);
131
+ if (config.language) form.append('language', config.language);
132
+ form.append('response_format', 'json');
133
+ if (withTemperature) form.append('temperature', '0');
134
+ return fetcher(config.url, { method: 'POST', redirect: 'error', headers: config.key ? { authorization: `Bearer ${config.key}` } : {}, body: form, signal: AbortSignal.timeout(TIMEOUT_MS) });
135
+ };
82
136
  let response;
83
137
  try {
84
- response = await fetcher(config.url, { method: 'POST', redirect: 'error', headers: config.key ? { authorization: `Bearer ${config.key}` } : {}, body: form, signal: AbortSignal.timeout(TIMEOUT_MS) });
138
+ response = await ask(strict);
139
+ if (strict && (response.status === 400 || response.status === 422)) {
140
+ const again = await ask(false);
141
+ if (again.ok) noTemperature.add(`${config.url} ${config.model}`);
142
+ response = again;
143
+ }
85
144
  } catch {
86
145
  /* The error of a failed request repeats the address it was sent to:
87
146
  it is not passed on. */
@@ -90,7 +149,7 @@ export async function transcribe(config, audio, fetcher = fetch) {
90
149
  if (!response.ok) throw new Refusal(502, `The speech-to-text engine answered ${response.status}.`);
91
150
  const body = await response.json().catch(() => undefined);
92
151
  if (typeof body?.text !== 'string') throw new Refusal(502, 'The speech-to-text engine gave no text.');
93
- return cleanDictation(body.text);
152
+ return cleanDictation(body.text, wavSeconds(audio));
94
153
  }
95
154
 
96
155
  /* ---------- THE ENGINE CHOSEN IN SETTINGS ----------
package/web/voice-core.js CHANGED
@@ -11,7 +11,18 @@ export const BLOCK_MS = (BLOCK / RATE) * 1000; /* 32 ms */
11
11
  export const PRE_ROLL_MS = 320; /* kept from before the first word, or its attack is cut */
12
12
  export const SILENCE_MS = 500; /* a pause this long ends the phrase */
13
13
  export const MINIMUM_MS = 250; /* less SPEECH than this is a noise, not a phrase */
14
- export const MAXIMUM_MS = 30_000; /* a phrase is cut rather than growing for ever */
14
+ /* A phrase is cut rather than growing for ever: past SOFT_MAXIMUM_MS at its next short pause, at MAXIMUM_MS whatever.
15
+ Long pieces are where an engine runs on in loops; and the server takes 16 s of audio at most (AUDIO_MAX). */
16
+ export const SOFT_MAXIMUM_MS = 12_000;
17
+ export const MAXIMUM_MS = 15_000;
18
+ export const SHORT_PAUSE_MS = 200;
19
+ /* SPEECH IS HELD, A NOISE IS NOT: a syllable lasts this long at least (a click, a key, a breath do not), and
20
+ between its first and last sound, a phrase is speech this much of the time at least. What is sent of a
21
+ near-silence is what an engine fills with what it learned ("Sous-titrage ST' 501"). */
22
+ export const HELD_MS = 160;
23
+ export const SPEECH_SHARE = 0.3;
24
+ /* Kept after the last sound: enough for its end, not a silence for the engine to fill. */
25
+ export const TAIL_MS = 200;
15
26
 
16
27
  export function loudness(samples) {
17
28
  if (!samples || samples.length === 0) return 0;
@@ -63,16 +74,17 @@ export class Segmenter {
63
74
  while (this.ring.length > Math.ceil(PRE_ROLL_MS / BLOCK_MS)) this.ring.shift();
64
75
  return;
65
76
  }
66
- this.current = { start: at, blocks: [...this.ring, samples], spoken: 1 };
77
+ this.current = { start: at, blocks: [...this.ring, samples], spoken: 1, first: this.ring.length, last: this.ring.length, run: 1, held: 1 };
67
78
  this.ring = []; this.silentSince = null;
68
79
  this.onStart();
69
80
  return;
70
81
  }
71
- this.current.blocks.push(samples);
72
- if (speech) { this.current.spoken++; this.silentSince = null; }
73
- else if (this.silentSince === null) this.silentSince = at;
74
- else if (at - this.silentSince >= SILENCE_MS) { this.close(); return; }
75
- if (at - this.current.start >= MAXIMUM_MS) this.close();
82
+ const c = this.current;
83
+ c.blocks.push(samples);
84
+ if (speech) { c.spoken++; c.last = c.blocks.length - 1; c.run++; c.held = Math.max(c.held, c.run); this.silentSince = null; }
85
+ else { c.run = 0; if (this.silentSince === null) this.silentSince = at; else if (at - this.silentSince >= SILENCE_MS) { this.close(); return; } }
86
+ const long = at - c.start;
87
+ if (long >= MAXIMUM_MS || (long >= SOFT_MAXIMUM_MS && this.silentSince !== null && at - this.silentSince >= SHORT_PAUSE_MS)) this.close();
76
88
  }
77
89
  close() {
78
90
  const phrase = this.current;
@@ -81,7 +93,9 @@ export class Segmenter {
81
93
  /* Counted in blocks of SPEECH, never in length: a cough followed by
82
94
  half a second of silence is long, and is not a phrase. */
83
95
  if (phrase.spoken * BLOCK_MS < MINIMUM_MS) return;
84
- this.onPhrase(phrase.blocks);
96
+ if (phrase.held * BLOCK_MS < HELD_MS) return;
97
+ if (phrase.spoken / (phrase.last - phrase.first + 1) < SPEECH_SHARE) return;
98
+ this.onPhrase(phrase.blocks.slice(0, phrase.last + 1 + Math.ceil(TAIL_MS / BLOCK_MS)));
85
99
  }
86
100
  }
87
101