-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathWhisperCppTranscriptionPlugin.ts
More file actions
1487 lines (1321 loc) · 43.6 KB
/
WhisperCppTranscriptionPlugin.ts
File metadata and controls
1487 lines (1321 loc) · 43.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { spawn, ChildProcess } from "child_process";
import {
unlinkSync,
existsSync,
readFileSync,
readdirSync,
} from "fs";
import { join } from "path";
import { arch, platform } from "os";
import { v4 as uuidv4 } from "uuid";
import { AppConfig } from "../config/AppConfig";
import { FileSystemService } from "../services/FileSystemService";
import {
Segment,
TranscribedSegment,
InProgressSegment,
SegmentUpdate,
} from "../types/SegmentTypes";
import {
BaseTranscriptionPlugin,
TranscriptionSetupProgress,
PluginSchemaItem,
PluginUIFunctions,
} from "./TranscriptionPlugin";
import { readPrompt } from "../helpers/getPrompt";
/**
* Whisper.cpp transcription plugin
*/
export class WhisperCppTranscriptionPlugin extends BaseTranscriptionPlugin {
readonly name = "whisper-cpp";
readonly displayName = "Whisper.cpp";
readonly version = "1.7.6";
readonly description =
"High-performance C++ implementation of OpenAI Whisper for local transcription";
readonly supportsRealtime = true;
readonly supportsBatchProcessing = true;
private config: AppConfig;
private sessionUid: string = "";
private currentSegments: Segment[] = [];
private whisperBinaryPath: string;
private modelPath: string = "";
private isAppleSilicon: boolean;
private resolvedBinaryPath: string;
private warmupTimer: NodeJS.Timeout | null = null;
private isWarmupRunning = false;
private isWindowVisible = false;
private isCurrentlyTranscribing = false;
private useCoreML = false;
constructor(config: AppConfig) {
super();
this.config = config;
this.isAppleSilicon = arch() === "arm64" && platform() === "darwin";
this.whisperBinaryPath = this.resolveWhisperBinaryPath(); // Keep for backward compatibility
// Don't set modelPath here - wait for options to be applied
this.resolvedBinaryPath = this.getBinaryPath(true); // Resolve once and store
// Default to processing segments individually, will be updated when options are set
const defaultRunOnAll = false;
this.setActivationCriteria({
runOnAll: defaultRunOnAll,
skipTransformation: false,
});
this.useCoreML = false;
}
/**
* Define fallback chain for Whisper.cpp plugin
* Prefer offline plugins: Vosk first, then YAP as lightweight fallback
*/
getFallbackChain(): string[] {
return ["vosk", "yap"];
}
private resolveWhisperBinaryPath(): string {
// On Apple Silicon, prefer Metal version if available
if (this.isAppleSilicon) {
// Try production bundled Metal path first
const packagedMetalPath = join(
process.resourcesPath,
"whisper-cpp",
"whisper-cli-metal",
);
if (existsSync(packagedMetalPath)) {
return packagedMetalPath;
}
// Fall back to development vendor Metal path
const devMetalPath = join(
process.cwd(),
"vendor",
"whisper-cpp",
"whisper-cli-metal",
);
if (existsSync(devMetalPath)) {
return devMetalPath;
}
}
// Try production bundled path first
const packagedPath = join(
process.resourcesPath,
"whisper-cpp",
"whisper-cli",
);
if (existsSync(packagedPath)) {
return packagedPath;
}
// Fall back to development vendor path
const devPath = join(process.cwd(), "vendor", "whisper-cpp", "whisper-cli");
if (existsSync(devPath)) {
return devPath;
}
// Fall back to system whisper-cli (if installed)
return "whisper-cli";
}
private resolveModelPath(): string {
// Get model from plugin options with fallback to default
const modelName = this.options.model || "ggml-base.en.bin";
// Models are now stored directly as files in the models directory
const userModelPath = join(this.config.getModelsDir(), modelName);
if (existsSync(userModelPath)) {
return userModelPath;
}
// Try production bundled path first
const packagedPath = join(
process.resourcesPath,
"whisper-cpp",
"models",
modelName,
);
if (existsSync(packagedPath)) {
return packagedPath;
}
// Fall back to development vendor path
const devPath = join(
process.cwd(),
"vendor",
"whisper-cpp",
"models",
modelName,
);
if (existsSync(devPath)) {
return devPath;
}
// Return expected path for download
return userModelPath;
}
async isBinaryAvailable(): Promise<boolean> {
try {
// Check if whisper binary exists and is executable
return new Promise((resolve) => {
const whisperProcess = spawn(this.resolvedBinaryPath, ["--help"], {
stdio: ["ignore", "pipe", "pipe"],
});
console.log(
"Whisper.cpp binary check started",
this.resolvedBinaryPath,
);
let hasOutput = false;
whisperProcess.stdout?.on("data", (data) => {
hasOutput = true;
resolve(true);
});
whisperProcess.stderr?.on("data", (data) => {
hasOutput = true;
resolve(true);
});
whisperProcess.on("close", (code) => {
console.log("Whisper.cpp binary check closed with code:", {
code,
hasOutput,
});
resolve(code === 0); // Some versions return 1 for --help
});
whisperProcess.on("error", (error) => {
console.log("Whisper.cpp binary check failed:", error.message);
resolve(false);
});
// Timeout after 5 seconds with cleanup
const timeout = setTimeout(() => {
if (!whisperProcess.killed) {
console.log("Whisper.cpp binary check timed out");
whisperProcess.kill();
resolve(false);
}
}, 5000);
whisperProcess.on("close", () => clearTimeout(timeout));
whisperProcess.on("error", () => clearTimeout(timeout));
});
} catch (error) {
console.error("Whisper.cpp binary availability check failed:", error);
return false;
}
}
async isAvailable(): Promise<boolean> {
return await this.isBinaryAvailable();
}
async startTranscription(
onUpdate: (update: SegmentUpdate) => void,
onProgress?: (progress: TranscriptionSetupProgress) => void,
onLog?: (line: string) => void,
): Promise<void> {
if (this.isRunning) {
onLog?.("[Whisper.cpp Plugin] Service already running");
onProgress?.({ status: "complete", message: "Whisper.cpp plugin ready" });
return;
}
try {
// Model path should already be set by the unified plugin system
// Don't override it here
onProgress?.({
status: "starting",
message: "Initializing Whisper.cpp plugin",
});
// Log which binary and Core ML model will be used
const modelName = this.options.model || "ggml-base.en.bin";
const coreMLPath = this.getCoreMLModelPath(modelName);
if (this.isAppleSilicon) {
if (coreMLPath) {
onLog?.("[Whisper.cpp Plugin] Apple Metal acceleration enabled");
} else {
console.log("Core ML model not found, using regular binary");
onLog?.(
"[Whisper.cpp Plugin] Apple Metal acceleration not available",
);
}
}
this.setTranscriptionCallback(onUpdate);
this.sessionUid = uuidv4();
this.currentSegments = [];
this.setRunning(true);
onProgress?.({ status: "complete", message: "Whisper.cpp plugin ready" });
onLog?.(
"[Whisper.cpp Plugin] Service initialized and ready for audio segments",
);
} catch (error: any) {
console.error("Failed to start Whisper.cpp plugin:", error);
this.setRunning(false);
onProgress?.({
status: "error",
message: `Failed to start plugin: ${error.message}`,
});
this.emit("error", error);
throw error;
}
}
async processAudioSegment(audioData: Float32Array): Promise<void> {
if (!this.isRunning || !this.onTranscriptionCallback) {
return;
}
try {
this.isCurrentlyTranscribing = true;
console.log(`Processing audio segment: ${audioData.length} samples`);
// Show in-progress transcription synchronously before any async operations
const inProgressSegment: InProgressSegment = {
id: uuidv4(),
type: "inprogress",
text: "Transcribing...",
timestamp: Date.now(),
};
this.currentSegments = [inProgressSegment];
this.onTranscriptionCallback?.({
segments: [...this.currentSegments],
sessionUid: this.sessionUid,
});
// Create temporary WAV file for whisper.cpp
const tempAudioPath = await this.saveAudioAsWav(audioData);
// Transcribe with whisper.cpp
const rawTranscription =
await this.transcribeWithWhisperCpp(tempAudioPath);
// Clean up temp file
try {
unlinkSync(tempAudioPath);
} catch (err) {
console.warn("Failed to delete temp audio file:", err);
}
// Use uniform post-processing API
const postProcessed = this.postProcessTranscription(rawTranscription, {
parseTimestamps: true,
cleanText: true,
extractConfidence: false,
});
// Create completed segment
const completedSegment: TranscribedSegment = {
id: uuidv4(),
type: "transcribed",
text: postProcessed.text,
completed: true,
timestamp: Date.now(),
confidence: postProcessed.confidence ?? 0.95, // Whisper.cpp generally has good confidence
start: postProcessed.start,
end: postProcessed.end,
};
this.currentSegments = [completedSegment];
if (this.onTranscriptionCallback) {
this.onTranscriptionCallback({
segments: [...this.currentSegments],
sessionUid: this.sessionUid,
});
}
} catch (error: any) {
console.error("Failed to process audio segment:", error);
const errorSegment: TranscribedSegment = {
id: uuidv4(),
type: "transcribed",
text: "[Transcription failed]",
completed: true,
timestamp: Date.now(),
confidence: 0,
};
this.currentSegments = [errorSegment];
if (this.onTranscriptionCallback) {
this.onTranscriptionCallback({
segments: [...this.currentSegments],
sessionUid: this.sessionUid,
});
}
} finally {
this.isCurrentlyTranscribing = false;
}
}
async transcribeFile(filePath: string): Promise<string> {
const rawTranscription = await this.transcribeWithWhisperCpp(filePath);
const postProcessed = this.postProcessTranscription(rawTranscription, {
parseTimestamps: true,
cleanText: true,
extractConfidence: false,
});
return postProcessed.text;
}
async stopTranscription(): Promise<void> {
console.log("=== Stopping Whisper.cpp transcription plugin ===");
this.setRunning(false);
this.setTranscriptionCallback(null);
this.currentSegments = [];
this.isCurrentlyTranscribing = false;
console.log("Whisper.cpp transcription plugin stopped");
}
async cleanup(): Promise<void> {
await this.stopTranscription();
// Clean up temp directory
try {
const { readdirSync } = require("fs");
const files = readdirSync(this.tempDir);
for (const file of files) {
unlinkSync(join(this.tempDir, file));
}
} catch (err) {
console.warn("Failed to clean temp directory:", err);
}
}
/**
* Update the model path after model switch
*/
updateModelPath(): void {
this.modelPath = this.resolveModelPath();
console.log(
`WhisperCppTranscriptionPlugin: Updated model path to ${this.modelPath}`,
);
}
/**
* Download Core ML model for a given model name
*/
async downloadCoreMLModel(modelName: string): Promise<string | null> {
if (!this.isAppleSilicon) {
console.log("Core ML models are only supported on Apple Silicon");
return null;
}
// Strip quantization suffix if present (e.g., "ggml-base.en-q4_0.bin" -> "ggml-base.en")
const baseModelName = modelName
.replace(/-\w+\.bin$/, "")
.replace(/\.bin$/, "");
const coreMLModelName = `${baseModelName}-encoder.mlmodelc`;
const coreMLZipName = `${coreMLModelName}.zip`;
const coreMLUrl = `https://huggingface.co/ggerganov/whisper.cpp/resolve/main/${coreMLZipName}`;
const localZipPath = join(this.config.getModelsDir(), coreMLZipName);
const localModelPath = join(this.config.getModelsDir(), coreMLModelName);
// Check if already exists
if (existsSync(localModelPath)) {
console.log(`Core ML model ${coreMLModelName} already exists`);
return localModelPath;
}
try {
console.log(`Downloading Core ML model: ${coreMLModelName}`);
await this.downloadFileWithProgress(coreMLUrl, localZipPath, coreMLModelName);
// Extract the zip
await this.extractZip(localZipPath, this.config.getModelsDir());
// Clean up zip file
unlinkSync(localZipPath);
console.log(`Core ML model ${coreMLModelName} downloaded successfully`);
return localModelPath;
} catch (error) {
console.warn(
`Failed to download Core ML model ${coreMLModelName}: ${error}`,
);
return null;
}
}
/**
* Get the appropriate binary path for the current platform
* @param preferMetal - Whether to prefer Metal version on Apple Silicon
* @returns Path to the appropriate binary
*/
getBinaryPath(preferMetal = true): string {
if (this.isAppleSilicon && this.useCoreML) {
// Try production bundled Metal path first
const packagedMetalPath = join(
process.resourcesPath,
"whisper-cpp",
"whisper-cli-metal",
);
if (existsSync(packagedMetalPath)) {
return packagedMetalPath;
}
// Fall back to development vendor Metal path
const devMetalPath = join(
process.cwd(),
"vendor",
"whisper-cpp",
"whisper-cli-metal",
);
if (existsSync(devMetalPath)) {
return devMetalPath;
}
}
// Fall back to regular binary
return this.resolveWhisperBinaryPath();
}
/**
* Check if Core ML model exists for a given model name
* @param modelName - The model name to check
* @returns Path to Core ML model if it exists, null otherwise
*/
getCoreMLModelPath(modelName: string): string | null {
if (!this.isAppleSilicon) {
return null;
}
// Strip quantization suffix if present (e.g., "ggml-base.en-q4_0.bin" -> "ggml-base.en")
const baseModelName = modelName
.replace(/-\w+\.bin$/, "")
.replace(/\.bin$/, "");
const coreMLModelName = `${baseModelName}-encoder.mlmodelc`;
const coreMLModelPath = join(this.config.getModelsDir(), coreMLModelName);
return existsSync(coreMLModelPath) ? coreMLModelPath : null;
}
/**
* Transcribe audio file using whisper.cpp CLI
*/
private async transcribeWithWhisperCpp(audioPath: string): Promise<string> {
return new Promise((resolve, reject) => {
const args = [
"--file",
audioPath,
"--model",
this.modelPath,
"--output-txt",
];
// Add whisper prompt
const whisperPrompt = this.options.prompt;
if (whisperPrompt && whisperPrompt.trim()) {
args.push("--prompt", whisperPrompt.trim());
}
// Add configuration options
const language = this.options.language || "auto";
if (language && language !== "auto") {
args.push("--language", language);
}
const threads = this.options.threads || 4;
if (threads) {
args.push("--threads", threads.toString());
}
console.log(
`Running Whisper.cpp: ${this.resolvedBinaryPath} ${args.join(" ")}`,
);
const whisperProcess = spawn(this.resolvedBinaryPath, args, {
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
whisperProcess.stdout?.on("data", (data) => {
stdout += data.toString();
});
whisperProcess.stderr?.on("data", (data) => {
stderr += data.toString();
});
whisperProcess.on("close", (code) => {
if (code === 0) {
// Try to read the output txt file
const txtOutputPath = audioPath.replace(/\.[^/.]+$/, ".txt");
try {
const rawTranscription = readFileSync(txtOutputPath, "utf8").trim();
unlinkSync(txtOutputPath); // Clean up output file
resolve(rawTranscription || "[No speech detected]");
} catch (fileError) {
// If we can't read the file, try to get output from stdout
const rawTranscription = stdout.trim();
resolve(rawTranscription || "[No speech detected]");
}
} else {
const error = new Error(
`Whisper.cpp failed with code ${code}: ${stderr}`,
);
console.error("Whisper.cpp error:", error.message);
reject(error);
}
});
whisperProcess.on("error", (error) => {
console.error("Whisper.cpp spawn error:", error);
reject(error);
});
// Set timeout to prevent hanging (3 minutes) with cleanup
const timeout = setTimeout(() => {
if (!whisperProcess.killed) {
console.error("Whisper.cpp transcription timeout after 3 minutes");
whisperProcess.kill();
reject(new Error("Whisper.cpp transcription timeout"));
}
}, 180000);
const clearAll = () => clearTimeout(timeout);
whisperProcess.on("close", clearAll);
whisperProcess.on("error", clearAll);
});
}
// New unified plugin system methods
getSchema(): PluginSchemaItem[] {
const whisperModels = [
{
value: "ggml-tiny.bin",
label: "Tiny",
description: "Fastest, least accurate - multilingual",
size: "77.7 MB",
},
{
value: "ggml-tiny.en.bin",
label: "Tiny English",
description: "English only, fastest option",
size: "77.7 MB",
},
{
value: "ggml-tiny-q5_1.bin",
label: "Tiny Quantized",
description: "Smallest size, good quality",
size: "32.2 MB",
},
{
value: "ggml-tiny-q8_0.bin",
label: "Tiny Q8",
description: "Better quality than Q5_1",
size: "43.5 MB",
},
{
value: "ggml-base.bin",
label: "Base",
description: "Good balance of speed and accuracy",
size: "148 MB",
},
{
value: "ggml-base.en.bin",
label: "Base English",
description: "English only, recommended for most users",
size: "148 MB",
},
{
value: "ggml-base-q5_1.bin",
label: "Base Quantized",
description: "Compact with good quality",
size: "59.7 MB",
},
{
value: "ggml-base-q8_0.bin",
label: "Base Q8",
description: "Higher quality quantized",
size: "81.8 MB",
},
{
value: "ggml-small.bin",
label: "Small",
description: "Higher accuracy, slower",
size: "488 MB",
},
{
value: "ggml-small.en.bin",
label: "Small English",
description: "English only, higher accuracy",
size: "488 MB",
},
{
value: "ggml-medium.bin",
label: "Medium",
description: "Very accurate, much slower",
size: "1.53 GB",
},
{
value: "ggml-medium.en.bin",
label: "Medium English",
description: "English only, very accurate",
size: "1.53 GB",
},
{
value: "ggml-large-v2.bin",
label: "Large v2",
description: "Excellent accuracy, very slow",
size: "3.09 GB",
},
{
value: "ggml-large-v3.bin",
label: "Large v3",
description: "Latest large model, best accuracy",
size: "3.1 GB",
},
{
value: "ggml-large-v3-turbo.bin",
label: "Large v3 Turbo",
description: "Fast large model, great balance",
size: "1.62 GB",
},
];
const options: PluginSchemaItem[] = [
{
key: "model",
type: "model-select",
label: "Whisper Model",
description: "Choose the Whisper model to use for transcription",
default: "ggml-base.en.bin",
category: "model",
options: whisperModels,
required: true,
},
{
key: "language",
type: "select",
label: "Language",
description:
"Language for transcription (auto-detect if not specified)",
default: "auto",
category: "basic",
options: [
{ value: "auto", label: "Auto-detect" },
{ value: "en", label: "English" },
{ value: "es", label: "Spanish" },
{ value: "fr", label: "French" },
{ value: "de", label: "German" },
{ value: "it", label: "Italian" },
{ value: "pt", label: "Portuguese" },
{ value: "ru", label: "Russian" },
{ value: "ja", label: "Japanese" },
{ value: "ko", label: "Korean" },
{ value: "zh", label: "Chinese" },
],
},
{
key: "threads",
type: "number",
label: "Thread Count",
description: "Number of threads to use for transcription",
default: 4,
min: 1,
max: 16,
category: "advanced",
},
{
key: "prompt",
type: "string",
label: "Transcription Prompt",
description: "Custom prompt to guide the transcription (optional)",
default: readPrompt("whisper"),
category: "advanced",
},
{
key: "runOnAll",
type: "boolean",
label: "Process All Audio Together",
description:
"When enabled, processes all audio segments together for better context. When disabled, processes each segment individually.",
default: false,
category: "advanced",
},
];
// Add Apple Metal option only on Apple Silicon
if (this.isAppleSilicon) {
options.push({
key: "useCoreML",
type: "boolean",
label: "Use Apple Metal Acceleration",
description:
"Enable Apple Metal acceleration for faster transcription on Apple Silicon Macs",
default: true,
category: "advanced",
});
}
return options;
}
async validateOptions(
options: Record<string, any>,
): Promise<{ valid: boolean; errors: string[] }> {
const errors: string[] = [];
if (options.model) {
const validModels =
this.getSchema()
.find((opt) => opt.key === "model")
?.options?.map((opt) => opt.value) || [];
if (!validModels.includes(options.model)) {
errors.push(`Invalid model: ${options.model}`);
}
}
if (options.threads !== undefined) {
const threads = Number(options.threads);
if (isNaN(threads) || threads < 1 || threads > 16) {
errors.push("Thread count must be between 1 and 16");
}
}
if (
options.useCoreML !== undefined &&
typeof options.useCoreML !== "boolean"
) {
errors.push("Apple Metal acceleration must be true or false");
}
// Validate prompt option - no specific validation needed, just check it's a string
if (options.prompt !== undefined && typeof options.prompt !== "string") {
errors.push("Prompt must be a string");
}
if (
options.runOnAll !== undefined &&
typeof options.runOnAll !== "boolean"
) {
errors.push("Process all audio together must be true or false");
}
return { valid: errors.length === 0, errors };
}
async onActivated(uiFunctions?: PluginUIFunctions): Promise<void> {
this.setActive(true);
try {
// Initialize useCoreML from options
this.useCoreML =
this.options.useCoreML !== undefined
? this.options.useCoreML
: this.isAppleSilicon;
this.resolvedBinaryPath = this.getBinaryPath(true);
// Update activation criteria based on runOnAll option
const runOnAll =
this.options.runOnAll !== undefined
? this.options.runOnAll
: (this.getSchema().find((opt) => opt.key === "runOnAll")?.default ??
false);
this.setActivationCriteria({
runOnAll,
skipTransformation: false,
});
// Get model from stored options (unified plugin system), fallback to default
const modelName =
this.options.model ||
this.getSchema().find((opt) => opt.key === "model")?.default ||
"ggml-base.en.bin";
const modelPath = join(this.config.getModelsDir(), modelName);
if (!existsSync(modelPath)) {
const error = `Model ${modelName} not found. Please download it first.`;
this.setError(error);
throw new Error(error);
}
// Update the model path with the correct model
this.modelPath = modelPath;
this.setError(null);
console.log(
`Whisper.cpp plugin activated with model: ${modelName}, runOnAll: ${runOnAll}`,
);
// Start warmup loop and run initial warmup
this.startWarmupLoop();
this.runWarmupIfIdle();
} catch (error) {
this.setActive(false);
throw error;
}
}
async initialize(): Promise<void> {
this.setLoadingState(true, "Initializing Whisper.cpp plugin...");
try {
// Only verify binary is available - don't check models here
const available = await this.isBinaryAvailable();
if (!available) {
throw new Error("Whisper.cpp binary not found or not executable");
}
this.setInitialized(true);
this.setLoadingState(false);
console.log("Whisper.cpp plugin initialized successfully");
} catch (error) {
this.setError(`Whisper.cpp initialization failed: ${error}`);
this.setLoadingState(false);
throw error;
}
}
async onDeactivate(): Promise<void> {
await super.onDeactivate();
this.stopWarmupLoop();
}
async listData(): Promise<
Array<{ name: string; description: string; size: number; id: string }>
> {
const dataItems: Array<{
name: string;
description: string;
size: number;
id: string;
}> = [];
try {
const modelsDir = this.config.getModelsDir();
// List downloaded models
if (existsSync(modelsDir)) {
const files = readdirSync(modelsDir);
for (const file of files) {
const modelPath = join(modelsDir, file);
try {
if (file.endsWith(".bin")) {
const stats = require("fs").statSync(modelPath);
dataItems.push({
name: file.replace(".bin", ""),
description: `Whisper.cpp model file`,
size: stats.size,
id: `model:${file}`,
});
} else if (file.endsWith(".mlmodelc")) {
const dirSize =
FileSystemService.calculateDirectorySize(modelPath);
dataItems.push({
name: file,
description: `Whisper.cpp CoreML model`,
size: dirSize,
id: `model:${file}`,
});
}
} catch (error) {
console.warn(`Failed to stat model file ${file}:`, error);
}
}
}
// List temp files
if (existsSync(this.tempDir)) {
const tempFiles = readdirSync(this.tempDir);
for (const tempFile of tempFiles) {
const tempPath = join(this.tempDir, tempFile);
try {
const stats = require("fs").statSync(tempPath);
dataItems.push({
name: tempFile,
description: `Temporary audio file`,
size: stats.size,
id: `temp:${tempFile}`,
});
} catch (error) {
console.warn(`Failed to stat temp file ${tempFile}:`, error);
}
}
}
// List secure storage keys
const secureKeys = await this.listSecureKeys();
for (const key of secureKeys) {
dataItems.push({
name: key,
description: `Secure storage item`,
size: 0,
id: `secure:${key}`,
});
}
} catch (error) {
console.warn("Failed to list Whisper.cpp plugin data:", error);
}
return dataItems;
}
async deleteDataItem(id: string): Promise<void> {
const [type, identifier] = id.split(":", 2);
try {
switch (type) {
case "model":
const modelPath = join(this.config.getModelsDir(), identifier);
if (existsSync(modelPath)) {
const stats = require("fs").statSync(modelPath);
if (stats.isDirectory()) {
FileSystemService.deleteDirectory(modelPath);
console.log(`Deleted model directory: ${identifier}`);
} else {
require("fs").unlinkSync(modelPath);
console.log(`Deleted model file: ${identifier}`);
}
}
break;
case "temp":
const tempPath = join(this.tempDir, identifier);
if (existsSync(tempPath)) {
require("fs").unlinkSync(tempPath);
console.log(`Deleted temp file: ${identifier}`);
}
break;