@senad-d/micme 0.3.5 → 0.3.7
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 +1 -0
- package/README.md +20 -5
- package/micme.example.json +7 -7
- package/micme.schema.json +117 -9
- package/package.json +8 -7
- package/scripts/doctor.mjs +57 -258
- package/src/audio.ts +59 -23
- package/src/config.ts +216 -52
- package/src/constants.ts +25 -0
- package/src/editor.ts +117 -66
- package/src/extension.ts +411 -188
- package/src/models.ts +208 -51
- package/src/processes.ts +104 -28
- package/src/settings.ts +53 -35
- package/src/streaming.ts +2 -2
- package/src/transcription.ts +10 -10
- package/src/types.ts +9 -1
- package/tsconfig.json +1 -1
package/scripts/doctor.mjs
CHANGED
|
@@ -1,117 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { accessSync, constants as fsConstants, existsSync, readFileSync, statSync } from "node:fs";
|
|
3
|
-
import { access } from "node:fs/promises";
|
|
4
|
-
import { delimiter, join, resolve } from "node:path";
|
|
5
|
-
import { homedir } from "node:os";
|
|
6
2
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { getPythonWhisperBinary, getWhisperCppBinary, getWhisperStreamBinary, resolveTranscriptionPlan } from "../src/backends.ts";
|
|
5
|
+
import { env, getAutoDownloadModel, getTranscriptionMode, getTranslateToEnglishLanguage, reloadMicmeConfig } from "../src/config.ts";
|
|
6
|
+
import { resolveWhisperCppModel } from "../src/models.ts";
|
|
7
|
+
import { findExecutable } from "../src/processes.ts";
|
|
8
|
+
import { sanitizeTerminalOutput } from "../src/terminal-text.ts";
|
|
7
9
|
|
|
8
|
-
const
|
|
9
|
-
const micmeConfig = loadMicmeConfig();
|
|
10
|
-
const DEFAULT_TRANSCRIBE_BACKEND = "auto";
|
|
11
|
-
|
|
12
|
-
function stripTerminalControlSequences(value) {
|
|
13
|
-
return String(value)
|
|
14
|
-
.replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, " ")
|
|
15
|
-
.replace(/\x1b[PX^_][\s\S]*?(?:\x07|\x1b\\)/g, " ")
|
|
16
|
-
.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, " ")
|
|
17
|
-
.replace(/\x1b[ -/]*[@-~]/g, " ")
|
|
18
|
-
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, " ");
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
function sanitizeTerminalOutput(value) {
|
|
22
|
-
return stripTerminalControlSequences(value)
|
|
23
|
-
.replace(/\r\n/g, "\n")
|
|
24
|
-
.replace(/\r/g, "\n")
|
|
25
|
-
.split("\n")
|
|
26
|
-
.map((line) => line.trimEnd())
|
|
27
|
-
.join("\n")
|
|
28
|
-
.trim();
|
|
29
|
-
}
|
|
30
|
-
const TRANSCRIBE_BACKENDS = new Set(["auto", "whisper.cpp", "python", "custom"]);
|
|
31
|
-
|
|
32
|
-
function getMicmeConfigPath() {
|
|
33
|
-
const agentDir = process.env.PI_CODING_AGENT_DIR ? resolve(process.env.PI_CODING_AGENT_DIR) : join(homedir(), ".pi", "agent");
|
|
34
|
-
return join(agentDir, "micme.json");
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function loadMicmeConfig() {
|
|
38
|
-
const path = getMicmeConfigPath();
|
|
39
|
-
if (!existsSync(path)) return { path, found: false, values: {} };
|
|
40
|
-
|
|
41
|
-
try {
|
|
42
|
-
const parsed = JSON.parse(readFileSync(path, "utf8").replace(/^\uFEFF/, ""));
|
|
43
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
44
|
-
return { path, found: true, values: {}, error: "top-level value must be a JSON object" };
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
const values = {};
|
|
48
|
-
for (const [key, value] of Object.entries(parsed)) {
|
|
49
|
-
if (!key.startsWith("MICME_")) continue;
|
|
50
|
-
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") values[key] = String(value);
|
|
51
|
-
}
|
|
52
|
-
return { path, found: true, values };
|
|
53
|
-
} catch (error) {
|
|
54
|
-
return { path, found: true, values: {}, error: error instanceof Error ? error.message : String(error) };
|
|
55
|
-
}
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
function env(name) {
|
|
59
|
-
return process.env[name] ?? micmeConfig.values[name];
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
function expandConfigValue(value) {
|
|
63
|
-
const home = process.env.HOME || homedir();
|
|
64
|
-
const withHome = value.startsWith("~/") && home ? `${home}${value.slice(1)}` : value;
|
|
65
|
-
return withHome.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (_m, braced, bare) => {
|
|
66
|
-
const key = braced || bare || "";
|
|
67
|
-
return process.env[key] ?? micmeConfig.values[key] ?? "";
|
|
68
|
-
});
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
function envPath(name) {
|
|
72
|
-
const value = env(name);
|
|
73
|
-
return value ? expandConfigValue(value) : undefined;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function which(names) {
|
|
77
|
-
const pathDirs = (process.env.PATH || "").split(delimiter).filter(Boolean);
|
|
78
|
-
const exts = isWin ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";") : [""];
|
|
79
|
-
for (const name of names) {
|
|
80
|
-
for (const dir of pathDirs) {
|
|
81
|
-
for (const ext of exts) {
|
|
82
|
-
const candidate = join(dir, isWin && !/\.[^.]+$/.test(name) ? `${name}${ext}` : name);
|
|
83
|
-
if (isExecutableFile(candidate)) return candidate;
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
return undefined;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
function isExecutableFile(path) {
|
|
91
|
-
try {
|
|
92
|
-
const stats = statSync(path);
|
|
93
|
-
if (!stats.isFile()) return false;
|
|
94
|
-
if (isWin) return true;
|
|
95
|
-
accessSync(path, fsConstants.X_OK);
|
|
96
|
-
return true;
|
|
97
|
-
} catch {
|
|
98
|
-
return false;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function isRegularFile(path) {
|
|
103
|
-
try {
|
|
104
|
-
return statSync(path).isFile();
|
|
105
|
-
} catch {
|
|
106
|
-
return false;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function resolveExecutable(value) {
|
|
111
|
-
const expanded = expandConfigValue(value);
|
|
112
|
-
if (/[\\/]/.test(expanded)) return expanded;
|
|
113
|
-
return which([expanded]) || expanded;
|
|
114
|
-
}
|
|
10
|
+
const micmeConfig = reloadMicmeConfig();
|
|
115
11
|
|
|
116
12
|
function ok(label, detail = "") {
|
|
117
13
|
const safeLabel = sanitizeTerminalOutput(label);
|
|
@@ -138,115 +34,22 @@ function summarizeConfiguredCommand(value) {
|
|
|
138
34
|
return `configured (${trimmed.length} chars${placeholderText}; full value redacted)`;
|
|
139
35
|
}
|
|
140
36
|
|
|
141
|
-
function
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
function getTranscriptionMode() {
|
|
147
|
-
return env("MICME_TRANSCRIPTION_MODE") === "stream" ? "stream" : "clip";
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
function getTranslateToEnglishLanguage() {
|
|
151
|
-
const value = env("MICME_TRANSLATE_TO_ENGLISH")?.trim();
|
|
152
|
-
if (!value || /^(0|false|no|off)$/i.test(value)) return undefined;
|
|
153
|
-
return value;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
function toMultilingualWhisperModelName(modelName) {
|
|
157
|
-
return modelName.replace(/\.en$/i, "");
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function isTranslationUnsupportedWhisperModelName(modelName) {
|
|
161
|
-
if (!modelName) return false;
|
|
162
|
-
const normalized = modelName.toLowerCase();
|
|
163
|
-
return normalized === "turbo" || normalized === "large-v3-turbo" || normalized.startsWith("large-v3-turbo-");
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
function toTranslationCapableWhisperModelName(modelName) {
|
|
167
|
-
const multilingualName = toMultilingualWhisperModelName(modelName);
|
|
168
|
-
return isTranslationUnsupportedWhisperModelName(multilingualName) ? "large-v3" : multilingualName;
|
|
169
|
-
}
|
|
170
|
-
|
|
171
|
-
function getTranslationAwareWhisperModelName(modelName) {
|
|
172
|
-
return getTranslateToEnglishLanguage() ? toTranslationCapableWhisperModelName(modelName) : modelName;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
function isEnglishOnlyWhisperModelName(modelName) {
|
|
176
|
-
return Boolean(modelName && /\.en$/i.test(modelName));
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
function inferWhisperCppModelName(modelPath) {
|
|
180
|
-
return modelPath.match(/(?:^|[/\\])ggml-(.+)\.(?:bin|gguf)$/i)?.[1];
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
function getPythonWhisperModelName() {
|
|
184
|
-
return getTranslationAwareWhisperModelName(env("MICME_WHISPER_MODEL") || "base.en");
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
function resolveWhisperCppModelSummary() {
|
|
188
|
-
const explicit = envPath("MICME_WHISPER_CPP_MODEL");
|
|
189
|
-
if (explicit) {
|
|
190
|
-
return {
|
|
191
|
-
path: explicit,
|
|
192
|
-
modelName: inferWhisperCppModelName(explicit),
|
|
193
|
-
source: "MICME_WHISPER_CPP_MODEL explicit path",
|
|
194
|
-
exists: isRegularFile(explicit),
|
|
195
|
-
};
|
|
37
|
+
function resolveDoctorBinary(resolver) {
|
|
38
|
+
try {
|
|
39
|
+
return { path: resolver() };
|
|
40
|
+
} catch (error) {
|
|
41
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
196
42
|
}
|
|
197
|
-
const defaultModel = getTranslationAwareWhisperModelName(env("MICME_DEFAULT_WHISPER_CPP_MODEL") || "small.en");
|
|
198
|
-
const modelDir = expandConfigValue(env("MICME_MODEL_DIR") || join(homedir(), ".cache", "whisper.cpp"));
|
|
199
|
-
const path = join(modelDir, `ggml-${defaultModel}.bin`);
|
|
200
|
-
return {
|
|
201
|
-
path,
|
|
202
|
-
modelName: defaultModel,
|
|
203
|
-
source: env("MICME_DEFAULT_WHISPER_CPP_MODEL") ? "MICME_DEFAULT_WHISPER_CPP_MODEL" : "default whisper.cpp model name",
|
|
204
|
-
exists: isRegularFile(path),
|
|
205
|
-
};
|
|
206
43
|
}
|
|
207
44
|
|
|
208
|
-
function
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
const model = resolveWhisperCppModelSummary();
|
|
215
|
-
const warnings = [];
|
|
216
|
-
|
|
217
|
-
const invalidBackend = env("MICME_TRANSCRIBE_BACKEND")?.trim();
|
|
218
|
-
if (invalidBackend && !TRANSCRIBE_BACKENDS.has(invalidBackend)) warnings.push(`Invalid MICME_TRANSCRIBE_BACKEND=${invalidBackend}; using auto.`);
|
|
219
|
-
|
|
220
|
-
if (mode === "stream") {
|
|
221
|
-
if (requestedBackend === "python") {
|
|
222
|
-
return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "Streaming mode requires whisper.cpp; Python Whisper only supports clip transcription.", warnings };
|
|
223
|
-
}
|
|
224
|
-
if (requestedBackend === "custom") {
|
|
225
|
-
return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "Streaming mode requires whisper.cpp; custom transcribe commands only support clip transcription.", warnings };
|
|
226
|
-
}
|
|
227
|
-
if (whisperStreamAvailable) {
|
|
228
|
-
return { requestedBackend, effectiveBackend: "whisper.cpp", binary: whisperStream, model, effectiveModel: model.path, reason: "streaming uses whisper-stream", warnings };
|
|
229
|
-
}
|
|
230
|
-
return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIPTION_MODE=stream but whisper-stream was not found.", warnings };
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
if (requestedBackend === "custom") {
|
|
234
|
-
if (transcribeCommand?.trim()) return { requestedBackend, effectiveBackend: "custom", effectiveModel: "unknown", reason: "MICME_TRANSCRIBE_BACKEND=custom", warnings };
|
|
235
|
-
return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIBE_BACKEND=custom but MICME_TRANSCRIBE_COMMAND is not set.", warnings };
|
|
236
|
-
}
|
|
237
|
-
if (requestedBackend === "whisper.cpp") {
|
|
238
|
-
if (whisperCppAvailable) return { requestedBackend, effectiveBackend: "whisper.cpp", binary: whisperCpp, model, effectiveModel: model.path, reason: "MICME_TRANSCRIBE_BACKEND=whisper.cpp", warnings };
|
|
239
|
-
return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIBE_BACKEND=whisper.cpp but whisper.cpp was not found.", warnings };
|
|
240
|
-
}
|
|
241
|
-
if (requestedBackend === "python") {
|
|
242
|
-
if (pythonAvailable) return { requestedBackend, effectiveBackend: "python", binary: whisper, effectiveModel: getPythonWhisperModelName(), reason: "MICME_TRANSCRIBE_BACKEND=python", warnings };
|
|
243
|
-
return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "MICME_TRANSCRIBE_BACKEND=python but the `whisper` CLI was not found.", warnings };
|
|
45
|
+
function printWhisperCppModelDiagnostics(model) {
|
|
46
|
+
if (model.exists) {
|
|
47
|
+
ok("resolved whisper.cpp model", model.path);
|
|
48
|
+
} else {
|
|
49
|
+
const detail = getAutoDownloadModel() && model.downloadable ? `${model.path} (Micme will try to download this standard model when needed)` : model.path;
|
|
50
|
+
warn("resolved whisper.cpp model is missing", detail);
|
|
244
51
|
}
|
|
245
|
-
|
|
246
|
-
if (transcribeCommand?.trim()) return { requestedBackend, effectiveBackend: "custom", effectiveModel: "unknown", reason: "auto selected custom command because MICME_TRANSCRIBE_COMMAND is configured", warnings };
|
|
247
|
-
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 };
|
|
248
|
-
if (pythonAvailable) return { requestedBackend, effectiveBackend: "python", binary: whisper, effectiveModel: getPythonWhisperModelName(), reason: "auto selected Python Whisper because whisper.cpp is unavailable", warnings };
|
|
249
|
-
return { requestedBackend, effectiveBackend: "none", effectiveModel: "unavailable", reason: "No Micme transcription backend found.", warnings };
|
|
52
|
+
if (model.translationFallbackFrom) info("translation model fallback", `${model.translationFallbackFrom} -> ${model.modelName}`);
|
|
250
53
|
}
|
|
251
54
|
|
|
252
55
|
function printBackendPlanDiagnostics(plan) {
|
|
@@ -254,29 +57,29 @@ function printBackendPlanDiagnostics(plan) {
|
|
|
254
57
|
if (plan.effectiveBackend === "none") warn("effective backend", plan.reason);
|
|
255
58
|
else ok("effective backend", `${plan.effectiveBackend} (${plan.reason})`);
|
|
256
59
|
|
|
257
|
-
if (plan.effectiveBackend === "custom")
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
ok("translation", `${translateLanguage} -> English`);
|
|
267
|
-
if (plan.effectiveBackend === "custom") warn("translation backend", "custom transcribe commands must implement translation themselves");
|
|
268
|
-
if (plan.effectiveBackend === "whisper.cpp" && isEnglishOnlyWhisperModelName(plan.model?.modelName)) warn("translation model", `${plan.model.modelName} appears to be English-only; use a multilingual model`);
|
|
269
|
-
if (plan.effectiveBackend === "python" && isEnglishOnlyWhisperModelName(plan.effectiveModel)) warn("translation model", `${plan.effectiveModel} appears to be English-only; use a multilingual model`);
|
|
60
|
+
if (plan.effectiveBackend === "custom") {
|
|
61
|
+
info("effective model", "unknown; controlled by MICME_TRANSCRIBE_COMMAND");
|
|
62
|
+
} else if (plan.effectiveBackend === "whisper.cpp") {
|
|
63
|
+
info("effective model path", plan.modelPath || "unavailable");
|
|
64
|
+
info("effective model name", plan.modelName || "unknown");
|
|
65
|
+
info("effective model source", plan.modelSource || "unknown");
|
|
66
|
+
} else if (plan.effectiveBackend === "python") {
|
|
67
|
+
info("effective model name", plan.modelName || "unknown");
|
|
68
|
+
info("effective model source", plan.modelSource || "unknown");
|
|
270
69
|
} else {
|
|
271
|
-
info("
|
|
70
|
+
info("effective model", "unavailable");
|
|
272
71
|
}
|
|
273
72
|
|
|
73
|
+
const translateLanguage = getTranslateToEnglishLanguage();
|
|
74
|
+
if (translateLanguage) ok("translation", `${translateLanguage} -> English`);
|
|
75
|
+
else info("translation", "off");
|
|
76
|
+
|
|
274
77
|
for (const warning of plan.warnings) warn("backend warning", warning);
|
|
275
78
|
}
|
|
276
79
|
|
|
277
80
|
function printConfigDiagnostics() {
|
|
278
81
|
if (micmeConfig.error) warn("micme.json invalid", `${micmeConfig.path}: ${micmeConfig.error}`);
|
|
279
|
-
else if (micmeConfig.
|
|
82
|
+
else if (existsSync(micmeConfig.path)) ok("micme.json loaded", `${micmeConfig.path} (${Object.keys(micmeConfig.values).length} MICME_* key(s))`);
|
|
280
83
|
else info("micme.json", `not found; /micme conf will create ${micmeConfig.path}`);
|
|
281
84
|
|
|
282
85
|
const micmeEnvKeys = Object.keys(process.env).filter((key) => key.startsWith("MICME_")).sort((a, b) => a.localeCompare(b));
|
|
@@ -292,43 +95,28 @@ async function main() {
|
|
|
292
95
|
info("node", process.version);
|
|
293
96
|
printConfigDiagnostics();
|
|
294
97
|
|
|
295
|
-
const pi =
|
|
98
|
+
const pi = findExecutable(["pi"]);
|
|
296
99
|
if (pi) ok("pi CLI", pi);
|
|
297
100
|
else warn("pi CLI not found", "install @earendil-works/pi-coding-agent or use this as a package from pi");
|
|
298
101
|
|
|
299
|
-
const ffmpeg =
|
|
102
|
+
const ffmpeg = findExecutable(["ffmpeg"]);
|
|
300
103
|
if (ffmpeg) ok("ffmpeg recorder", ffmpeg);
|
|
301
104
|
else warn("ffmpeg recorder missing", "install ffmpeg or set MICME_RECORD_COMMAND");
|
|
302
105
|
|
|
303
|
-
const
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
if (whisperCpp && isExecutableFile(whisperCpp)) ok("whisper.cpp binary", whisperCpp);
|
|
307
|
-
else if (configuredWhisperCpp) warn("MICME_WHISPER_CPP_BIN is set but not executable or not found", resolveExecutable(configuredWhisperCpp));
|
|
106
|
+
const whisperCpp = resolveDoctorBinary(getWhisperCppBinary);
|
|
107
|
+
if (whisperCpp.path) ok("whisper.cpp binary", whisperCpp.path);
|
|
108
|
+
else if (whisperCpp.error) warn("whisper.cpp binary", whisperCpp.error);
|
|
308
109
|
else warn("whisper.cpp binary missing", "recommended backend for portable local transcription");
|
|
309
110
|
|
|
310
|
-
const
|
|
311
|
-
|
|
312
|
-
if (whisperStream
|
|
313
|
-
else if (configuredWhisperStream) warn("MICME_WHISPER_STREAM_BIN is set but not executable or not found", resolveExecutable(configuredWhisperStream));
|
|
111
|
+
const whisperStream = resolveDoctorBinary(getWhisperStreamBinary);
|
|
112
|
+
if (whisperStream.path) ok("whisper-stream binary", whisperStream.path);
|
|
113
|
+
else if (whisperStream.error) warn("whisper-stream binary", whisperStream.error);
|
|
314
114
|
else info("whisper-stream binary", "not installed; only needed for MICME_TRANSCRIPTION_MODE=stream");
|
|
315
115
|
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
if (!isRegularFile(whisperCppModel)) throw new Error("not a regular file");
|
|
319
|
-
await access(whisperCppModel);
|
|
320
|
-
ok("MICME_WHISPER_CPP_MODEL", whisperCppModel);
|
|
321
|
-
} catch {
|
|
322
|
-
const auto = env("MICME_AUTO_DOWNLOAD_MODEL") !== "0";
|
|
323
|
-
warn("MICME_WHISPER_CPP_MODEL is set but not readable as a file", auto ? `${whisperCppModel} (Micme will try to download if it is a standard ggml model path)` : whisperCppModel);
|
|
324
|
-
}
|
|
325
|
-
} else {
|
|
326
|
-
const defaultModel = getTranslationAwareWhisperModelName(env("MICME_DEFAULT_WHISPER_CPP_MODEL") || "small.en");
|
|
327
|
-
const modelDir = expandConfigValue(env("MICME_MODEL_DIR") || join(homedir(), ".cache", "whisper.cpp"));
|
|
328
|
-
info("MICME_WHISPER_CPP_MODEL", `not set; Micme defaults to ${modelDir}/ggml-${defaultModel}.bin and auto-downloads when needed`);
|
|
329
|
-
}
|
|
116
|
+
const whisperCppModel = resolveWhisperCppModel();
|
|
117
|
+
printWhisperCppModelDiagnostics(whisperCppModel);
|
|
330
118
|
|
|
331
|
-
const whisper =
|
|
119
|
+
const whisper = getPythonWhisperBinary();
|
|
332
120
|
if (whisper) ok("openai-whisper fallback", whisper);
|
|
333
121
|
else info("openai-whisper fallback", "not installed");
|
|
334
122
|
|
|
@@ -336,7 +124,18 @@ async function main() {
|
|
|
336
124
|
if (transcribeCommand) ok("custom transcribe command", summarizeConfiguredCommand(transcribeCommand));
|
|
337
125
|
else info("custom transcribe command", "not set");
|
|
338
126
|
|
|
339
|
-
printBackendPlanDiagnostics(
|
|
127
|
+
printBackendPlanDiagnostics(
|
|
128
|
+
resolveTranscriptionPlan({
|
|
129
|
+
transcriptionMode: getTranscriptionMode(),
|
|
130
|
+
customCommand: transcribeCommand || null,
|
|
131
|
+
whisperCppBinary: whisperCpp.path || null,
|
|
132
|
+
whisperCppBinaryError: whisperCpp.error,
|
|
133
|
+
whisperStreamBinary: whisperStream.path || null,
|
|
134
|
+
whisperStreamBinaryError: whisperStream.error,
|
|
135
|
+
pythonWhisperBinary: whisper || null,
|
|
136
|
+
whisperCppModel,
|
|
137
|
+
}),
|
|
138
|
+
);
|
|
340
139
|
|
|
341
140
|
const recordCommand = env("MICME_RECORD_COMMAND");
|
|
342
141
|
if (recordCommand) ok("custom record command", summarizeConfiguredCommand(recordCommand));
|
package/src/audio.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { sliceByColumn, visibleWidth, type Component } from "@earendil-works/pi-tui";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
-
import { AUDIO_VALIDATION_TIMEOUT_MS } from "./constants.ts";
|
|
4
|
+
import { AUDIO_VALIDATION_TIMEOUT_MS, MAX_CAPTURED_OUTPUT_CHARS } from "./constants.ts";
|
|
5
5
|
import { env, envFlag, getAudioFilter, getAvfoundationDropLateFrames, getAvfoundationInputSampleRate, getMinMaxVolumeDb, getRecordMeter, getRecordSampleRate, getRecordSync, getTranscribeSampleRate } from "./config.ts";
|
|
6
|
-
import { findExecutable, formatProcessOutput, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
|
|
6
|
+
import { appendCapped, findExecutable, formatProcessOutput, formatRunExit, replacePlaceholders, runProcess, shellCommand, shellQuote } from "./processes.ts";
|
|
7
7
|
import { sanitizeTerminalText } from "./terminal-text.ts";
|
|
8
|
-
import type { AudioDeviceCandidate, AudioDiagnostics, CommandSpec, RunResult } from "./types.ts";
|
|
8
|
+
import type { AudioDeviceCandidate, AudioDiagnostics, AudioValidationOutcome, CommandSpec, RunResult } from "./types.ts";
|
|
9
9
|
|
|
10
10
|
type DeviceBackend = "avfoundation" | "pulse" | "dshow" | "unsupported";
|
|
11
11
|
type DeviceKind = "audio" | "video";
|
|
@@ -637,19 +637,16 @@ export function parseAvfoundationAudioDevices(output: string): AudioDeviceCandid
|
|
|
637
637
|
}));
|
|
638
638
|
}
|
|
639
639
|
|
|
640
|
-
export async function prepareAudioForTranscription(inputPath: string, tempDir: string) {
|
|
640
|
+
export async function prepareAudioForTranscription(inputPath: string, tempDir: string, signal?: AbortSignal) {
|
|
641
641
|
if (env("MICME_PROCESS_AUDIO") === "0") return inputPath;
|
|
642
642
|
|
|
643
643
|
const ffmpeg = findExecutable(["ffmpeg"]);
|
|
644
644
|
if (!ffmpeg) return inputPath;
|
|
645
645
|
|
|
646
646
|
const outputPath = join(tempDir, "clip.wav");
|
|
647
|
-
const
|
|
648
|
-
const args = ["-hide_banner", "-loglevel", "error", "-y", "-i", inputPath];
|
|
649
|
-
if (filter) args.push("-af", filter);
|
|
650
|
-
args.push("-ac", "1", "-ar", String(getTranscribeSampleRate()), "-c:a", "pcm_s16le", outputPath);
|
|
647
|
+
const args = buildAudioPreprocessingArgs(inputPath, outputPath, getAudioFilter());
|
|
651
648
|
|
|
652
|
-
const result = await runProcess(ffmpeg, args, AUDIO_VALIDATION_TIMEOUT_MS);
|
|
649
|
+
const result = await runProcess(ffmpeg, args, AUDIO_VALIDATION_TIMEOUT_MS, { signal });
|
|
653
650
|
if (result.code !== 0) {
|
|
654
651
|
throw new Error(`Micme audio preprocessing failed (${formatRunExit(result)}):\n${formatProcessOutput(result.stderr, result.stdout)}`);
|
|
655
652
|
}
|
|
@@ -657,38 +654,77 @@ export async function prepareAudioForTranscription(inputPath: string, tempDir: s
|
|
|
657
654
|
return outputPath;
|
|
658
655
|
}
|
|
659
656
|
|
|
660
|
-
export
|
|
661
|
-
|
|
657
|
+
export function buildAudioPreprocessingArgs(inputPath: string, outputPath: string, filter: string) {
|
|
658
|
+
const args = ["-hide_banner", "-loglevel", "error", "-y", "-i", inputPath];
|
|
659
|
+
if (filter) args.push("-af", filter);
|
|
660
|
+
args.push("-ac", "1", "-ar", String(getTranscribeSampleRate()), "-c:a", "pcm_s16le", outputPath);
|
|
661
|
+
return args;
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
export async function validateRecordedAudio(audioPath: string, signal?: AbortSignal): Promise<AudioValidationOutcome> {
|
|
665
|
+
if (env("MICME_VALIDATE_AUDIO") === "0" || envFlag("MICME_SKIP_AUDIO_VALIDATION")) {
|
|
666
|
+
return { status: "skipped", reason: "disabled" };
|
|
667
|
+
}
|
|
662
668
|
|
|
663
669
|
const ffmpeg = findExecutable(["ffmpeg"]);
|
|
664
|
-
if (!ffmpeg) return
|
|
670
|
+
if (!ffmpeg) return { status: "skipped", reason: "ffmpeg-unavailable" };
|
|
665
671
|
|
|
666
|
-
const result = await runProcess(ffmpeg, ["-hide_banner", "-nostats", "-i", audioPath, "-af", "volumedetect", "-f", "null", "-"], AUDIO_VALIDATION_TIMEOUT_MS);
|
|
667
|
-
const raw = formatProcessOutput(`${result.stdout}\n${result.stderr}`);
|
|
672
|
+
const result = await runProcess(ffmpeg, ["-hide_banner", "-nostats", "-i", audioPath, "-af", "volumedetect", "-f", "null", "-"], AUDIO_VALIDATION_TIMEOUT_MS, { signal });
|
|
673
|
+
const raw = formatProcessOutput(appendCapped("", `${result.stdout}\n${result.stderr}`));
|
|
668
674
|
if (result.code !== 0) {
|
|
669
|
-
throw new Error(`Micme could not inspect recorded audio (${formatRunExit(result)})
|
|
675
|
+
throw new Error(`Micme could not inspect recorded audio (${formatRunExit(result)}).${formatAudioValidationDiagnostics(raw)}`);
|
|
676
|
+
}
|
|
677
|
+
if (audioValidationOutputReachedLimit(result)) {
|
|
678
|
+
throw new Error(
|
|
679
|
+
`Micme could not validate recorded audio because ffmpeg diagnostics reached the ${MAX_CAPTURED_OUTPUT_CHARS}-character capture limit; silence metrics may be truncated.` +
|
|
680
|
+
formatAudioValidationDiagnostics(raw),
|
|
681
|
+
);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const maxVolumeDb = parseVolumeDb(raw, "max_volume");
|
|
685
|
+
if (maxVolumeDb === undefined) {
|
|
686
|
+
throw new Error(
|
|
687
|
+
"Micme could not validate recorded audio because ffmpeg did not report the required max_volume metric. Silence validation did not pass." +
|
|
688
|
+
formatAudioValidationDiagnostics(raw),
|
|
689
|
+
);
|
|
670
690
|
}
|
|
671
691
|
|
|
672
692
|
const diagnostics: AudioDiagnostics = {
|
|
673
693
|
meanVolumeDb: parseVolumeDb(raw, "mean_volume"),
|
|
674
|
-
maxVolumeDb
|
|
694
|
+
maxVolumeDb,
|
|
675
695
|
raw,
|
|
676
696
|
};
|
|
677
697
|
|
|
678
698
|
const minimumMaxVolumeDb = getMinMaxVolumeDb();
|
|
679
|
-
if (diagnostics.maxVolumeDb
|
|
699
|
+
if (diagnostics.maxVolumeDb < minimumMaxVolumeDb) {
|
|
680
700
|
throw new Error(
|
|
681
|
-
`Micme recorded almost-silent audio (max ${diagnostics.maxVolumeDb
|
|
701
|
+
`Micme recorded almost-silent audio (max ${formatVolumeDb(diagnostics.maxVolumeDb)} dB; threshold ${minimumMaxVolumeDb.toFixed(1)} dB). ` +
|
|
682
702
|
"Whisper often hallucinates phrases like 'Thank you very much' from silence. " +
|
|
683
703
|
"Run /micme devices and set MICME_AUDIO_DEVICE to the real microphone, or set MICME_VALIDATE_AUDIO=0 to bypass this check.",
|
|
684
704
|
);
|
|
685
705
|
}
|
|
686
706
|
|
|
687
|
-
return diagnostics;
|
|
707
|
+
return { status: "validated", diagnostics };
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function audioValidationOutputReachedLimit(result: RunResult) {
|
|
711
|
+
return (
|
|
712
|
+
result.stdout.length >= MAX_CAPTURED_OUTPUT_CHARS ||
|
|
713
|
+
result.stderr.length >= MAX_CAPTURED_OUTPUT_CHARS ||
|
|
714
|
+
result.stdout.length + result.stderr.length >= MAX_CAPTURED_OUTPUT_CHARS
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function formatAudioValidationDiagnostics(raw: string) {
|
|
719
|
+
return raw ? `\nFFmpeg output:\n${raw}` : "\nFFmpeg produced no diagnostic output.";
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function formatVolumeDb(value: number) {
|
|
723
|
+
return value === Number.NEGATIVE_INFINITY ? "-inf" : value.toFixed(1);
|
|
688
724
|
}
|
|
689
725
|
|
|
690
726
|
export function parseVolumeDb(output: string, label: "mean_volume" | "max_volume") {
|
|
691
|
-
const pattern = new RegExp(String.raw`${label}:\s*(
|
|
727
|
+
const pattern = new RegExp(String.raw`${label}:\s*(-?\d+(?:\.\d+)?|-inf)\s*dB`, "i");
|
|
692
728
|
const match = pattern.exec(output);
|
|
693
729
|
if (!match) return undefined;
|
|
694
730
|
return match[1]?.toLowerCase() === "-inf" ? Number.NEGATIVE_INFINITY : Number(match[1]);
|
|
@@ -719,19 +755,19 @@ export function buildRecorderCommand(audioPath: string, tempDir = dirname(audioP
|
|
|
719
755
|
inputOptions: ["-drop_late_frames", getAvfoundationDropLateFrames() ? "true" : "false"],
|
|
720
756
|
audioFilters: getAvfoundationAudioFilters(recordSync, avfoundationInputSampleRate),
|
|
721
757
|
});
|
|
722
|
-
return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n" };
|
|
758
|
+
return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n", signalStopExitCodes: [255] };
|
|
723
759
|
}
|
|
724
760
|
|
|
725
761
|
if (process.platform === "linux") {
|
|
726
762
|
const input = env("MICME_PULSE_SOURCE") || "default";
|
|
727
763
|
const args = buildFfmpegRecorderArgs("pulse", input, audioPath, recordSampleRate, { meter: recordMeter, audioFilters: timingFilters });
|
|
728
|
-
return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n" };
|
|
764
|
+
return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n", signalStopExitCodes: [255] };
|
|
729
765
|
}
|
|
730
766
|
|
|
731
767
|
if (process.platform === "win32") {
|
|
732
768
|
const input = `audio=${env("MICME_DSHOW_AUDIO_DEVICE") || "default"}`;
|
|
733
769
|
const args = buildFfmpegRecorderArgs("dshow", input, audioPath, recordSampleRate, { meter: recordMeter, audioFilters: timingFilters });
|
|
734
|
-
return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n" };
|
|
770
|
+
return { command: ffmpeg, args, display: `${ffmpeg} ${args.map(shellQuote).join(" ")}`, meterFromStdout: recordMeter, stopInput: "q\n", signalStopExitCodes: [255] };
|
|
735
771
|
}
|
|
736
772
|
|
|
737
773
|
throw new Error(`Micme has no default recorder for ${process.platform}. Set MICME_RECORD_COMMAND.`);
|