@senad-d/micme 0.3.1 → 0.3.2
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/SECURITY.md +2 -1
- package/package.json +1 -1
- package/src/audio.ts +10 -5
- package/src/backends.ts +2 -1
- package/src/extension.ts +74 -56
- package/src/models.ts +7 -1
- package/src/processes.ts +21 -8
- package/src/recording-dir.ts +12 -1
- package/src/settings.ts +113 -9
- package/src/streaming.ts +2 -1
- package/src/terminal-text.ts +11 -0
package/SECURITY.md
CHANGED
|
@@ -23,7 +23,7 @@ The default recorder uses `ffmpeg` and your operating system's microphone APIs:
|
|
|
23
23
|
- Linux: PulseAudio through `ffmpeg -f pulse`
|
|
24
24
|
- Windows: DirectShow through `ffmpeg -f dshow`
|
|
25
25
|
|
|
26
|
-
Micme writes temporary audio files under the operating system temp directory by default. After successful transcription, those files are removed. Set `MICME_KEEP_AUDIO=1` only when you intentionally want to keep raw/preprocessed audio for debugging; kept recordings are written to per-recording project directories such as `./micme-rec/rec-001/`.
|
|
26
|
+
Micme writes temporary audio files under the operating system temp directory by default. After successful transcription, those files are removed. Set `MICME_KEEP_AUDIO=1` only when you intentionally want to keep raw/preprocessed audio for debugging; kept recordings are written to per-recording project directories such as `./micme-rec/rec-001/`. Micme refuses to keep audio when the project `micme-rec` directory is a symbolic link.
|
|
27
27
|
|
|
28
28
|
## Local process execution
|
|
29
29
|
|
|
@@ -33,6 +33,7 @@ Micme spawns local processes for recording and transcription:
|
|
|
33
33
|
- `whisper-cli` or `whisper-cpp` for whisper.cpp transcription.
|
|
34
34
|
- `whisper-stream` for experimental streaming mode.
|
|
35
35
|
- `whisper` for the optional Python openai-whisper fallback.
|
|
36
|
+
- `python -I` only for optional Python Whisper model-name discovery in `/micme conf`; isolated mode avoids importing project-local Python files.
|
|
36
37
|
- Optional user-provided shell commands in `MICME_RECORD_COMMAND` and `MICME_TRANSCRIBE_COMMAND`.
|
|
37
38
|
|
|
38
39
|
The default process output is capped before it is shown to users or errors. Diagnostics should not print secret values.
|
package/package.json
CHANGED
package/src/audio.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { join } from "node:path";
|
|
|
4
4
|
import { AUDIO_VALIDATION_TIMEOUT_MS } from "./constants.ts";
|
|
5
5
|
import { env, envFlag, getAudioFilter, getAvfoundationDropLateFrames, getAvfoundationInputSampleRate, getMinMaxVolumeDb, getRecordMeter, getRecordSampleRate, getRecordSync, getTranscribeSampleRate } from "./config.ts";
|
|
6
6
|
import { findExecutable, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
|
|
7
|
+
import { sanitizeTerminalText } from "./terminal-text.ts";
|
|
7
8
|
import type { AudioDeviceCandidate, AudioDiagnostics, CommandSpec, RunResult } from "./types.ts";
|
|
8
9
|
|
|
9
10
|
type DeviceBackend = "avfoundation" | "pulse" | "dshow" | "unsupported";
|
|
@@ -226,8 +227,8 @@ export function parseAvfoundationDevices(output: string): ParsedDeviceInventory
|
|
|
226
227
|
|
|
227
228
|
const match = line.match(/\[(\d+)\]\s+(.+)$/);
|
|
228
229
|
if (!match) continue;
|
|
229
|
-
const id = match[1] ?? "";
|
|
230
|
-
const name = (match[2] ?? "")
|
|
230
|
+
const id = sanitizeDeviceField(match[1] ?? "");
|
|
231
|
+
const name = sanitizeDeviceField(match[2] ?? "");
|
|
231
232
|
if (!name) continue;
|
|
232
233
|
inventory[section].push({ id, name });
|
|
233
234
|
}
|
|
@@ -251,9 +252,9 @@ function parsePulseAudioDevices(output: string): ParsedDeviceInventory {
|
|
|
251
252
|
const sourceLine = line.replace(/^\*\s*/, "");
|
|
252
253
|
const match = sourceLine.match(/^([^\s\[]+)(?:\s+\[(.+)\])?$/);
|
|
253
254
|
if (!match) continue;
|
|
254
|
-
const id = (match[1] ?? "")
|
|
255
|
+
const id = sanitizeDeviceField(match[1] ?? "");
|
|
255
256
|
if (!id || id.includes(":")) continue;
|
|
256
|
-
let name = (match[2] ?? "")
|
|
257
|
+
let name = sanitizeDeviceField(match[2] ?? "");
|
|
257
258
|
if (id === "default" && (!name || /^default$/i.test(name))) name = "PulseAudio default source";
|
|
258
259
|
inventory.audio.push({ id, name });
|
|
259
260
|
}
|
|
@@ -280,7 +281,7 @@ function parseDirectShowDevices(output: string): ParsedDeviceInventory {
|
|
|
280
281
|
if (!section || /Alternative name/i.test(line)) continue;
|
|
281
282
|
|
|
282
283
|
const match = line.match(/^"(.+)"$/) ?? line.match(/"([^"]+)"/);
|
|
283
|
-
const name = (match?.[1] ?? "")
|
|
284
|
+
const name = sanitizeDeviceField(match?.[1] ?? "");
|
|
284
285
|
if (!name) continue;
|
|
285
286
|
inventory[section].push({ name });
|
|
286
287
|
}
|
|
@@ -292,6 +293,10 @@ function stripFfmpegLogPrefix(line: string) {
|
|
|
292
293
|
return line.replace(/^(?:\[[^\]]+\]\s*)+/, "");
|
|
293
294
|
}
|
|
294
295
|
|
|
296
|
+
function sanitizeDeviceField(value: string) {
|
|
297
|
+
return sanitizeTerminalText(value);
|
|
298
|
+
}
|
|
299
|
+
|
|
295
300
|
function hasMacosPermissionIssue(output: string) {
|
|
296
301
|
return /(?:not authorized|authorization|privacy|permission|operation not permitted|microphone access|access.*microphone|microphone.*blocked)/i.test(output);
|
|
297
302
|
}
|
package/src/backends.ts
CHANGED
|
@@ -3,7 +3,7 @@ import type { TranscribeBackend, TranscriptionMode, ResolvedTranscriptionPlan, R
|
|
|
3
3
|
import { DEFAULT_TRANSCRIBE_BACKEND } from "./constants.ts";
|
|
4
4
|
import { env, expandConfigPath, getTranscribeBackend, getTranslateToEnglishLanguage, isTranscribeBackend } from "./config.ts";
|
|
5
5
|
import { getPythonWhisperModelName, isEnglishOnlyWhisperModelName, isTranslationUnsupportedWhisperModelName, resolveWhisperCppModel } from "./models.ts";
|
|
6
|
-
import { findExecutable } from "./processes.ts";
|
|
6
|
+
import { findExecutable, isExecutableFile } from "./processes.ts";
|
|
7
7
|
|
|
8
8
|
export type ResolveTranscriptionPlanOptions = {
|
|
9
9
|
requestedBackend?: TranscribeBackend | string;
|
|
@@ -88,6 +88,7 @@ export function resolveExecutableConfig(value: string, configName: string) {
|
|
|
88
88
|
const expanded = expandConfigPath(value);
|
|
89
89
|
if (/[/\\]/.test(expanded)) {
|
|
90
90
|
if (!existsSync(expanded)) throw new Error(`${configName} is set but not found: ${expanded}`);
|
|
91
|
+
if (!isExecutableFile(expanded)) throw new Error(`${configName} is set but is not an executable file: ${expanded}`);
|
|
91
92
|
return expanded;
|
|
92
93
|
}
|
|
93
94
|
const executable = findExecutable([expanded]);
|
package/src/extension.ts
CHANGED
|
@@ -173,24 +173,38 @@ async function startRecording(ctx: ExtensionContext, stopHint = getShortcut()) {
|
|
|
173
173
|
}
|
|
174
174
|
|
|
175
175
|
const tempDir = await createRecordingDirectory(ctx.cwd, envFlag("MICME_KEEP_AUDIO"), "micme-");
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
176
|
+
let active: Recording | undefined;
|
|
177
|
+
|
|
178
|
+
try {
|
|
179
|
+
const audioPath = join(tempDir, "raw.wav");
|
|
180
|
+
const command = buildRecorderCommand(audioPath);
|
|
181
|
+
active = spawnRecording(command, audioPath, tempDir);
|
|
182
|
+
recording = active;
|
|
183
|
+
|
|
184
|
+
const earlyExit = await raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS);
|
|
185
|
+
if (earlyExit) {
|
|
186
|
+
if (active.stopRequested) return;
|
|
187
|
+
const stderr = active.stderr().trim();
|
|
188
|
+
const suffix = stderr ? `\n${stderr}` : "";
|
|
189
|
+
throw new Error(`Micme recorder exited early (${formatExit(earlyExit)}).${suffix}`);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
ctx.ui.setStatus(STATUS_KEY, `● recording (${stopHint} or /micme)`);
|
|
193
|
+
startRecordingWidget(ctx, active);
|
|
194
|
+
} catch (error) {
|
|
195
|
+
await cleanupFailedRecordingStart(ctx, tempDir, active);
|
|
196
|
+
throw error;
|
|
190
197
|
}
|
|
198
|
+
}
|
|
191
199
|
|
|
192
|
-
|
|
193
|
-
|
|
200
|
+
async function cleanupFailedRecordingStart(ctx: ExtensionContext, tempDir: string, active: Recording | undefined) {
|
|
201
|
+
if (active && recording === active) recording = undefined;
|
|
202
|
+
clearRecordingWidget(ctx);
|
|
203
|
+
if (active) {
|
|
204
|
+
await stopProcess(active).catch(() => undefined);
|
|
205
|
+
if (active.clipRecording) await stopProcess(active.clipRecording).catch(() => undefined);
|
|
206
|
+
}
|
|
207
|
+
await cleanup(tempDir).catch(() => undefined);
|
|
194
208
|
}
|
|
195
209
|
|
|
196
210
|
async function stopAndTranscribe(ctx: ExtensionContext, pi: ExtensionAPI) {
|
|
@@ -251,49 +265,53 @@ async function startStreamingTranscription(ctx: ExtensionContext, stopHint = get
|
|
|
251
265
|
await ensureWhisperCppModel(plan.modelPath, ctx, { allowDownload: plan.modelDownloadable !== false });
|
|
252
266
|
|
|
253
267
|
const tempDir = await createRecordingDirectory(ctx.cwd, envFlag("MICME_KEEP_AUDIO"), "micme-stream-");
|
|
254
|
-
|
|
255
|
-
const active = spawnRecording(command, "", tempDir);
|
|
256
|
-
const baseText = ctx.ui.getEditorText();
|
|
257
|
-
active.streaming = {
|
|
258
|
-
baseText,
|
|
259
|
-
previewText: baseText,
|
|
260
|
-
outputBuffer: "",
|
|
261
|
-
lastText: "",
|
|
262
|
-
emittedWords: [],
|
|
263
|
-
candidateWords: [],
|
|
264
|
-
lastHypothesisWords: [],
|
|
265
|
-
startedAt: Date.now(),
|
|
266
|
-
};
|
|
267
|
-
if (getStreamFinalizeWithClip()) {
|
|
268
|
-
const audioPath = join(tempDir, "raw.wav");
|
|
269
|
-
active.clipRecording = spawnRecording(buildRecorderCommand(audioPath), audioPath, tempDir);
|
|
270
|
-
}
|
|
271
|
-
recording = active;
|
|
268
|
+
let active: Recording | undefined;
|
|
272
269
|
|
|
273
|
-
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
270
|
+
try {
|
|
271
|
+
const command = buildWhisperStreamCommand(plan.binary, plan.modelPath, tempDir);
|
|
272
|
+
const clipAudioPath = getStreamFinalizeWithClip() ? join(tempDir, "raw.wav") : undefined;
|
|
273
|
+
const clipCommand = clipAudioPath ? buildRecorderCommand(clipAudioPath) : undefined;
|
|
274
|
+
active = spawnRecording(command, "", tempDir);
|
|
275
|
+
const streamRecording = active;
|
|
276
|
+
const baseText = ctx.ui.getEditorText();
|
|
277
|
+
streamRecording.streaming = {
|
|
278
|
+
baseText,
|
|
279
|
+
previewText: baseText,
|
|
280
|
+
outputBuffer: "",
|
|
281
|
+
lastText: "",
|
|
282
|
+
emittedWords: [],
|
|
283
|
+
candidateWords: [],
|
|
284
|
+
lastHypothesisWords: [],
|
|
285
|
+
startedAt: Date.now(),
|
|
286
|
+
};
|
|
287
|
+
if (clipCommand && clipAudioPath) {
|
|
288
|
+
streamRecording.clipRecording = spawnRecording(clipCommand, clipAudioPath, tempDir);
|
|
289
|
+
}
|
|
290
|
+
recording = streamRecording;
|
|
277
291
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
if (earlyExit || recorderEarlyExit) {
|
|
283
|
-
if (active.stopRequested || active.clipRecording?.stopRequested) return;
|
|
284
|
-
recording = undefined;
|
|
285
|
-
clearRecordingWidget(ctx);
|
|
286
|
-
await stopProcess(active).catch(() => undefined);
|
|
287
|
-
if (active.clipRecording) await stopProcess(active.clipRecording).catch(() => undefined);
|
|
288
|
-
await cleanup(tempDir).catch(() => undefined);
|
|
289
|
-
const failed = earlyExit ? active : active.clipRecording;
|
|
290
|
-
const stderr = failed?.stderr().trim();
|
|
291
|
-
const suffix = stderr ? `\n${stderr}` : "";
|
|
292
|
-
throw new Error(`Micme streaming exited early (${formatExit(earlyExit ?? recorderEarlyExit!)}).${suffix}`);
|
|
293
|
-
}
|
|
292
|
+
streamRecording.process.stdout?.on("data", (chunk: Buffer | string) => {
|
|
293
|
+
const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
|
|
294
|
+
handleStreamingOutput(ctx, streamRecording, text);
|
|
295
|
+
});
|
|
294
296
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
+
const [earlyExit, recorderEarlyExit] = await Promise.all([
|
|
298
|
+
raceWithTimeout(streamRecording.exitPromise, RECORDER_STARTUP_GRACE_MS),
|
|
299
|
+
streamRecording.clipRecording ? raceWithTimeout(streamRecording.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
|
|
300
|
+
]);
|
|
301
|
+
if (earlyExit || recorderEarlyExit) {
|
|
302
|
+
if (streamRecording.stopRequested || streamRecording.clipRecording?.stopRequested) return;
|
|
303
|
+
const failed = earlyExit ? streamRecording : streamRecording.clipRecording;
|
|
304
|
+
const stderr = failed?.stderr().trim();
|
|
305
|
+
const suffix = stderr ? `\n${stderr}` : "";
|
|
306
|
+
throw new Error(`Micme streaming exited early (${formatExit(earlyExit ?? recorderEarlyExit!)}).${suffix}`);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
ctx.ui.setStatus(STATUS_KEY, `● streaming (${stopHint} or /micme)`);
|
|
310
|
+
startRecordingWidget(ctx, streamRecording);
|
|
311
|
+
} catch (error) {
|
|
312
|
+
await cleanupFailedRecordingStart(ctx, tempDir, active);
|
|
313
|
+
throw error;
|
|
314
|
+
}
|
|
297
315
|
}
|
|
298
316
|
|
|
299
317
|
async function stopStreamingTranscription(ctx: ExtensionContext, pi: ExtensionAPI, active: Recording) {
|
package/src/models.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { findExecutable, runProcess } from "./processes.ts";
|
|
|
18
18
|
import type { ModelCandidate, ResolvedWhisperCppModel } from "./types.ts";
|
|
19
19
|
|
|
20
20
|
const modelDownloads = new Map<string, Promise<void>>();
|
|
21
|
+
const PYTHON_WHISPER_MODELS_SCRIPT = "import whisper; print('\\n'.join(whisper.available_models()))";
|
|
21
22
|
|
|
22
23
|
export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
|
|
23
24
|
const candidates: ModelCandidate[] = [];
|
|
@@ -222,7 +223,7 @@ export async function queryPythonWhisperModelNames(): Promise<string[]> {
|
|
|
222
223
|
if (!python) return [];
|
|
223
224
|
|
|
224
225
|
try {
|
|
225
|
-
const result = await runProcess(python,
|
|
226
|
+
const result = await runProcess(python, getPythonWhisperModelQueryArgs(), 2_000);
|
|
226
227
|
if (result.code !== 0 || result.timedOut) return [];
|
|
227
228
|
return uniqueModelNames(result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
|
|
228
229
|
} catch {
|
|
@@ -230,6 +231,11 @@ export async function queryPythonWhisperModelNames(): Promise<string[]> {
|
|
|
230
231
|
}
|
|
231
232
|
}
|
|
232
233
|
|
|
234
|
+
export function getPythonWhisperModelQueryArgs() {
|
|
235
|
+
// Isolated mode prevents project-local Python files (for example ./whisper.py) or PYTHONPATH from executing during model discovery.
|
|
236
|
+
return ["-I", "-c", PYTHON_WHISPER_MODELS_SCRIPT];
|
|
237
|
+
}
|
|
238
|
+
|
|
233
239
|
export function uniqueModelNames(names: string[]) {
|
|
234
240
|
const seen = new Set<string>();
|
|
235
241
|
const output: string[] = [];
|
package/src/processes.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { spawn } from "node:child_process";
|
|
2
|
-
import {
|
|
2
|
+
import { accessSync, constants as fsConstants, statSync } from "node:fs";
|
|
3
3
|
import { rm, stat } from "node:fs/promises";
|
|
4
4
|
import { delimiter, join } from "node:path";
|
|
5
5
|
import { MAX_CAPTURED_OUTPUT_CHARS, MIN_AUDIO_BYTES, RECORDER_STOP_GRACE_MS } from "./constants.ts";
|
|
@@ -17,6 +17,8 @@ export function spawnRecording(command: CommandSpec, audioPath: string, tempDir:
|
|
|
17
17
|
let settled = false;
|
|
18
18
|
let audioLevel = 0;
|
|
19
19
|
|
|
20
|
+
child.stdin?.on("error", () => undefined);
|
|
21
|
+
|
|
20
22
|
if (command.meterFromStdout) {
|
|
21
23
|
child.stdout?.on("data", (chunk: Buffer) => {
|
|
22
24
|
audioLevel = audioLevel * 0.35 + pcm16BufferLevel(chunk) * 0.65;
|
|
@@ -163,12 +165,11 @@ export function normalizeTranscript(text: string) {
|
|
|
163
165
|
}
|
|
164
166
|
|
|
165
167
|
export function replacePlaceholders(template: string, values: Record<string, string>) {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
}
|
|
171
|
-
return output;
|
|
168
|
+
return template.replace(/\{([A-Za-z][A-Za-z0-9]*?)(Raw)?\}/g, (placeholder, key: string, rawSuffix: string | undefined) => {
|
|
169
|
+
if (!Object.prototype.hasOwnProperty.call(values, key)) return placeholder;
|
|
170
|
+
const value = values[key] ?? "";
|
|
171
|
+
return rawSuffix ? value : shellQuote(value);
|
|
172
|
+
});
|
|
172
173
|
}
|
|
173
174
|
|
|
174
175
|
export function findExecutable(names: string[]) {
|
|
@@ -179,13 +180,25 @@ export function findExecutable(names: string[]) {
|
|
|
179
180
|
for (const dir of dirs) {
|
|
180
181
|
for (const extension of extensions) {
|
|
181
182
|
const candidate = join(dir, process.platform === "win32" && !/\.[^.]+$/.test(name) ? `${name}${extension}` : name);
|
|
182
|
-
if (
|
|
183
|
+
if (isExecutableFile(candidate)) return candidate;
|
|
183
184
|
}
|
|
184
185
|
}
|
|
185
186
|
}
|
|
186
187
|
return undefined;
|
|
187
188
|
}
|
|
188
189
|
|
|
190
|
+
export function isExecutableFile(path: string) {
|
|
191
|
+
try {
|
|
192
|
+
const stats = statSync(path);
|
|
193
|
+
if (!stats.isFile()) return false;
|
|
194
|
+
if (process.platform === "win32") return true;
|
|
195
|
+
accessSync(path, fsConstants.X_OK);
|
|
196
|
+
return true;
|
|
197
|
+
} catch {
|
|
198
|
+
return false;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
189
202
|
export function appendCapped(current: string, chunk: string) {
|
|
190
203
|
const next = current + chunk;
|
|
191
204
|
return next.length > MAX_CAPTURED_OUTPUT_CHARS ? next.slice(-MAX_CAPTURED_OUTPUT_CHARS) : next;
|
package/src/recording-dir.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { mkdir, mkdtemp, readdir } from "node:fs/promises";
|
|
1
|
+
import { lstat, mkdir, mkdtemp, readdir } from "node:fs/promises";
|
|
2
2
|
import { tmpdir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
|
|
@@ -14,6 +14,7 @@ export async function createRecordingDirectory(cwd: string, keepAudio: boolean,
|
|
|
14
14
|
export async function createProjectRecordingDirectory(cwd: string) {
|
|
15
15
|
const recordingsRoot = join(cwd, PROJECT_RECORDINGS_DIR);
|
|
16
16
|
await mkdir(recordingsRoot, { recursive: true });
|
|
17
|
+
await assertSafeRecordingsRoot(recordingsRoot);
|
|
17
18
|
|
|
18
19
|
const nextIndex = await getNextRecordingIndex(recordingsRoot);
|
|
19
20
|
|
|
@@ -31,6 +32,16 @@ export async function createProjectRecordingDirectory(cwd: string) {
|
|
|
31
32
|
throw new Error(`Unable to create a Micme recording directory under ${recordingsRoot}.`);
|
|
32
33
|
}
|
|
33
34
|
|
|
35
|
+
async function assertSafeRecordingsRoot(recordingsRoot: string) {
|
|
36
|
+
const stats = await lstat(recordingsRoot);
|
|
37
|
+
if (stats.isSymbolicLink()) {
|
|
38
|
+
throw new Error(`Refusing to keep Micme audio in a symbolic-link recordings directory: ${recordingsRoot}`);
|
|
39
|
+
}
|
|
40
|
+
if (!stats.isDirectory()) {
|
|
41
|
+
throw new Error(`Micme recordings path is not a directory: ${recordingsRoot}`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
34
45
|
async function getNextRecordingIndex(recordingsRoot: string) {
|
|
35
46
|
const entries = await readdir(recordingsRoot, { withFileTypes: true });
|
|
36
47
|
let maxIndex = 0;
|
package/src/settings.ts
CHANGED
|
@@ -88,6 +88,15 @@ const TRANSLATE_FROM_VALUE_LABELS: Record<string, string> = {
|
|
|
88
88
|
...Object.fromEntries(TRANSLATION_SOURCE_LANGUAGE_VALUES.map((language) => [language, `${LANGUAGE_LABELS[language] ?? language} → English`])),
|
|
89
89
|
};
|
|
90
90
|
|
|
91
|
+
type ConfigurationDiscoveryKey = "audio devices" | "whisper.cpp models" | "Python Whisper models";
|
|
92
|
+
|
|
93
|
+
type ConfigurationDiscoveryState = {
|
|
94
|
+
audioDevices: AudioDeviceCandidate[];
|
|
95
|
+
modelCandidates: ModelCandidate[];
|
|
96
|
+
pythonModelCandidates: ModelCandidate[];
|
|
97
|
+
pending: Set<ConfigurationDiscoveryKey>;
|
|
98
|
+
};
|
|
99
|
+
|
|
91
100
|
export async function showConfiguration(ctx: ExtensionContext) {
|
|
92
101
|
if (ctx.mode !== "tui") {
|
|
93
102
|
ctx.ui.notify("/micme conf requires interactive TUI mode.", "warning");
|
|
@@ -98,27 +107,109 @@ export async function showConfiguration(ctx: ExtensionContext) {
|
|
|
98
107
|
if (configState.error) {
|
|
99
108
|
ctx.ui.notify(`Micme config is invalid at ${configState.path}: ${configState.error}. Fix it before saving settings.`, "warning");
|
|
100
109
|
}
|
|
101
|
-
const audioDevices = await discoverAudioDevices();
|
|
102
|
-
const modelCandidates = discoverWhisperCppModels(ctx.cwd);
|
|
103
|
-
const pythonModelCandidates = await discoverPythonWhisperModels();
|
|
104
|
-
|
|
105
110
|
await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
|
|
106
|
-
const
|
|
107
|
-
|
|
111
|
+
const discovery = createInitialConfigurationDiscovery();
|
|
112
|
+
let closed = false;
|
|
113
|
+
const screen = new ConfigurationScreen({
|
|
108
114
|
configPath: configState.path,
|
|
109
|
-
items,
|
|
115
|
+
items: buildConfigurationItems(discovery.modelCandidates, discovery.pythonModelCandidates, discovery.audioDevices, theme),
|
|
110
116
|
theme,
|
|
111
|
-
onDone:
|
|
117
|
+
onDone: () => {
|
|
118
|
+
closed = true;
|
|
119
|
+
done();
|
|
120
|
+
},
|
|
112
121
|
onError: (error) => ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"),
|
|
113
122
|
onSave: (id, newValue) => saveConfigurationValue(ctx, id, newValue),
|
|
114
123
|
requestRender: () => tui.requestRender(),
|
|
124
|
+
statusText: formatDiscoveryStatus(discovery.pending),
|
|
115
125
|
});
|
|
126
|
+
|
|
127
|
+
startConfigurationDiscovery({
|
|
128
|
+
ctx,
|
|
129
|
+
cwd: ctx.cwd,
|
|
130
|
+
theme,
|
|
131
|
+
discovery,
|
|
132
|
+
screen,
|
|
133
|
+
isClosed: () => closed,
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
return screen;
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function createInitialConfigurationDiscovery(): ConfigurationDiscoveryState {
|
|
141
|
+
return {
|
|
142
|
+
audioDevices: [],
|
|
143
|
+
modelCandidates: [],
|
|
144
|
+
pythonModelCandidates: [],
|
|
145
|
+
pending: new Set(["audio devices", "whisper.cpp models", "Python Whisper models"]),
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function startConfigurationDiscovery(options: {
|
|
150
|
+
ctx: ExtensionContext;
|
|
151
|
+
cwd: string;
|
|
152
|
+
theme: MicmeTheme;
|
|
153
|
+
discovery: ConfigurationDiscoveryState;
|
|
154
|
+
screen: ConfigurationScreen;
|
|
155
|
+
isClosed: () => boolean;
|
|
156
|
+
}) {
|
|
157
|
+
void loadConfigurationDiscovery(options, "audio devices", deferDiscovery(discoverAudioDevices), (audioDevices) => {
|
|
158
|
+
options.discovery.audioDevices = audioDevices;
|
|
159
|
+
});
|
|
160
|
+
void loadConfigurationDiscovery(options, "whisper.cpp models", deferDiscovery(() => discoverWhisperCppModels(options.cwd)), (modelCandidates) => {
|
|
161
|
+
options.discovery.modelCandidates = modelCandidates;
|
|
162
|
+
});
|
|
163
|
+
void loadConfigurationDiscovery(options, "Python Whisper models", deferDiscovery(discoverPythonWhisperModels), (pythonModelCandidates) => {
|
|
164
|
+
options.discovery.pythonModelCandidates = pythonModelCandidates;
|
|
116
165
|
});
|
|
117
166
|
}
|
|
118
167
|
|
|
168
|
+
async function loadConfigurationDiscovery<T>(
|
|
169
|
+
options: {
|
|
170
|
+
ctx: ExtensionContext;
|
|
171
|
+
theme: MicmeTheme;
|
|
172
|
+
discovery: ConfigurationDiscoveryState;
|
|
173
|
+
screen: ConfigurationScreen;
|
|
174
|
+
isClosed: () => boolean;
|
|
175
|
+
},
|
|
176
|
+
key: ConfigurationDiscoveryKey,
|
|
177
|
+
promise: Promise<T>,
|
|
178
|
+
applyResult: (value: T) => void,
|
|
179
|
+
) {
|
|
180
|
+
try {
|
|
181
|
+
applyResult(await promise);
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (!options.isClosed()) options.ctx.ui.notify(`Micme could not load ${key}: ${error instanceof Error ? error.message : String(error)}`, "warning");
|
|
184
|
+
} finally {
|
|
185
|
+
options.discovery.pending.delete(key);
|
|
186
|
+
if (!options.isClosed()) {
|
|
187
|
+
options.screen.updateDiscoveredItems(
|
|
188
|
+
buildConfigurationItems(options.discovery.modelCandidates, options.discovery.pythonModelCandidates, options.discovery.audioDevices, options.theme),
|
|
189
|
+
formatDiscoveryStatus(options.discovery.pending),
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function deferDiscovery<T>(load: () => T | Promise<T>): Promise<T> {
|
|
196
|
+
return new Promise((resolve, reject) => {
|
|
197
|
+
setImmediate(() => {
|
|
198
|
+
Promise.resolve()
|
|
199
|
+
.then(load)
|
|
200
|
+
.then(resolve, reject);
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function formatDiscoveryStatus(pending: Set<ConfigurationDiscoveryKey>) {
|
|
206
|
+
if (pending.size === 0) return "";
|
|
207
|
+
return `Loading ${[...pending].join(", ")}…`;
|
|
208
|
+
}
|
|
209
|
+
|
|
119
210
|
class ConfigurationScreen implements Component {
|
|
120
211
|
private readonly configPath: string;
|
|
121
|
-
private
|
|
212
|
+
private items: ConfigurationItem[];
|
|
122
213
|
private readonly theme: MicmeTheme;
|
|
123
214
|
private readonly onDone: () => void;
|
|
124
215
|
private readonly onError: (error: unknown) => void;
|
|
@@ -144,6 +235,7 @@ class ConfigurationScreen implements Component {
|
|
|
144
235
|
onError: (error: unknown) => void;
|
|
145
236
|
onSave: (id: string, newValue: string) => Promise<Record<string, string>>;
|
|
146
237
|
requestRender: () => void;
|
|
238
|
+
statusText?: string;
|
|
147
239
|
}) {
|
|
148
240
|
this.configPath = options.configPath;
|
|
149
241
|
this.items = options.items;
|
|
@@ -152,9 +244,20 @@ class ConfigurationScreen implements Component {
|
|
|
152
244
|
this.onError = options.onError;
|
|
153
245
|
this.onSave = options.onSave;
|
|
154
246
|
this.requestRender = options.requestRender;
|
|
247
|
+
this.statusText = options.statusText ?? "";
|
|
155
248
|
for (const category of CONFIGURATION_CATEGORIES) this.selectedByCategory.set(category.id, 0);
|
|
156
249
|
}
|
|
157
250
|
|
|
251
|
+
updateDiscoveredItems(items: ConfigurationItem[], statusText: string) {
|
|
252
|
+
this.items = items;
|
|
253
|
+
this.refreshDerivedItems();
|
|
254
|
+
this.clampSelections();
|
|
255
|
+
if (!this.saving && (!this.statusText || this.statusText.startsWith("Loading "))) {
|
|
256
|
+
this.statusText = statusText;
|
|
257
|
+
}
|
|
258
|
+
this.requestRender();
|
|
259
|
+
}
|
|
260
|
+
|
|
158
261
|
render(width: number): string[] {
|
|
159
262
|
this.refreshDerivedItems();
|
|
160
263
|
if (this.submenuComponent) return this.submenuComponent.render(width);
|
|
@@ -1091,6 +1194,7 @@ export function uniqueStrings(values: string[]) {
|
|
|
1091
1194
|
function getConfigurationValuesToWrite(id: string, value: string) {
|
|
1092
1195
|
if (id === "MICME_TRANSCRIPTION_MODE") return getTranscriptionModeProfile(value === "stream" ? "stream" : "clip");
|
|
1093
1196
|
if (id === "MICME_SHORTCUT") return { MICME_SHORTCUT: value, MICME_PRINTABLE_SHORTCUTS: undefined };
|
|
1197
|
+
if (id === "MICME_WHISPER_CPP_MODEL" && !value) return { MICME_WHISPER_CPP_MODEL: undefined };
|
|
1094
1198
|
return { [id]: value };
|
|
1095
1199
|
}
|
|
1096
1200
|
|
package/src/streaming.ts
CHANGED
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
} from "./config.ts";
|
|
16
16
|
import { pasteOrSubmitTranscript } from "./transcript-delivery.ts";
|
|
17
17
|
import { shellQuote } from "./processes.ts";
|
|
18
|
+
import { sanitizeTerminalText } from "./terminal-text.ts";
|
|
18
19
|
import type { CommandSpec, Recording, StreamingState } from "./types.ts";
|
|
19
20
|
|
|
20
21
|
export type StreamingFrameMode = "cumulative" | "incremental" | "rolling" | "duplicate" | "reset";
|
|
@@ -155,7 +156,7 @@ export function sanitizeStreamingText(text: string) {
|
|
|
155
156
|
}
|
|
156
157
|
|
|
157
158
|
export function stripStreamingControls(text: string) {
|
|
158
|
-
return text
|
|
159
|
+
return sanitizeTerminalText(text);
|
|
159
160
|
}
|
|
160
161
|
|
|
161
162
|
export function diffStreamingText(previous: string, current: string) {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function stripTerminalControlSequences(value: string) {
|
|
2
|
+
return value
|
|
3
|
+
.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, " ")
|
|
4
|
+
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, " ")
|
|
5
|
+
.replace(/\x1b[ -/]*[@-~]/g, " ")
|
|
6
|
+
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, " ");
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function sanitizeTerminalText(value: string) {
|
|
10
|
+
return stripTerminalControlSequences(value).replace(/\s+/g, " ").trim();
|
|
11
|
+
}
|