@senad-d/micme 0.3.0 → 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/CHANGELOG.md CHANGED
@@ -10,8 +10,10 @@ All notable changes to Micme will be documented in this file.
10
10
  - Add an interactive npm publishing script that prompts for a version, validates the package, creates the release commit/tag, and publishes with public scoped-package access.
11
11
  - Keep publication on hold until package name, metadata, security review, validation, and smoke tests are complete.
12
12
  - Add explicit transcription backend selection with backend-specific `/micme conf` model rows, doctor diagnostics, schema, and docs.
13
+ - Add a single `MICME_TRANSLATE_TO_ENGLISH` setting that translates selected source languages to English and switches default Whisper model names to multilingual variants.
13
14
  - Store kept audio in sequential project directories under `./micme-rec/rec-###/` instead of the system temp directory.
14
15
  - Make the recorder quality-safe by default: preserve recorder timing from ffmpeg timestamps, disable the stdout meter branch, and ask macOS AVFoundation not to drop late frames.
16
+ - Rename the translation UI to “Translate from” and automatically route translation away from non-translation Whisper turbo models to the closest translate-capable model.
15
17
 
16
18
  ## 0.1.0 - 2026-06-18
17
19
 
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
 
16
16
  ---
17
17
 
18
- MicMe is a pi extension for short coding prompts. It records your microphone with `ffmpeg`, transcribes locally with `whisper.cpp` or another local backend, and inserts the transcript into pi.
18
+ MicMe is a Pi extension for coding prompts. It records your microphone with `ffmpeg`, transcribes locally with `whisper.cpp` or another local backend, and inserts the transcript into pi.
19
19
 
20
20
  <table align="center">
21
21
  <tr>
@@ -147,7 +147,7 @@ MICME_WHISPER_CPP_MODEL=/path/to/ggml-small.en.bin
147
147
 
148
148
  ## Configuration
149
149
 
150
- Micme reads settings from shell environment variables and from the global Micme config file at `~/.pi/agent/micme.json`. Shell variables win. `/micme conf` writes only `MICME_*` keys to that JSON file, so settings follow you across pi projects on the same machine.
150
+ MicMe reads settings from shell environment variables and from the global Micme config file at `~/.pi/agent/micme.json`. Shell variables win. `/micme conf` writes only `MICME_*` keys to that JSON file, so settings follow you across pi projects on the same machine.
151
151
 
152
152
  The usual setup path is to run:
153
153
 
