@senad-d/micme 0.1.1 → 0.2.0

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/src/streaming.ts CHANGED
@@ -1,11 +1,9 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import {
3
- MAX_CAPTURED_OUTPUT_CHARS,
4
- STREAM_MIN_INITIAL_WORDS,
5
- } from "./constants.ts";
2
+ import { MAX_CAPTURED_OUTPUT_CHARS } from "./constants.ts";
6
3
  import {
7
4
  env,
8
5
  envFlag,
6
+ getStreamFlushMs,
9
7
  getStreamKeepContext,
10
8
  getStreamKeepMs,
11
9
  getStreamLengthMs,
@@ -18,6 +16,22 @@ import { pasteOrSubmitTranscript } from "./transcript-delivery.ts";
18
16
  import { shellQuote } from "./processes.ts";
19
17
  import type { CommandSpec, Recording, StreamingState } from "./types.ts";
20
18
 
19
+ export type StreamingFrameMode = "cumulative" | "incremental" | "rolling" | "duplicate" | "reset";
20
+
21
+ export type StreamingExtraction = {
22
+ mode: StreamingFrameMode;
23
+ newWords: string[];
24
+ };
25
+
26
+ type StreamingDiagnosticDetails = {
27
+ rawFrame?: string;
28
+ sanitizedText?: string;
29
+ frameWords?: string[];
30
+ extractionMode: StreamingFrameMode | "ignored" | "flush";
31
+ newWords?: string[];
32
+ reason?: string;
33
+ };
34
+
21
35
  export function buildWhisperStreamCommand(binary: string, modelPath: string, tempDir: string): CommandSpec {
22
36
  const args = [
23
37
  "-m",
@@ -52,25 +66,54 @@ export function handleStreamingOutput(ctx: ExtensionContext, active: Recording,
52
66
 
53
67
  export function drainStreamingOutput(ctx: ExtensionContext, active: Recording, force: boolean, chunk = "") {
54
68
  if (!active.streaming) return;
55
- for (const part of readStreamingOutputFrames(active.streaming, chunk, force)) {
56
- const text = sanitizeStreamingText(part);
57
- if (!text) {
58
- if (shouldResetStreamingPending(part)) {
59
- active.streaming.pendingWords = [];
60
- renderStreamingPreview(ctx, active.streaming, false);
69
+ const state = active.streaming;
70
+
71
+ for (const rawFrame of readStreamingOutputFrames(state, chunk, force)) {
72
+ const sanitizedText = sanitizeStreamingText(rawFrame);
73
+ const frameWords = splitStreamingWords(sanitizedText);
74
+
75
+ if (!sanitizedText) {
76
+ if (shouldResetStreamingPending(rawFrame)) {
77
+ clearStreamingFlush(state);
78
+ state.candidateWords = [];
79
+ state.lastHypothesisWords = [];
80
+ state.lastText = "";
81
+ renderStreamingPreview(ctx, state, false);
82
+ showStreamingFrameDiagnostics(ctx, state, {
83
+ rawFrame,
84
+ sanitizedText,
85
+ frameWords,
86
+ extractionMode: "reset",
87
+ newWords: [],
88
+ reason: "reset/hallucination frame",
89
+ });
90
+ } else {
91
+ showStreamingFrameDiagnostics(ctx, state, {
92
+ rawFrame,
93
+ sanitizedText,
94
+ frameWords,
95
+ extractionMode: "ignored",
96
+ newWords: [],
97
+ reason: "empty frame",
98
+ });
61
99
  }
62
100
  continue;
63
101
  }
64
- if (!active.streaming.firstOutputAt) active.streaming.firstOutputAt = Date.now();
65
- const next = diffStreamingText(active.streaming.emittedWords.slice(-160).join(" "), text);
66
- active.streaming.lastText = text;
67
- if (!next) {
68
- active.streaming.pendingWords = [];
69
- renderStreamingPreview(ctx, active.streaming, false);
70
- continue;
71
- }
102
+
103
+ clearStreamingFlush(state);
104
+ if (!state.firstOutputAt) state.firstOutputAt = Date.now();
105
+ const extraction = extractStreamingCandidate(state, frameWords);
106
+ state.lastText = sanitizedText;
72
107
  active.audioLevel = () => 0.55;
73
- queueStableStreamingWords(ctx, active.streaming, splitStreamingWords(next));
108
+ queueStableStreamingWords(ctx, state, extraction.newWords, extraction.mode);
109
+ state.lastHypothesisWords = frameWords;
110
+ showStreamingFrameDiagnostics(ctx, state, {
111
+ rawFrame,
112
+ sanitizedText,
113
+ frameWords,
114
+ extractionMode: extraction.mode,
115
+ newWords: extraction.newWords,
116
+ });
74
117
  }
75
118
  }
76
119
 
@@ -117,6 +160,32 @@ export function diffStreamingText(previous: string, current: string) {
117
160
  return currentWords.slice(overlap).join(" ");
118
161
  }
119
162
 
163
+ export function extractStreamingCandidate(state: StreamingState, frameWords: string[]): StreamingExtraction {
164
+ const words = frameWords.filter(Boolean);
165
+ if (words.length === 0) return { mode: "reset", newWords: [] };
166
+
167
+ const emittedOverlap = streamingWordOverlap(state.emittedWords.slice(-160), words);
168
+ if (emittedOverlap === words.length) return { mode: "duplicate", newWords: [] };
169
+ if (emittedOverlap > 0) return { mode: "cumulative", newWords: words.slice(emittedOverlap) };
170
+
171
+ if (state.candidateWords.length > 0) {
172
+ if (streamingWordsEqual(state.candidateWords, words)) return { mode: "duplicate", newWords: words };
173
+ if (isStreamingWordsPrefix(state.candidateWords, words)) return { mode: "cumulative", newWords: words };
174
+ if (streamingWordOverlap(state.candidateWords, words) > 0) return { mode: "rolling", newWords: words };
175
+ if (looksLikeStreamingCorrection(state.candidateWords, words)) return { mode: "reset", newWords: words };
176
+ }
177
+
178
+ if (state.lastHypothesisWords.length > 0) {
179
+ if (streamingWordsEqual(state.lastHypothesisWords, words)) return { mode: "duplicate", newWords: words };
180
+ if (isStreamingWordsPrefix(state.lastHypothesisWords, words)) return { mode: "cumulative", newWords: trimCommittedStreamingPrefix(state, words) };
181
+ if (streamingWordOverlap(state.lastHypothesisWords, words) > 0) return { mode: "rolling", newWords: words };
182
+ if (looksLikeStreamingCorrection(state.lastHypothesisWords, words)) return { mode: "reset", newWords: words };
183
+ }
184
+
185
+ const isFirstHypothesis = state.emittedWords.length === 0 && state.candidateWords.length === 0 && state.lastHypothesisWords.length === 0;
186
+ return { mode: isFirstHypothesis ? "cumulative" : "incremental", newWords: words };
187
+ }
188
+
120
189
  export function isLikelyStreamingHallucination(text: string) {
121
190
  if (!text) return true;
122
191
  const normalized = text.toLowerCase().replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
@@ -133,28 +202,74 @@ export function shouldResetStreamingPending(text: string) {
133
202
  return /^\[[^\]]+\]$/.test(cleaned) || /^\([^)]*\)$/.test(cleaned);
134
203
  }
135
204
 
136
- export function queueStableStreamingWords(ctx: ExtensionContext, state: StreamingState, currentWords: string[]) {
137
- // Popular Whisper streaming frontends use local agreement: show/commit only the common prefix of consecutive hypotheses.
138
- const stableCount = commonStreamingPrefixLength(state.pendingWords, currentWords);
139
- const maxConfirmed = state.emittedWords.length === 0 && currentWords.length < STREAM_MIN_INITIAL_WORDS ? 0 : stableCount;
140
- const confirmedCount = Math.min(maxConfirmed, getStreamWordsPerChunk());
141
- if (confirmedCount > 0) queueStreamingWords(state, currentWords.slice(0, confirmedCount));
142
- state.pendingWords = currentWords.slice(confirmedCount);
205
+ export function queueStableStreamingWords(ctx: ExtensionContext, state: StreamingState, currentWords: string[], mode: StreamingFrameMode = "cumulative") {
206
+ const words = currentWords.filter(Boolean);
207
+
208
+ if (mode === "reset") {
209
+ state.candidateWords = trimCommittedStreamingPrefix(state, words);
210
+ renderStreamingPreview(ctx, state, false);
211
+ scheduleStreamingFlush(ctx, state);
212
+ return;
213
+ }
214
+
215
+ if (mode === "incremental") {
216
+ commitStreamingCandidate(state);
217
+ state.candidateWords = trimCommittedStreamingPrefix(state, words);
218
+ renderStreamingPreview(ctx, state, false);
219
+ scheduleStreamingFlush(ctx, state);
220
+ return;
221
+ }
222
+
223
+ if (mode === "rolling") {
224
+ queueRollingStreamingWords(state, words);
225
+ renderStreamingPreview(ctx, state, false);
226
+ scheduleStreamingFlush(ctx, state);
227
+ return;
228
+ }
229
+
230
+ if (mode === "duplicate" && words.length === 0) {
231
+ renderStreamingPreview(ctx, state, false);
232
+ scheduleStreamingFlush(ctx, state);
233
+ return;
234
+ }
235
+
236
+ const stableCount = commonStreamingPrefixLength(state.candidateWords, words);
237
+ const confirmedCount = Math.min(stableCount, getStreamWordsPerChunk());
238
+ if (confirmedCount > 0) queueStreamingWords(state, words.slice(0, confirmedCount));
239
+ state.candidateWords = words.slice(confirmedCount);
143
240
  renderStreamingPreview(ctx, state, false);
241
+ scheduleStreamingFlush(ctx, state);
144
242
  }
145
243
 
146
- export function flushPendingStreamingWords(ctx: ExtensionContext, state: StreamingState) {
147
- if (state.pendingWords.length > 0) {
148
- queueStreamingWords(state, state.pendingWords);
149
- state.pendingWords = [];
150
- }
151
- renderStreamingPreview(ctx, state, true);
244
+ export function flushPendingStreamingWords(ctx: ExtensionContext, state: StreamingState, trailingSpace = true) {
245
+ clearStreamingFlush(state);
246
+ commitStreamingCandidate(state);
247
+ renderStreamingPreview(ctx, state, trailingSpace);
248
+ showStreamingFrameDiagnostics(ctx, state, {
249
+ extractionMode: "flush",
250
+ newWords: [],
251
+ reason: trailingSpace ? "stop flush" : "pause flush",
252
+ });
253
+ }
254
+
255
+ export function scheduleStreamingFlush(ctx: ExtensionContext, state: StreamingState) {
256
+ clearStreamingFlush(state);
257
+ if (state.candidateWords.length === 0) return;
258
+ const delayMs = getStreamFlushMs();
259
+ state.flushTimer = setTimeout(() => {
260
+ state.flushTimer = undefined;
261
+ flushPendingStreamingWords(ctx, state, false);
262
+ }, delayMs);
263
+ unrefStreamingTimer(state.flushTimer);
152
264
  }
153
265
 
154
266
  export function queueStreamingWords(state: StreamingState, words: string[]) {
155
267
  const nextWords = words.filter(Boolean);
156
268
  if (nextWords.length === 0) return;
157
- state.emittedWords.push(...nextWords);
269
+ const overlap = streamingWordOverlap(state.emittedWords, nextWords);
270
+ const appendWords = nextWords.slice(overlap);
271
+ if (appendWords.length === 0) return;
272
+ state.emittedWords.push(...appendWords);
158
273
  }
159
274
 
160
275
  export function splitStreamingWords(text: string) {
@@ -181,6 +296,15 @@ export function commonStreamingPrefixLength(previousWords: string[], currentWord
181
296
  return count;
182
297
  }
183
298
 
299
+ export function commonStreamingSuffixLength(previousWords: string[], currentWords: string[]) {
300
+ const maxSuffix = Math.min(previousWords.length, currentWords.length);
301
+ let count = 0;
302
+ while (count < maxSuffix && normalizeStreamingWord(previousWords[previousWords.length - 1 - count] ?? "") === normalizeStreamingWord(currentWords[currentWords.length - 1 - count] ?? "")) {
303
+ count++;
304
+ }
305
+ return count;
306
+ }
307
+
184
308
  export function streamingWordsEqual(left: string[], right: string[]) {
185
309
  if (left.length !== right.length) return false;
186
310
  return left.every((word, index) => normalizeStreamingWord(word) === normalizeStreamingWord(right[index] ?? ""));
@@ -192,7 +316,7 @@ export function normalizeStreamingWord(word: string) {
192
316
  }
193
317
 
194
318
  export function getStreamingTranscript(state: StreamingState) {
195
- return [...state.emittedWords, ...state.pendingWords].join(" ");
319
+ return state.emittedWords.join(" ");
196
320
  }
197
321
 
198
322
  export function renderStreamingPreview(ctx: ExtensionContext, state: StreamingState, trailingSpace: boolean) {
@@ -235,3 +359,74 @@ export function clearStreamingFlush(state: StreamingState) {
235
359
  clearTimeout(state.flushTimer);
236
360
  state.flushTimer = undefined;
237
361
  }
362
+
363
+ function queueRollingStreamingWords(state: StreamingState, words: string[]) {
364
+ const overlap = streamingWordOverlap(state.candidateWords, words);
365
+ if (overlap <= 0) {
366
+ commitStreamingCandidate(state);
367
+ state.candidateWords = trimCommittedStreamingPrefix(state, words);
368
+ return;
369
+ }
370
+
371
+ const previousCandidatePrefix = state.candidateWords.slice(0, state.candidateWords.length - overlap);
372
+ queueStreamingWords(state, previousCandidatePrefix);
373
+ const confirmedOverlap = Math.min(overlap, getStreamWordsPerChunk());
374
+ queueStreamingWords(state, words.slice(0, confirmedOverlap));
375
+ state.candidateWords = trimCommittedStreamingPrefix(state, words.slice(confirmedOverlap));
376
+ }
377
+
378
+ function commitStreamingCandidate(state: StreamingState) {
379
+ if (state.candidateWords.length === 0) return;
380
+ queueStreamingWords(state, state.candidateWords);
381
+ state.candidateWords = [];
382
+ }
383
+
384
+ function trimCommittedStreamingPrefix(state: StreamingState, words: string[]) {
385
+ const overlap = streamingWordOverlap(state.emittedWords, words);
386
+ return words.slice(overlap);
387
+ }
388
+
389
+ function isStreamingWordsPrefix(prefixWords: string[], words: string[]) {
390
+ if (prefixWords.length === 0 || prefixWords.length > words.length) return false;
391
+ return streamingWordsEqual(prefixWords, words.slice(0, prefixWords.length));
392
+ }
393
+
394
+ function looksLikeStreamingCorrection(previousWords: string[], currentWords: string[]) {
395
+ if (previousWords.length === 0 || currentWords.length === 0) return false;
396
+ if (previousWords.length === 1 && currentWords.length === 1) return false;
397
+ if (commonStreamingPrefixLength(previousWords, currentWords) > 0) return true;
398
+ if (commonStreamingSuffixLength(previousWords, currentWords) > 0) return true;
399
+ const previousNormalized = new Set(previousWords.map(normalizeStreamingWord));
400
+ const sharedCount = currentWords.filter((word) => previousNormalized.has(normalizeStreamingWord(word))).length;
401
+ return previousWords.length > 1 && currentWords.length > 1 && sharedCount >= Math.ceil(Math.min(previousWords.length, currentWords.length) / 2);
402
+ }
403
+
404
+ function showStreamingFrameDiagnostics(ctx: ExtensionContext, state: StreamingState, details: StreamingDiagnosticDetails) {
405
+ if (!envFlag("MICME_STREAM_DIAGNOSTICS")) return;
406
+ const payload = {
407
+ rawFrame: details.rawFrame === undefined ? undefined : truncateStreamingDiagnostic(stripStreamingControls(details.rawFrame)),
408
+ sanitizedText: details.sanitizedText === undefined ? undefined : truncateStreamingDiagnostic(details.sanitizedText),
409
+ frameWords: limitStreamingDiagnosticWords(details.frameWords ?? []),
410
+ emittedWords: limitStreamingDiagnosticWords(state.emittedWords),
411
+ candidateWords: limitStreamingDiagnosticWords(state.candidateWords),
412
+ previewText: truncateStreamingDiagnostic(getStreamingTranscript(state)),
413
+ extractionMode: details.extractionMode,
414
+ newWords: limitStreamingDiagnosticWords(details.newWords ?? []),
415
+ reason: details.reason,
416
+ };
417
+ ctx.ui.notify(`Micme stream frame: ${JSON.stringify(payload)}`, "info");
418
+ }
419
+
420
+ function limitStreamingDiagnosticWords(words: string[]) {
421
+ return words.slice(-16);
422
+ }
423
+
424
+ function truncateStreamingDiagnostic(value: string) {
425
+ return value.length > 160 ? `${value.slice(0, 157)}...` : value;
426
+ }
427
+
428
+ function unrefStreamingTimer(timer: ReturnType<typeof setTimeout>) {
429
+ if (typeof timer !== "object" || timer === null || !("unref" in timer)) return;
430
+ const unref = timer.unref;
431
+ if (typeof unref === "function") unref.call(timer);
432
+ }
package/src/types.ts CHANGED
@@ -35,8 +35,9 @@ export type StreamingState = {
35
35
  previewText: string;
36
36
  outputBuffer: string;
37
37
  lastText: string;
38
- pendingWords: string[];
39
38
  emittedWords: string[];
39
+ candidateWords: string[];
40
+ lastHypothesisWords: string[];
40
41
  startedAt: number;
41
42
  firstOutputAt?: number;
42
43
  firstPreviewAt?: number;
@@ -59,7 +60,7 @@ export type Recording = {
59
60
  stderr: () => string;
60
61
  };
61
62
 
62
- export type DotEnvState = {
63
+ export type MicmeConfigState = {
63
64
  path: string;
64
65
  values: Record<string, string>;
65
66
  error?: string;
package/.env.example DELETED
@@ -1,75 +0,0 @@
1
- # Micme safe example configuration
2
- # Copy this file to .env, then run /micme conf inside pi to adjust it for your machine.
3
- # Shell environment variables override values from .env.
4
-
5
- # Shortcut used by the extension. macOS displays alt as Option.
6
- # Some terminals insert a printable character for Option+M instead of sending Alt+M.
7
- MICME_SHORTCUT=alt+m
8
- MICME_PRINTABLE_SHORTCUTS=§
9
-
10
- # Transcription behavior.
11
- # clip = stable default: record first, then transcribe when stopped.
12
- # stream = experimental live preview using whisper-stream.
13
- MICME_TRANSCRIPTION_MODE=clip
14
- MICME_AUTO_SUBMIT=0
15
- MICME_LANGUAGE=en
16
- MICME_TRANSCRIBE_TIMEOUT_MS=120000
17
-
18
- # Privacy/debugging.
19
- # By default Micme removes temp audio after successful transcription.
20
- MICME_KEEP_AUDIO=0
21
- MICME_VALIDATE_AUDIO=1
22
- MICME_MIN_MAX_VOLUME_DB=-50
23
-
24
- # Recorder selection.
25
- # Leave these unset until /micme devices shows the right value for your OS.
26
- # macOS avfoundation examples:
27
- # MICME_AUDIO_DEVICE=0
28
- # MICME_AVFOUNDATION_INPUT=:0
29
- # Linux PulseAudio example:
30
- # MICME_PULSE_SOURCE=default
31
- # Windows DirectShow example:
32
- # MICME_DSHOW_AUDIO_DEVICE=default
33
-
34
- # Recording/preprocessing. Micme records a raw WAV, then prepares a 16 kHz WAV for Whisper.
35
- MICME_RECORD_SAMPLE_RATE=48000
36
- MICME_TRANSCRIBE_SAMPLE_RATE=16000
37
- MICME_PROCESS_AUDIO=1
38
- MICME_AUDIO_FILTER=highpass=f=80,lowpass=f=7600
39
-
40
- # Recording meter tuning. Defaults should be fine for most microphones.
41
- MICME_METER_GAIN=1
42
- MICME_METER_FLOOR_DB=55
43
- MICME_METER_RANGE_DB=35
44
-
45
- # Recommended backend: whisper.cpp. Install it separately, then either leave the binary unset
46
- # so Micme searches PATH, or set MICME_WHISPER_CPP_BIN to an explicit local path.
47
- MICME_AUTO_DOWNLOAD_MODEL=1
48
- MICME_DEFAULT_WHISPER_CPP_MODEL=small.en
49
- MICME_MODEL_DIR=$HOME/.cache/whisper.cpp
50
- # MICME_WHISPER_CPP_BIN=whisper-cli
51
- # MICME_WHISPER_STREAM_BIN=whisper-stream
52
- # MICME_WHISPER_CPP_MODEL=$HOME/.cache/whisper.cpp/ggml-small.en.bin
53
-
54
- # Python openai-whisper fallback. Used only when whisper.cpp is not configured/found.
55
- MICME_WHISPER_MODEL=base.en
56
- MICME_WHISPER_DEVICE=cpu
57
- MICME_WHISPER_FP16=False
58
-
59
- # Experimental streaming profile. /micme conf can apply a low-latency profile automatically.
60
- MICME_STREAM_CAPTURE=-1
61
- MICME_STREAM_WORDS_PER_CHUNK=5
62
- MICME_STREAM_STEP_MS=500
63
- MICME_STREAM_LENGTH_MS=3000
64
- MICME_STREAM_KEEP_MS=300
65
- MICME_STREAM_MAX_TOKENS=32
66
- MICME_STREAM_KEEP_CONTEXT=1
67
- MICME_STREAM_FINALIZE_WITH_CLIP=0
68
- MICME_STREAM_VAD_THRESHOLD=0.35
69
- MICME_STREAM_DIAGNOSTICS=0
70
-
71
- # Advanced custom hooks. Placeholders are shell-quoted unless the Raw suffix is used:
72
- # {audio}, {audioRaw}, {tempDir}, {tempDirRaw}, {transcript}, {transcriptRaw}
73
- # Raw placeholders bypass shell quoting; use them only when you fully control the command.
74
- # MICME_RECORD_COMMAND=ffmpeg -hide_banner -loglevel error -f avfoundation -i :0 -ac 1 -ar 16000 -y {audio}
75
- # MICME_TRANSCRIBE_COMMAND=whisper-cli -m /path/to/model.bin -f {audio} -otxt -of {tempDirRaw}/out -nt -np && cat {tempDirRaw}/out.txt