@senad-d/micme 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/models.ts CHANGED
@@ -6,13 +6,16 @@ import { homedir } from "node:os";
6
6
  import { basename, dirname, join } from "node:path";
7
7
  import { finished } from "node:stream/promises";
8
8
  import {
9
+ DEFAULT_PYTHON_WHISPER_MODEL_NAME,
9
10
  DEFAULT_WHISPER_CPP_MODEL_NAME,
11
+ PYTHON_WHISPER_MODEL_NAMES,
10
12
  STATUS_KEY,
11
13
  WHISPER_CPP_MODEL_BASE_URL,
12
14
  WHISPER_CPP_MODEL_NAMES,
13
15
  } from "./constants.ts";
14
16
  import { env, expandConfigPath } from "./config.ts";
15
- import type { ModelCandidate } from "./types.ts";
17
+ import { findExecutable, runProcess } from "./processes.ts";
18
+ import type { ModelCandidate, ResolvedWhisperCppModel } from "./types.ts";
16
19
 
17
20
  const modelDownloads = new Map<string, Promise<void>>();
18
21
 
@@ -32,23 +35,25 @@ export function discoverWhisperCppModels(cwd: string): ModelCandidate[] {
32
35
  add({
33
36
  label: basename(expanded),
34
37
  value: expanded,
35
- description: existsSync(expanded) ? `current model: ${expanded}` : `current model path is missing: ${expanded}`,
38
+ description: existsSync(expanded) ? `current explicit path: ${expanded}` : `current explicit path is missing: ${expanded}`,
36
39
  installed: existsSync(expanded),
40
+ kind: "path",
37
41
  });
38
42
  }
39
43
 
40
44
  for (const file of scanModelFiles(cwd)) {
41
- add({ label: basename(file), value: file, description: file, installed: true });
45
+ add({ label: basename(file), value: file, description: file, installed: true, kind: "path" });
42
46
  }
43
47
 
44
48
  const cacheDir = getWhisperCppModelCacheDir();
45
49
  for (const modelName of WHISPER_CPP_MODEL_NAMES) {
46
50
  const path = join(cacheDir, `ggml-${modelName}.bin`);
47
51
  add({
48
- label: `ggml-${modelName}.bin`,
52
+ label: modelName,
49
53
  value: path,
50
- description: `${describeWhisperModel(modelName)}${existsSync(path) ? "" : " (expected path; download model first)"}`,
54
+ description: `${describeWhisperModel(modelName)} • ${basename(path)}${existsSync(path) ? "" : " (expected path; download model first)"}`,
51
55
  installed: existsSync(path),
56
+ kind: "model-name",
52
57
  });
53
58
  }
54
59
 
@@ -111,8 +116,80 @@ export function describeWhisperModel(name: string) {
111
116
  return "Whisper model";
112
117
  }
113
118
 