@@ -161,6 +161,7 @@ You can also edit the JSON manually. Minimal `~/.pi/agent/micme.json`:
161
161
  {
162
162
  "$schema": "https://raw.githubusercontent.com/senad-d/micme/main/micme.schema.json",
163
163
  "MICME_LANGUAGE": "en",
164
+ "MICME_TRANSLATE_TO_ENGLISH": "off",
164
165
  "MICME_TRANSCRIBE_BACKEND": "auto",
165
166
  "MICME_AUTO_DOWNLOAD_MODEL": "1",
166
167
  "MICME_DEFAULT_WHISPER_CPP_MODEL": "small.en",
@@ -178,6 +179,8 @@ Common settings:
178
179
  | `MICME_TRANSCRIBE_BACKEND=auto` | Backend selector. `auto` preserves priority: custom command, whisper.cpp, then Python Whisper. |
179
180
  | `MICME_TRANSCRIPTION_MODE=clip` | Stable default: transcribe after recording stops. |
180
181
  | `MICME_TRANSCRIPTION_MODE=stream` | Experimental append-only live dictation with `whisper-stream`; requires whisper.cpp. |
182
+ | `MICME_LANGUAGE=en` | Transcription language when translation is off. Use `auto` for detection. |
183
+ | `MICME_TRANSLATE_TO_ENGLISH=off` | “Translate from” option. Leave `off`, or set the spoken source language code such as `hr`, `bs`, `de`, or `tr` to output English. |
181
184
  | `MICME_STREAM_KEEP_CONTEXT=0` | Stream default: avoid Whisper prompt carry-over so live chunks are less likely to rewrite each other. |
182
185
  | `MICME_STREAM_FLUSH_MS=650` | Stream profile quiet interval before tentative words are committed append-only. |
183
186
  | `MICME_STREAM_FINALIZE_WITH_CLIP=0` | Keep the append-only live transcript on stop. Set `1` to opt in to final clip replacement. |
@@ -225,7 +228,7 @@ With `MICME_AUTO_DOWNLOAD_MODEL=1`, Micme downloads missing standard whisper.cpp
225
228
  MICME_AUTO_DOWNLOAD_MODEL=0
226
229
  ```
227
230
 
228
- Recommended model progression: `base.en` for speed, `small.en` for a stronger default, `medium.en` for accuracy.
231
+ Recommended model progression: `base.en` for speed, `small.en` for a stronger default, `medium.en` for accuracy. Translation uses Whisper's built-in translate task and needs translate-capable multilingual models; when `MICME_TRANSLATE_TO_ENGLISH` is enabled, Micme maps `.en` model names to multilingual defaults (`small.en` → `small`, `base.en` → `base`) and maps non-translation turbo models to the closest translate-capable model (`large-v3-turbo` → `large-v3`).
229
232
 
230
233
  Advanced users can replace the recorder or transcriber:
231
234
 
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.
@@ -5,6 +5,7 @@
5
5
  "MICME_TRANSCRIBE_BACKEND": "auto",
6
6
  "MICME_AUTO_SUBMIT": "0",
7
7
  "MICME_LANGUAGE": "en",
8
+ "MICME_TRANSLATE_TO_ENGLISH": "off",
8
9
  "MICME_TRANSCRIBE_TIMEOUT_MS": "120000",
9
10
  "MICME_AUTO_DOWNLOAD_MODEL": "1",
10
11
  "MICME_DEFAULT_WHISPER_CPP_MODEL": "small.en",
package/micme.schema.json CHANGED
@@ -34,7 +34,14 @@
34
34
  },
35
35
  "MICME_LANGUAGE": {
36
36
  "type": "string",
37
- "default": "en"
37
+ "default": "en",
38
+ "description": "Transcription language when translation is off. Use auto for language detection."
39
+ },
40
+ "MICME_TRANSLATE_TO_ENGLISH": {
41
+ "type": "string",
42
+ "enum": ["off", "bs", "hr", "sr", "de", "es", "fr", "it", "pt", "nl", "pl", "tr"],
43
+ "default": "off",
44
+ "description": "Translate from control. off disables translation; any language code means translate speech in that source language to English."
38
45
  },
39
46
  "MICME_AUTO_DOWNLOAD_MODEL": {
40
47
  "$ref": "#/$defs/stringFlag"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senad-d/micme",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "type": "module",
5
5
  "description": "Local voice dictation for Pi coding prompts. Press Alt+M, speak, review, send.",
6
6
  "license": "MIT",
@@ -102,16 +102,43 @@ function getTranscriptionMode() {
102
102
  return env("MICME_TRANSCRIPTION_MODE") === "stream" ? "stream" : "clip";
103
103
  }
104
104
 
105
+ function getTranslateToEnglishLanguage() {
106
+ const value = env("MICME_TRANSLATE_TO_ENGLISH")?.trim();
107
+ if (!value || /^(0|false|no|off)$/i.test(value)) return undefined;
108
+ return value;
109
+ }
110
+
111
+ function toMultilingualWhisperModelName(modelName) {
112
+ return modelName.replace(/\.en$/i, "");
113
+ }
114
+
115
+ function getTranslationAwareWhisperModelName(modelName) {
116
+ return getTranslateToEnglishLanguage() ? toMultilingualWhisperModelName(modelName) : modelName;
117
+ }
118
+
119
+ function isEnglishOnlyWhisperModelName(modelName) {
120
+ return Boolean(modelName && /\.en$/i.test(modelName));
121
+ }
122
+
123
+ function inferWhisperCppModelName(modelPath) {
124
+ return modelPath.match(/(?:^|[/\\])ggml-(.+)\.(?:bin|gguf)$/i)?.[1];
125
+ }
126
+
127
+ function getPythonWhisperModelName() {
128
+ return getTranslationAwareWhisperModelName(env("MICME_WHISPER_MODEL") || "base.en");
129
+ }
130
+
105
131
  function resolveWhisperCppModelSummary() {
106
132
  const explicit = envPath("MICME_WHISPER_CPP_MODEL");
107
133
  if (explicit) {
108
134
  return {
109
135
  path: explicit,
136
+ modelName: inferWhisperCppModelName(explicit),
110
137
  source: "MICME_WHISPER_CPP_MODEL explicit path",
111
138
  exists: existsSync(explicit),
112
139
  };
113
140
  }
114
- const defaultModel = env("MICME_DEFAULT_WHISPER_CPP_MODEL") || "small.en";
141
+ const defaultModel = getTranslationAwareWhisperModelName(env("MICME_DEFAULT_WHISPER_CPP_MODEL") || "small.en");
115
142
  const modelDir = expandConfigValue(env("MICME_MODEL_DIR") || join(homedir(), ".cache", "whisper.cpp"));
116
143
  const path = join(modelDir, `ggml-${defaultModel}.bin`);
117
144
  return {
@@ -156,13 +183,13 @@ function resolveBackendPlan({ whisperCpp, whisperStream, whisper, transcribeComm
156
183
  return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIBE_BACKEND=whisper.cpp but whisper.cpp was not found.", warnings };
157
184
  }
158
185
  if (requestedBackend === "python") {
159
- if (pythonAvailable) return { requestedBackend, effectiveBackend: "python", binary: whisper, effectiveModel: env("MICME_WHISPER_MODEL") || "base.en", reason: "MICME_TRANSCRIBE_BACKEND=python", warnings };
186
+ if (pythonAvailable) return { requestedBackend, effectiveBackend: "python", binary: whisper, effectiveModel: getPythonWhisperModelName(), reason: "MICME_TRANSCRIBE_BACKEND=python", warnings };
160
187
  return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIBE_BACKEND=python but the `whisper` CLI was not found.", warnings };
161
188
  }
162
189
 
163
190
  if (transcribeCommand?.trim()) return { requestedBackend, effectiveBackend: "custom", effectiveModel: "unknown", reason: "auto selected custom command because MICME_TRANSCRIBE_COMMAND is configured", warnings };
164
191
  if (whisperCppAvailable) return { requestedBackend, effectiveBackend: "whisper.cpp", binary: whisperCpp, model, effectiveModel: model.path, reason: "auto selected whisper.cpp because a whisper.cpp binary is available", warnings };
165
- if (pythonAvailable) return { requestedBackend, effectiveBackend: "python", binary: whisper, effectiveModel: env("MICME_WHISPER_MODEL") || "base.en", reason: "auto selected Python Whisper because whisper.cpp is unavailable", warnings };
192
+ if (pythonAvailable) return { requestedBackend, effectiveBackend: "python", binary: whisper, effectiveModel: getPythonWhisperModelName(), reason: "auto selected Python Whisper because whisper.cpp is unavailable", warnings };
166
193
  return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "No Micme transcription backend found.", warnings };
167
194
  }
168
195
 
@@ -178,6 +205,16 @@ function printBackendPlanDiagnostics(plan) {
178
205
  } else if (plan.effectiveBackend === "python") info("effective model", plan.effectiveModel);
179
206
  else info("effective model", "unavailable");
180
207
 
208
+ const translateLanguage = getTranslateToEnglishLanguage();
209
+ if (translateLanguage) {
210
+ ok("translation", `${translateLanguage} -> English`);
211
+ if (plan.effectiveBackend === "custom") warn("translation backend", "custom transcribe commands must implement translation themselves");
212
+ if (plan.effectiveBackend === "whisper.cpp" && isEnglishOnlyWhisperModelName(plan.model?.modelName)) warn("translation model", `${plan.model.modelName} appears to be English-only; use a multilingual model`);
213
+ if (plan.effectiveBackend === "python" && isEnglishOnlyWhisperModelName(plan.effectiveModel)) warn("translation model", `${plan.effectiveModel} appears to be English-only; use a multilingual model`);
214
+ } else {
215
+ info("translation", "off");
216
+ }
217
+
181
218
  for (const warning of plan.warnings) warn("backend warning", warning);
182
219
  }
183
220
 
@@ -229,7 +266,7 @@ async function main() {
229
266
  warn("MICME_WHISPER_CPP_MODEL is set but not readable", auto ? `${whisperCppModel} (Micme will try to download if it is a standard ggml model path)` : whisperCppModel);
230
267
  }
231
268
  } else {
232
- const defaultModel = env("MICME_DEFAULT_WHISPER_CPP_MODEL") || "small.en";
269
+ const defaultModel = getTranslationAwareWhisperModelName(env("MICME_DEFAULT_WHISPER_CPP_MODEL") || "small.en");
233
270
  const modelDir = expandConfigValue(env("MICME_MODEL_DIR") || join(homedir(), ".cache", "whisper.cpp"));
234
271
  info("MICME_WHISPER_CPP_MODEL", `not set; Micme defaults to ${modelDir}/ggml-${defaultModel}.bin and auto-downloads when needed`);
235
272
  }
@@ -250,7 +287,7 @@ async function main() {
250
287
 
251
288
  console.log("\nRecommended macOS setup:");
252
289
  console.log(" brew install ffmpeg whisper-cpp");
253
- console.log(" # Then use /micme conf, or let Micme auto-download ggml-small.en.bin on first use.");
290
+ console.log(" # Then use /micme conf, or let Micme auto-download the default model on first use.");
254
291
 
255
292
  if (process.platform === "darwin" && ffmpeg) {
256
293
  console.log("\nmacOS microphone devices:");
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] ?? "").trim();
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] ?? "").trim();
255
+ const id = sanitizeDeviceField(match[1] ?? "");
255
256
  if (!id || id.includes(":")) continue;
256
- let name = (match[2] ?? "").trim();
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] ?? "").trim();
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
@@ -1,9 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import type { TranscribeBackend, TranscriptionMode, ResolvedTranscriptionPlan, ResolvedWhisperCppModel } from "./types.ts";
3
3
  import { DEFAULT_TRANSCRIBE_BACKEND } from "./constants.ts";
4
- import { env, expandConfigPath, getTranscribeBackend, isTranscribeBackend } from "./config.ts";
5
- import { getPythonWhisperModelName, resolveWhisperCppModel } from "./models.ts";
6
- import { findExecutable } from "./processes.ts";
4
+ import { env, expandConfigPath, getTranscribeBackend, getTranslateToEnglishLanguage, isTranscribeBackend } from "./config.ts";
5
+ import { getPythonWhisperModelName, isEnglishOnlyWhisperModelName, isTranslationUnsupportedWhisperModelName, resolveWhisperCppModel } from "./models.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]);
@@ -174,6 +175,10 @@ function whisperCppPlan(requestedBackend: TranscribeBackend, binary: string, mod
174
175
  } else if (!model.exists && !model.downloadable) {
175
176
  warnings.push(`Whisper.cpp model is missing and is not a standard downloadable model: ${model.path}`);
176
177
  }
178
+ if (model.translationFallbackFrom && model.modelName) {
179
+ warnings.push(`Translation to English uses ${model.modelName} instead of ${model.translationFallbackFrom} because the selected model does not support translation.`);
180
+ }
181
+ warnings.push(...getTranslationModelWarnings(model.modelName));
177
182
  return {
178
183
  requestedBackend,
179
184
  effectiveBackend: "whisper.cpp",
@@ -195,10 +200,17 @@ function pythonPlan(requestedBackend: TranscribeBackend, binary: string, modelNa
195
200
  binary,
196
201
  modelName,
197
202
  modelSource: "python-name",
198
- warnings: [],
203
+ warnings: getTranslationModelWarnings(modelName),
199
204
  };
200
205
  }
201
206
 
207
+ function getTranslationModelWarnings(modelName: string | undefined) {
208
+ if (!getTranslateToEnglishLanguage()) return [];
209
+ if (isEnglishOnlyWhisperModelName(modelName)) return [`Translation to English requires a multilingual Whisper model; ${modelName} appears to be English-only.`];
210
+ if (isTranslationUnsupportedWhisperModelName(modelName)) return [`Translation to English is not supported by ${modelName}; choose large-v3 or another multilingual translate-capable model.`];
211
+ return [];
212
+ }
213
+
202
214
  function nonePlan(requestedBackend: TranscribeBackend, reason: string, warnings: string[]): ResolvedTranscriptionPlan {
203
215
  return {
204
216
  requestedBackend,
package/src/config.ts CHANGED
@@ -175,6 +175,12 @@ export function getTranscriptionMode() {
175
175
  return env("MICME_TRANSCRIPTION_MODE") === "stream" ? "stream" : "clip";
176
176
  }
177
177
 
178
+ export function getTranslateToEnglishLanguage() {
179
+ const value = env("MICME_TRANSLATE_TO_ENGLISH")?.trim();
180
+ if (!value || /^(0|false|no|off)$/i.test(value)) return undefined;
181
+ return value;
182
+ }
183
+
178
184
  export function getTranscribeBackend(): TranscribeBackend {
179
185
  const value = env("MICME_TRANSCRIBE_BACKEND")?.trim();
180
186
  return isTranscribeBackend(value) ? value : DEFAULT_TRANSCRIBE_BACKEND;
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
- const audioPath = join(tempDir, "raw.wav");
177
- const command = buildRecorderCommand(audioPath);
178
- const active = spawnRecording(command, audioPath, tempDir);
179
- recording = active;
180
-
181
- const earlyExit = await raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS);
182
- if (earlyExit) {
183
- if (active.stopRequested) return;
184
- recording = undefined;
185
- clearRecordingWidget(ctx);
186
- await cleanup(tempDir).catch(() => undefined);
187
- const stderr = active.stderr().trim();
188
- const suffix = stderr ? `\n${stderr}` : "";
189
- throw new Error(`Micme recorder exited early (${formatExit(earlyExit)}).${suffix}`);
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
- ctx.ui.setStatus(STATUS_KEY, `● recording (${stopHint} or /micme)`);
193
- startRecordingWidget(ctx, active);
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
- const command = buildWhisperStreamCommand(plan.binary, plan.modelPath, tempDir);
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
- active.process.stdout?.on("data", (chunk: Buffer | string) => {
274
- const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
275
- handleStreamingOutput(ctx, active, text);
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
- const [earlyExit, recorderEarlyExit] = await Promise.all([
279
- raceWithTimeout(active.exitPromise, RECORDER_STARTUP_GRACE_MS),
280
- active.clipRecording ? raceWithTimeout(active.clipRecording.exitPromise, RECORDER_STARTUP_GRACE_MS) : Promise.resolve(undefined),
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
- ctx.ui.setStatus(STATUS_KEY, `● streaming (${stopHint} or /micme)`);
296
- startRecordingWidget(ctx, active);
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
@@ -3,7 +3,7 @@ import { once } from "node:events";
3
3
  import { createWriteStream, existsSync, readdirSync, statSync } from "node:fs";
4
4
  import { mkdir, rename, unlink } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
6
- import { basename, dirname, join } from "node:path";
6
+ import { basename, dirname, extname, join } from "node:path";
7
7
  import { finished } from "node:stream/promises";
8
8
  import {
9
9
  DEFAULT_PYTHON_WHISPER_MODEL_NAME,
@@ -13,11 +13,12 @@ import {
13
13
  WHISPER_CPP_MODEL_BASE_URL,
14
14
  WHISPER_CPP_MODEL_NAMES,
15
15
  } from "./constants.ts";
16
- import { env, expandConfigPath } from "./config.ts";
16
+ import { env, expandConfigPath, getTranslateToEnglishLanguage } from "./config.ts";
17
17
  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[] = [];
@@ -118,33 +119,90 @@ export function describeWhisperModel(name: string) {
118
119
 
119
120
  export function resolveWhisperCppModel(): ResolvedWhisperCppModel {
120
121
  const explicitPath = env("MICME_WHISPER_CPP_MODEL")?.trim();
121
- if (explicitPath) {
122
- const path = expandConfigPath(explicitPath);
123
- return {
124
- path,
125
- modelName: getWhisperCppModelNameFromPath(path),
126
- source: "explicit-path",
127
- configuredValue: explicitPath,
128
- exists: existsSync(path),
129
- downloadable: isDownloadableWhisperCppModelPath(path),
130
- };
131
- }
122
+ if (explicitPath) return resolveExplicitWhisperCppModel(expandConfigPath(explicitPath), explicitPath);
132
123
 
133
124
  const configuredName = env("MICME_DEFAULT_WHISPER_CPP_MODEL")?.trim();
134
- const modelName = configuredName || DEFAULT_WHISPER_CPP_MODEL_NAME;
125
+ const rawModelName = configuredName || DEFAULT_WHISPER_CPP_MODEL_NAME;
126
+ const modelName = getTranslationAwareWhisperModelName(rawModelName);
135
127
  const path = join(getWhisperCppModelCacheDir(), `ggml-${modelName}.bin`);
136
- return {
137
- path,
128
+ return buildResolvedWhisperCppModel(path, {
138
129
  modelName,
139
130
  source: configuredName ? "configured-name" : "default-name",
140
131
  configuredValue: configuredName,
132
+ translationFallbackFrom: getTranslationFallbackSource(rawModelName, modelName),
133
+ });
134
+ }
135
+
136
+ function resolveExplicitWhisperCppModel(path: string, configuredValue: string): ResolvedWhisperCppModel {
137
+ const modelName = getWhisperCppModelNameFromPath(path);
138
+ const translationModelName = modelName ? getTranslationAwareWhisperModelName(modelName) : undefined;
139
+ if (modelName && translationModelName && translationModelName !== modelName) {
140
+ const fallbackPath = getSiblingWhisperCppModelPath(path, translationModelName);
141
+ return buildResolvedWhisperCppModel(fallbackPath, {
142
+ modelName: translationModelName,
143
+ source: "explicit-path",
144
+ configuredValue,
145
+ translationFallbackFrom: modelName,
146
+ });
147
+ }
148
+
149
+ return buildResolvedWhisperCppModel(path, {
150
+ modelName,
151
+ source: "explicit-path",
152
+ configuredValue,
153
+ });
154
+ }
155
+
156
+ function buildResolvedWhisperCppModel(
157
+ path: string,
158
+ metadata: Pick<ResolvedWhisperCppModel, "source"> & Pick<Partial<ResolvedWhisperCppModel>, "modelName" | "configuredValue" | "translationFallbackFrom">,
159
+ ): ResolvedWhisperCppModel {
160
+ return {
161
+ path,
162
+ modelName: metadata.modelName,
163
+ source: metadata.source,
164
+ configuredValue: metadata.configuredValue,
141
165
  exists: existsSync(path),
142
166
  downloadable: isDownloadableWhisperCppModelPath(path),
167
+ translationFallbackFrom: metadata.translationFallbackFrom,
143
168
  };
144
169
  }
145
170
 
171
+ function getSiblingWhisperCppModelPath(modelPath: string, modelName: string) {
172
+ const extension = extname(modelPath) || ".bin";
173
+ return join(dirname(modelPath), `ggml-${modelName}${extension}`);
174
+ }
175
+
176
+ function getTranslationFallbackSource(rawModelName: string, modelName: string) {
177
+ return rawModelName !== modelName ? rawModelName : undefined;
178
+ }
179
+
146
180
  export function getPythonWhisperModelName() {
147
- return env("MICME_WHISPER_MODEL")?.trim() || DEFAULT_PYTHON_WHISPER_MODEL_NAME;
181
+ const modelName = env("MICME_WHISPER_MODEL")?.trim() || DEFAULT_PYTHON_WHISPER_MODEL_NAME;
182
+ return getTranslationAwareWhisperModelName(modelName);
183
+ }
184
+
185
+ export function getTranslationAwareWhisperModelName(modelName: string) {
186
+ return getTranslateToEnglishLanguage() ? toTranslationCapableWhisperModelName(modelName) : modelName;
187
+ }
188
+
189
+ export function toTranslationCapableWhisperModelName(modelName: string) {
190
+ const multilingualName = toMultilingualWhisperModelName(modelName);
191
+ return isTranslationUnsupportedWhisperModelName(multilingualName) ? "large-v3" : multilingualName;
192
+ }
193
+
194
+ export function toMultilingualWhisperModelName(modelName: string) {
195
+ return modelName.replace(/\.en$/i, "");
196
+ }
197
+
198
+ export function isEnglishOnlyWhisperModelName(modelName: string | undefined) {
199
+ return Boolean(modelName && /\.en$/i.test(modelName));
200
+ }
201
+
202
+ export function isTranslationUnsupportedWhisperModelName(modelName: string | undefined) {
203
+ if (!modelName) return false;
204
+ const normalized = modelName.toLowerCase();
205
+ return normalized === "turbo" || normalized === "large-v3-turbo" || normalized.startsWith("large-v3-turbo-");
148
206
  }
149
207
 
150
208
  export async function discoverPythonWhisperModels(): Promise<ModelCandidate[]> {
@@ -165,7 +223,7 @@ export async function queryPythonWhisperModelNames(): Promise<string[]> {
165
223
  if (!python) return [];
166
224
 
167
225
  try {
168
- const result = await runProcess(python, ["-c", "import whisper; print('\\n'.join(whisper.available_models()))"], 2_000);
226
+ const result = await runProcess(python, getPythonWhisperModelQueryArgs(), 2_000);
169
227
  if (result.code !== 0 || result.timedOut) return [];
170
228
  return uniqueModelNames(result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
171
229
  } catch {
@@ -173,6 +231,11 @@ export async function queryPythonWhisperModelNames(): Promise<string[]> {
173
231
  }
174
232
  }
175
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
+
176
239
  export function uniqueModelNames(names: string[]) {
177
240
  const seen = new Set<string>();
178
241
  const output: string[] = [];
@@ -304,7 +367,8 @@ export function getWhisperCppModelCacheDir() {
304
367
  }
305
368
 
306
369
  export function getDefaultWhisperCppModelPath() {
307
- const modelName = env("MICME_DEFAULT_WHISPER_CPP_MODEL")?.trim() || DEFAULT_WHISPER_CPP_MODEL_NAME;
370
+ const rawModelName = env("MICME_DEFAULT_WHISPER_CPP_MODEL")?.trim() || DEFAULT_WHISPER_CPP_MODEL_NAME;
371
+ const modelName = getTranslationAwareWhisperModelName(rawModelName);
308
372
  return join(getWhisperCppModelCacheDir(), `ggml-${modelName}.bin`);
309
373
  }
310
374
 
package/src/processes.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
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
- let output = template;
167
- for (const [key, value] of Object.entries(values)) {
168
- output = output.replaceAll(`{${key}}`, shellQuote(value));
169
- output = output.replaceAll(`{${key}Raw}`, value);
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 (existsSync(candidate)) return candidate;
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;
@@ -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
@@ -32,7 +32,7 @@ import {
32
32
  } from "./config.ts";
33
33
  import { discoverAudioDevices } from "./audio.ts";
34
34
  import { formatBackendLabel, resolveTranscriptionPlan } from "./backends.ts";
35
- import { discoverPythonWhisperModels, discoverWhisperCppModels, ensureWhisperCppModel, resolveWhisperCppModel } from "./models.ts";
35
+ import { discoverPythonWhisperModels, discoverWhisperCppModels, ensureWhisperCppModel, getPythonWhisperModelName, resolveWhisperCppModel } from "./models.ts";
36
36
  import { findExecutable } from "./processes.ts";
37
37
  import type { AudioDeviceCandidate, ModelCandidate, ResolvedTranscriptionPlan } from "./types.ts";
38
38
 
@@ -66,6 +66,36 @@ const CONFIGURATION_CATEGORIES: ConfigurationCategory[] = [
66
66
 
67
67
  const TWO_PANE_MIN_WIDTH = 72;
68
68
  const MAX_SETTINGS_ROWS = 10;
69
+ const LANGUAGE_LABELS: Record<string, string> = {
70
+ auto: "Auto detect",
71
+ en: "English",
72
+ bs: "Bosnian",
73
+ hr: "Croatian",
74
+ sr: "Serbian",
75
+ de: "German",
76
+ es: "Spanish",
77
+ fr: "French",
78
+ it: "Italian",
79
+ pt: "Portuguese",
80
+ nl: "Dutch",
81
+ pl: "Polish",
82
+ tr: "Turkish",
83
+ };
84
+ const TRANSCRIPTION_LANGUAGE_VALUES = ["en", "auto", "bs", "hr", "sr", "de", "es", "fr", "it", "pt", "nl", "pl", "tr"];
85
+ const TRANSLATION_SOURCE_LANGUAGE_VALUES = ["bs", "hr", "sr", "de", "es", "fr", "it", "pt", "nl", "pl", "tr"];
86
+ const TRANSLATE_FROM_VALUE_LABELS: Record<string, string> = {
87
+ off: "Off",
88
+ ...Object.fromEntries(TRANSLATION_SOURCE_LANGUAGE_VALUES.map((language) => [language, `${LANGUAGE_LABELS[language] ?? language} → English`])),
89
+ };
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
+ };
69
99
 
70
100
  export async function showConfiguration(ctx: ExtensionContext) {
71
101
  if (ctx.mode !== "tui") {
@@ -77,27 +107,109 @@ export async function showConfiguration(ctx: ExtensionContext) {
77
107
  if (configState.error) {
78
108
  ctx.ui.notify(`Micme config is invalid at ${configState.path}: ${configState.error}. Fix it before saving settings.`, "warning");
79
109
  }
80
- const audioDevices = await discoverAudioDevices();
81
- const modelCandidates = discoverWhisperCppModels(ctx.cwd);
82
- const pythonModelCandidates = await discoverPythonWhisperModels();
83
-
84
110
  await ctx.ui.custom<void>((tui, theme, _keybindings, done) => {
85
- const items = buildConfigurationItems(modelCandidates, pythonModelCandidates, audioDevices, theme);
86
- return new ConfigurationScreen({
111
+ const discovery = createInitialConfigurationDiscovery();
112
+ let closed = false;
113
+ const screen = new ConfigurationScreen({
87
114
  configPath: configState.path,
88
- items,
115
+ items: buildConfigurationItems(discovery.modelCandidates, discovery.pythonModelCandidates, discovery.audioDevices, theme),
89
116
  theme,
90
- onDone: done,
117
+ onDone: () => {
118
+ closed = true;
119
+ done();
120
+ },
91
121
  onError: (error) => ctx.ui.notify(error instanceof Error ? error.message : String(error), "error"),
92
122
  onSave: (id, newValue) => saveConfigurationValue(ctx, id, newValue),
93
123
  requestRender: () => tui.requestRender(),
124
+ statusText: formatDiscoveryStatus(discovery.pending),
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;
165
+ });
166
+ }
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);
94
201
  });
95
202
  });
96
203
  }
97
204
 
205
+ function formatDiscoveryStatus(pending: Set<ConfigurationDiscoveryKey>) {
206
+ if (pending.size === 0) return "";
207
+ return `Loading ${[...pending].join(", ")}…`;
208
+ }
209
+
98
210
  class ConfigurationScreen implements Component {
99
211
  private readonly configPath: string;
100
- private readonly items: ConfigurationItem[];
212
+ private items: ConfigurationItem[];
101
213
  private readonly theme: MicmeTheme;
102
214
  private readonly onDone: () => void;
103
215
  private readonly onError: (error: unknown) => void;
@@ -123,6 +235,7 @@ class ConfigurationScreen implements Component {
123
235
  onError: (error: unknown) => void;
124
236
  onSave: (id: string, newValue: string) => Promise<Record<string, string>>;
125
237
  requestRender: () => void;
238
+ statusText?: string;
126
239
  }) {
127
240
  this.configPath = options.configPath;
128
241
  this.items = options.items;
@@ -131,9 +244,20 @@ class ConfigurationScreen implements Component {
131
244
  this.onError = options.onError;
132
245
  this.onSave = options.onSave;
133
246
  this.requestRender = options.requestRender;
247
+ this.statusText = options.statusText ?? "";
134
248
  for (const category of CONFIGURATION_CATEGORIES) this.selectedByCategory.set(category.id, 0);
135
249
  }
136
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
+
137
261
  render(width: number): string[] {
138
262
  this.refreshDerivedItems();
139
263
  if (this.submenuComponent) return this.submenuComponent.render(width);
@@ -587,6 +711,12 @@ class ConfigurationScreen implements Component {
587
711
  model.currentValue = displayConfigurationValue(model.id, model.rawValue);
588
712
  }
589
713
 
714
+ const pythonModel = this.items.find((candidate) => candidate.id === "MICME_WHISPER_MODEL");
715
+ if (pythonModel) {
716
+ pythonModel.rawValue = getPythonWhisperModelName();
717
+ pythonModel.currentValue = pythonModel.rawValue;
718
+ }
719
+
590
720
  const mode = this.items.find((candidate) => candidate.id === "MICME_TRANSCRIPTION_MODE");
591
721
  if (mode) {
592
722
  const base = "Changing this applies the matching profile: stable clip defaults or low-latency stream settings.";
@@ -666,13 +796,15 @@ export function buildConfigurationItems(
666
796
  const whisperStreamBinValues = uniqueStrings([env("MICME_WHISPER_STREAM_BIN") ?? "", findExecutable(["whisper-stream"]) ?? "", "whisper-stream"]);
667
797
  const audioFilter = env("MICME_AUDIO_FILTER") ?? "highpass=f=80,lowpass=f=7600";
668
798
  const shortcut = getShortcutSettingValue();
799
+ const translateToEnglish = env("MICME_TRANSLATE_TO_ENGLISH") ?? "off";
669
800
  const plan = resolveTranscriptionPlan({ transcriptionMode: getTranscriptionMode() });
670
801
  const backendValues = ["whisper.cpp", "python"] as const;
671
802
  const backendLabels = Object.fromEntries(backendValues.map((value) => [value, formatBackendLabel(value)]));
672
803
  const uiBackendValue = getUiBackendValue(plan);
673
804
  const whisperCppVisible = (candidate: ResolvedTranscriptionPlan) => getUiBackendValue(candidate) === "whisper.cpp";
674
805
  const pythonVisible = (candidate: ResolvedTranscriptionPlan) => getUiBackendValue(candidate) === "python";
675
- const pythonModelValues = uniqueStrings([env("MICME_WHISPER_MODEL") ?? "base.en", ...pythonModelCandidates.map((candidate) => candidate.value)]);
806
+ const currentPythonModel = getPythonWhisperModelName();
807
+ const pythonModelValues = uniqueStrings([currentPythonModel, env("MICME_WHISPER_MODEL") ?? "", ...pythonModelCandidates.map((candidate) => candidate.value)]);
676
808
  const pythonModelLabels = Object.fromEntries(pythonModelCandidates.map((candidate) => [candidate.value, candidate.label]));
677
809
  const modelPathCandidates = [{ label: "Use default model", value: "", description: "Clear explicit path override and use Micme's default whisper.cpp model path.", installed: true, kind: "path" as const }, ...modelCandidates];
678
810
 
@@ -691,10 +823,22 @@ export function buildConfigurationItems(
691
823
  id: "MICME_LANGUAGE",
692
824
  categoryId: "general",
693
825
  label: "Language",
694
- description: "Use a fixed language for accuracy/speed, or auto for detection.",
826
+ description: "Transcription language when translation is off. Use auto for detection.",
695
827
  rawValue: env("MICME_LANGUAGE") ?? "en",
696
828
  currentValue: env("MICME_LANGUAGE") ?? "en",
697
- values: ["en", "auto", "bs", "hr", "sr", "de", "es", "fr", "it", "pt", "nl", "pl", "tr"],
829
+ values: [...TRANSCRIPTION_LANGUAGE_VALUES],
830
+ valueLabels: LANGUAGE_LABELS,
831
+ displayKind: "text",
832
+ },
833
+ {
834
+ id: "MICME_TRANSLATE_TO_ENGLISH",
835
+ categoryId: "general",
836
+ label: "Translate from",
837
+ description: "Off by default. Choose the spoken source language to output English.",
838
+ rawValue: translateToEnglish,
839
+ currentValue: translateToEnglish,
840
+ values: ["off", ...TRANSLATION_SOURCE_LANGUAGE_VALUES],
841
+ valueLabels: TRANSLATE_FROM_VALUE_LABELS,
698
842
  displayKind: "text",
699
843
  },
700
844
  {
@@ -747,8 +891,8 @@ export function buildConfigurationItems(
747
891
  categoryId: "transcription",
748
892
  label: "Model",
749
893
  description: "Model name passed to the OpenAI Whisper Python CLI.",
750
- rawValue: env("MICME_WHISPER_MODEL") ?? "base.en",
751
- currentValue: env("MICME_WHISPER_MODEL") ?? "base.en",
894
+ rawValue: currentPythonModel,
895
+ currentValue: currentPythonModel,
752
896
  values: pythonModelValues,
753
897
  valueLabels: pythonModelLabels,
754
898
  displayKind: "text",
@@ -1032,8 +1176,7 @@ function getUiBackendValue(plan: ResolvedTranscriptionPlan): "whisper.cpp" | "py
1032
1176
  }
1033
1177
 
1034
1178
  function getCurrentWhisperCppModelValue() {
1035
- const explicit = env("MICME_WHISPER_CPP_MODEL")?.trim();
1036
- return explicit ? expandConfigPath(explicit) : resolveWhisperCppModel().path;
1179
+ return resolveWhisperCppModel().path;
1037
1180
  }
1038
1181
 
1039
1182
  export function uniqueStrings(values: string[]) {
@@ -1051,6 +1194,7 @@ export function uniqueStrings(values: string[]) {
1051
1194
  function getConfigurationValuesToWrite(id: string, value: string) {
1052
1195
  if (id === "MICME_TRANSCRIPTION_MODE") return getTranscriptionModeProfile(value === "stream" ? "stream" : "clip");
1053
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 };
1054
1198
  return { [id]: value };
1055
1199
  }
1056
1200
 
package/src/streaming.ts CHANGED
@@ -3,6 +3,7 @@ import { MAX_CAPTURED_OUTPUT_CHARS } from "./constants.ts";
3
3
  import {
4
4
  env,
5
5
  envFlag,
6
+ getTranslateToEnglishLanguage,
6
7
  getStreamFlushMs,
7
8
  getStreamKeepContext,
8
9
  getStreamKeepMs,
@@ -14,6 +15,7 @@ import {
14
15
  } from "./config.ts";
15
16
  import { pasteOrSubmitTranscript } from "./transcript-delivery.ts";
16
17
  import { shellQuote } from "./processes.ts";
18
+ import { sanitizeTerminalText } from "./terminal-text.ts";
17
19
  import type { CommandSpec, Recording, StreamingState } from "./types.ts";
18
20
 
19
21
  export type StreamingFrameMode = "cumulative" | "incremental" | "rolling" | "duplicate" | "reset";
@@ -54,8 +56,13 @@ export function buildWhisperStreamCommand(binary: string, modelPath: string, tem
54
56
  const capture = env("MICME_STREAM_CAPTURE");
55
57
  if (capture?.trim()) args.push("--capture", capture.trim());
56
58
 
57
- const language = env("MICME_LANGUAGE");
58
- if (language?.trim()) args.push("-l", language.trim());
59
+ const translateLanguage = getTranslateToEnglishLanguage();
60
+ if (translateLanguage) {
61
+ args.push("-tr", "-l", translateLanguage);
62
+ } else {
63
+ const language = env("MICME_LANGUAGE");
64
+ if (language?.trim()) args.push("-l", language.trim());
65
+ }
59
66
 
60
67
  return { command: binary, args, display: `${binary} ${args.map(shellQuote).join(" ")}` };
61
68
  }
@@ -149,7 +156,7 @@ export function sanitizeStreamingText(text: string) {
149
156
  }
150
157
 
151
158
  export function stripStreamingControls(text: string) {
152
- return text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, " ").replace(/\s+/g, " ").trim();
159
+ return sanitizeTerminalText(text);
153
160
  }
154
161
 
155
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
+ }
@@ -3,8 +3,8 @@ import { existsSync } from "node:fs";
3
3
  import { readFile } from "node:fs/promises";
4
4
  import { basename, join } from "node:path";
5
5
  import { resolveTranscriptionPlan, formatTranscriptionPlan } from "./backends.ts";
6
- import { env, getTranscribeTimeoutMs } from "./config.ts";
7
- import { ensureWhisperCppModel } from "./models.ts";
6
+ import { env, getTranscribeTimeoutMs, getTranslateToEnglishLanguage } from "./config.ts";
7
+ import { ensureWhisperCppModel, getPythonWhisperModelName } from "./models.ts";
8
8
  import { formatRunExit, replacePlaceholders, runProcess, runShell } from "./processes.ts";
9
9
 
10
10
  export { getWhisperCppBinary, getWhisperStreamBinary, resolveExecutableConfig } from "./backends.ts";
@@ -56,8 +56,13 @@ export async function transcribeWithWhisperCpp(
56
56
  await ensureWhisperCppModel(modelPath, ctx, options);
57
57
  const outputBase = join(tempDir, "whisper-cpp");
58
58
  const args = ["-m", modelPath, "-f", audioPath, "-otxt", "-of", outputBase, "-nt", "-np", "-nf", "-sns"];
59
- const language = env("MICME_LANGUAGE");
60
- if (language?.trim()) args.push("-l", language.trim());
59
+ const translateLanguage = getTranslateToEnglishLanguage();
60
+ if (translateLanguage) {
61
+ args.push("-tr", "-l", translateLanguage);
62
+ } else {
63
+ const language = env("MICME_LANGUAGE");
64
+ if (language?.trim()) args.push("-l", language.trim());
65
+ }
61
66
 
62
67
  const result = await runProcess(binary, args, getTranscribeTimeoutMs());
63
68
  if (result.code !== 0) {
@@ -74,7 +79,7 @@ export async function transcribeWithWhisperCpp(
74
79
  }
75
80
 
76
81
  export async function transcribeWithOpenAiWhisper(binary: string, audioPath: string, tempDir: string, modelName?: string) {
77
- const model = modelName || env("MICME_WHISPER_MODEL") || "base.en";
82
+ const model = modelName || getPythonWhisperModelName();
78
83
  const args = [
79
84
  audioPath,
80
85
  "--model",
@@ -89,8 +94,13 @@ export async function transcribeWithOpenAiWhisper(binary: string, audioPath: str
89
94
  "False",
90
95
  ];
91
96
 
92
- const language = env("MICME_LANGUAGE");
93
- if (language?.trim() && language.trim().toLowerCase() !== "auto") args.push("--language", language.trim());
97
+ const translateLanguage = getTranslateToEnglishLanguage();
98
+ if (translateLanguage) {
99
+ args.push("--task", "translate", "--language", translateLanguage);
100
+ } else {
101
+ const language = env("MICME_LANGUAGE");
102
+ if (language?.trim() && language.trim().toLowerCase() !== "auto") args.push("--language", language.trim());
103
+ }
94
104
 
95
105
  const device = env("MICME_WHISPER_DEVICE");
96
106
  if (device?.trim()) args.push("--device", device.trim());
package/src/types.ts CHANGED
@@ -13,6 +13,7 @@ export type ResolvedWhisperCppModel = {
13
13
  configuredValue?: string;
14
14
  exists: boolean;
15
15
  downloadable: boolean;
16
+ translationFallbackFrom?: string;
16
17
  };
17
18
 
18
19
  export type ResolvedTranscriptionPlan = {