114
- export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionContext) {
119
+ export function resolveWhisperCppModel(): ResolvedWhisperCppModel {
120
+ 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
+ }
132
+
133
+ const configuredName = env("MICME_DEFAULT_WHISPER_CPP_MODEL")?.trim();
134
+ const modelName = configuredName || DEFAULT_WHISPER_CPP_MODEL_NAME;
135
+ const path = join(getWhisperCppModelCacheDir(), `ggml-${modelName}.bin`);
136
+ return {
137
+ path,
138
+ modelName,
139
+ source: configuredName ? "configured-name" : "default-name",
140
+ configuredValue: configuredName,
141
+ exists: existsSync(path),
142
+ downloadable: isDownloadableWhisperCppModelPath(path),
143
+ };
144
+ }
145
+
146
+ export function getPythonWhisperModelName() {
147
+ return env("MICME_WHISPER_MODEL")?.trim() || DEFAULT_PYTHON_WHISPER_MODEL_NAME;
148
+ }
149
+
150
+ export async function discoverPythonWhisperModels(): Promise<ModelCandidate[]> {
151
+ const dynamicNames = await queryPythonWhisperModelNames();
152
+ const names = dynamicNames.length > 0 ? dynamicNames : [...PYTHON_WHISPER_MODEL_NAMES];
153
+ const source = dynamicNames.length > 0 ? "reported by whisper.available_models()" : "built-in fallback list";
154
+ return names.map((name) => ({
155
+ label: name,
156
+ value: name,
157
+ description: `${describeWhisperModel(name)} • ${source}`,
158
+ installed: dynamicNames.length > 0,
159
+ kind: "model-name",
160
+ }));
161
+ }
162
+
163
+ export async function queryPythonWhisperModelNames(): Promise<string[]> {
164
+ const python = findExecutable(["python3", "python"]);
165
+ if (!python) return [];
166
+
167
+ try {
168
+ const result = await runProcess(python, ["-c", "import whisper; print('\\n'.join(whisper.available_models()))"], 2_000);
169
+ if (result.code !== 0 || result.timedOut) return [];
170
+ return uniqueModelNames(result.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
171
+ } catch {
172
+ return [];
173
+ }
174
+ }
175
+
176
+ export function uniqueModelNames(names: string[]) {
177
+ const seen = new Set<string>();
178
+ const output: string[] = [];
179
+ for (const name of names) {
180
+ const normalized = name.trim();
181
+ if (!normalized || seen.has(normalized)) continue;
182
+ seen.add(normalized);
183
+ output.push(normalized);
184
+ }
185
+ return output;
186
+ }
187
+
188
+ export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionContext, options: { allowDownload?: boolean } = {}) {
115
189
  if (existsSync(modelPath)) return;
190
+ if (options.allowDownload === false) {
191
+ throw new Error(`Micme model is missing: ${modelPath}`);
192
+ }
116
193
  if (env("MICME_AUTO_DOWNLOAD_MODEL") === "0") {
117
194
  throw new Error(`Micme model is missing and auto-download is disabled: ${modelPath}`);
118
195
  }
@@ -128,9 +205,9 @@ export async function ensureWhisperCppModel(modelPath: string, ctx?: ExtensionCo
128
205
  return;
129
206
  }
130
207
 
131
- const modelName = getWhisperCppModelNameFromPath(modelPath);
208
+ const modelName = getDownloadableWhisperCppModelName(modelPath);
132
209
  if (!modelName) {
133
- throw new Error(`Micme model is missing and cannot infer download URL: ${modelPath}`);
210
+ throw new Error(`Micme model is missing and cannot infer a standard download URL: ${modelPath}`);
134
211
  }
135
212
 
136
213
  const download = downloadWhisperCppModel(modelName, modelPath, ctx);
@@ -204,6 +281,20 @@ export function getWhisperCppModelNameFromPath(modelPath: string) {
204
281
  return match?.[1];
205
282
  }
206
283
 
284
+ export function getDownloadableWhisperCppModelName(modelPath: string) {
285
+ const match = basename(modelPath).match(/^ggml-(.+)\.bin$/i);
286
+ const modelName = match?.[1];
287
+ return modelName && isKnownWhisperCppModelName(modelName) ? modelName : undefined;
288
+ }
289
+
290
+ export function isDownloadableWhisperCppModelPath(modelPath: string) {
291
+ return getDownloadableWhisperCppModelName(modelPath) !== undefined;
292
+ }
293
+
294
+ export function isKnownWhisperCppModelName(modelName: string): modelName is (typeof WHISPER_CPP_MODEL_NAMES)[number] {
295
+ return WHISPER_CPP_MODEL_NAMES.includes(modelName as (typeof WHISPER_CPP_MODEL_NAMES)[number]);
296
+ }
297
+
207
298
  export function getWhisperCppModelUrl(modelName: string) {
208
299
  return `${WHISPER_CPP_MODEL_BASE_URL}/ggml-${modelName}.bin`;
209
300
  }
@@ -213,7 +304,7 @@ export function getWhisperCppModelCacheDir() {
213
304
  }
214
305
 
215
306
  export function getDefaultWhisperCppModelPath() {
216
- const modelName = env("MICME_DEFAULT_WHISPER_CPP_MODEL") || DEFAULT_WHISPER_CPP_MODEL_NAME;
307
+ const modelName = env("MICME_DEFAULT_WHISPER_CPP_MODEL")?.trim() || DEFAULT_WHISPER_CPP_MODEL_NAME;
217
308
  return join(getWhisperCppModelCacheDir(), `ggml-${modelName}.bin`);
218
309
  }
219
310
 
@@ -0,0 +1,54 @@
1
+ import { mkdir, mkdtemp, readdir } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+
5
+ const PROJECT_RECORDINGS_DIR = "micme-rec";
6
+ const RECORDING_DIR_PREFIX = "rec-";
7
+ const MAX_SEQUENTIAL_RECORDING_DIRS = 999_999;
8
+
9
+ export async function createRecordingDirectory(cwd: string, keepAudio: boolean, tempPrefix = "micme-") {
10
+ if (!keepAudio) return mkdtemp(join(tmpdir(), tempPrefix));
11
+ return createProjectRecordingDirectory(cwd);
12
+ }
13
+
14
+ export async function createProjectRecordingDirectory(cwd: string) {
15
+ const recordingsRoot = join(cwd, PROJECT_RECORDINGS_DIR);
16
+ await mkdir(recordingsRoot, { recursive: true });
17
+
18
+ const nextIndex = await getNextRecordingIndex(recordingsRoot);
19
+
20
+ for (let index = nextIndex; index <= MAX_SEQUENTIAL_RECORDING_DIRS; index += 1) {
21
+ const candidate = join(recordingsRoot, formatRecordingDirectoryName(index));
22
+ try {
23
+ await mkdir(candidate);
24
+ return candidate;
25
+ } catch (error) {
26
+ if (isAlreadyExistsError(error)) continue;
27
+ throw error;
28
+ }
29
+ }
30
+
31
+ throw new Error(`Unable to create a Micme recording directory under ${recordingsRoot}.`);
32
+ }
33
+
34
+ async function getNextRecordingIndex(recordingsRoot: string) {
35
+ const entries = await readdir(recordingsRoot, { withFileTypes: true });
36
+ let maxIndex = 0;
37
+ for (const entry of entries) {
38
+ const match = /^rec-(\d+)$/.exec(entry.name);
39
+ if (!match) continue;
40
+ const index = Number(match[1]);
41
+ if (Number.isInteger(index) && index > maxIndex) maxIndex = index;
42
+ }
43
+ return Math.max(1, maxIndex + 1);
44
+ }
45
+
46
+ export function formatRecordingDirectoryName(index: number) {
47
+ const safeIndex = Math.max(1, Math.trunc(index));
48
+ const text = String(safeIndex);
49
+ return `${RECORDING_DIR_PREFIX}${text.padStart(Math.max(3, text.length), "0")}`;
50
+ }
51
+
52
+ function isAlreadyExistsError(error: unknown) {
53
+ return typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "EEXIST";
54
+ }