-
Notifications
You must be signed in to change notification settings - Fork 21
/
whisper_worker.js
4092 lines (3110 loc) · 145 KB
/
whisper_worker.js
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 {
pipeline,
env,
AutoTokenizer,
AutoProcessor,
AutoModel,
AutoModelForAudioFrameClassification,
TextStreamer,
//WhisperTextStreamer,
WhisperForConditionalGeneration,
full,
} from './tjs/transformers.min.js';
const MAX_NEW_TOKENS = 64; // not used?
env.allowLocalModels = false;
env.allowRemoteModels = true;
env.useBrowserCache = true;
self.device = 'webgpu';
let gpu_checked = false;
env.backends.onnx.wasm.proxy = false;
self.supports_web_gpu16 = false;
self.supports_web_gpu32 = false;
//self.output_so_far = '';
self.task = null;
let processing = false;
self.busy_transcribing = false;
self.busy_loading = false;
self.busy_disposing_models = false;
self.was_disposed = false;
self.segmentation_loaded = null;
self.quantized = null;
self.current_model_preferences = null;
self.current_asr_model_id = null;
self.is_mobile = true;
self.segmentation_preferences = {};
self.speaker_translation = 'Speaker';
self.fingerprints = [];
self.fingerprint_matches = {};
let next_fingerprints_id = 1;
self.matches = [];
let recorded_audio_length = 0;
let total_duration_time = null;
self.interrupted = false;
self.start_time = null;
self.similarity_threshold = 0.965;
self.perfect_simillarity_threshold = 0.975;
self.minimal_verification_duration = 2000;
let segment_index = 0;
self.last_used_preferences = null;
self.last_used_segmentation = null;
let PER_DEVICE_CONFIG = {
webgpu: {
dtype: {
encoder_model: 'fp32',
decoder_model_merged: 'q4', // 'fp32', //
},
device: 'webgpu',
},
wasm: {
dtype: 'q8',
device: 'wasm',
},
};
/*
// From Transformers.js V2 demo: https://github.com/xenova/whisper-web/blob/main/src/utils/Constants.ts
export default {
SAMPLING_RATE: 16000,
DEFAULT_AUDIO_URL: `https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/${
isMobileOrTablet ? "jfk" : "ted_60_16k"
}.wav`,
DEFAULT_MODEL: "Xenova/whisper-tiny",
DEFAULT_SUBTASK: "transcribe",
DEFAULT_LANGUAGE: "english",
DEFAULT_QUANTIZED: isMobileOrTablet,
DEFAULT_MULTILINGUAL: false,
};
*/
function delay(millisec) {
return new Promise(resolve => {
setTimeout(() => { resolve('') }, millisec);
})
}
// Define model factories
// Ensures only one model is created of each type
class PipelineFactory {
//class AutomaticSpeechRecognitionPipelineFactory {
//static task = null;
static task = null; //"automatic-speech-recognition";
static model = null; //'onnx-community/whisper-small.en_timestamped';
static instance = null;
//static model_id = 'onnx-community/whisper-tiny.en_timestamped';
static quantized = null;
constructor(tokenizer, model, quantized) {
this.tokenizer = tokenizer;
this.model = model;
//this.quantized = quantized;
}
static instance_exists(){
//console.log("returning if instance exists");
return this.instance != null;
}
static set_to_null(var_to_null=null) {
if(typeof var_to_null == 'string' && typeof this[var_to_null] != 'undefined'){
this[var_to_null] = null;
//console.log("WHISPER WORKER: ASR PipelineFactory: set_to_null: ", var_to_null);
}
}
static async getInstance(progress_callback=null, model_id=null, quantized=null, preferences={}) {
//console.log("ASR: getInstance: model_id,quantized,preferences: ", model_id, quantized, preferences);
if(typeof model_id == 'string'){
//console.log("using provided model_id string: ", model_id);
this.model = model_id;
}
else if(typeof this.model != 'string'){
this.model = 'onnx-community/whisper-tiny.en_timestamped';
}
this.quantized = quantized;
// TODO DEBUG
this.quantized = true;
//this.model = model_id;
//this.quantized = quantized;
//console.log("\n\npipelineFactory: getInstance");
//console.log("- this.task: ", this.task);
//console.log("- this.model_id: ", this.model_id);
//console.log("- this.model: ", this.model);
//console.log("- this.quantized: ", this.quantized);
//console.log("- self.device: ", self.device);
//this.model = 'onnx-community/whisper-large-v3-turbo';
if (this.instance === null) {
if(self.device == 'webgpu'){
this.instance = pipeline(this.task, this.model, {
"dtype": {
"encoder_model": "fp32",
"decoder_model_merged": "q4" // "fp32" //
},
"device": "webgpu",
"quantized":true,
progress_callback
});
}
else{
this.instance = pipeline(this.task, this.model, {
"dtype": "q8",
"device": "wasm",
progress_callback
});
}
}
else{
//console.log("ASR pipeline getInstance: this.instance already existed: ", this.instance);
}
//console.log("PipelineFactory: returning this.instance: ", this.instance);
return this.instance;
}
}
class AutomaticSpeechRecognitionPipelineFactory extends PipelineFactory {
static task = "automatic-speech-recognition";
static model = null;
static quantized = null;
}
class SegmentationSingleton {
static instance = null;
static segmentation_model_id = 'onnx-community/pyannote-segmentation-3.0';
static segmentation_instance = null;
static segmentation_processor = null;
static loaded_segmentation = false;
static verification_model_id = 'Xenova/wavlm-base-plus-sv'; // Xenova/wavlm-base-plus-sv
//static verification_model_id = 'onnx-community/wespeaker-voxceleb-resnet34-LM';
static verification_instance = null;
static verification_processor = null;
static instance_exists(){
return this.segmentation_instance != null;
}
static set_to_null(var_to_null=null){
if(typeof var_to_null == 'string' && typeof this[var_to_null] != 'undefined'){
this[var_to_null] = null;
//console.log("SegmentationSingleton: set_to_null: ", var_to_null);
}
}
//static async getInstance(progress_callback=null,model_name='onnx-community/whisper-base_timestamped',preferences={},load_segmentation=true) {
static async getInstance(progress_callback=null,preferences={}) {
//console.log("Whisper_worker: SegmentationSingleton: getInstance");
if(self.is_mobile){
//console.log("mobile, so setting quantized to true for segmentation AI's");
preferences['quantized'] = true;
}
this.loaded_segmentation = true
//console.log("segmentationSingleton: creating segmentation instances");
this.segmentation_processor ??= AutoProcessor.from_pretrained(this.segmentation_model_id, {
...preferences,
progress_callback,
});
this.segmentation_instance ??= AutoModelForAudioFrameClassification.from_pretrained(this.segmentation_model_id, {
// NOTE: WebGPU is not currently supported for this model
// See https://github.com/microsoft/onnxruntime/issues/21386
device: 'wasm',
//dtype: 'fp32',
dtype: 'q8',
...preferences,
progress_callback,
});
if(this.verification_model_id.endsWith('wespeaker-voxceleb-resnet34-LM')){
self.similarity_threshold = 0.5;
self.perfect_simillarity_threshold = 0.7;
}
else{
self.similarity_threshold = 0.95;
self.perfect_simillarity_threshold = 0.98;
}
this.verification_processor ??= AutoProcessor.from_pretrained(this.verification_model_id, {
device: 'wasm',
dtype: 'fp32',
//device: 'webgpu',
//dtype: 'q8',
...preferences,
progress_callback,
});
this.verification_instance ??= AutoModel.from_pretrained(this.verification_model_id, {
device: 'wasm',
dtype: 'fp32',
//device: 'webgpu',
//dtype: 'q8',
...preferences,
progress_callback,
});
return Promise.all([this.segmentation_processor, this.segmentation_instance, this.verification_processor, this.verification_instance]);
}
}
const transcribo = async (message,preload=false) => {
//console.log("in transcribo. preload: ", preload);
//console.log("whisper_worker: in new transcribo function. message,preload: ", message, preload);
// Storage for chunks to be processed. Initialise with an empty chunk.
const chunks = [];
let output = null;
let tps;
try{
if(typeof message.model != 'string'){
console.error("transcribe: message.model was not a string!");
return null;
}
//console.log("transcribo: message.model: ", message.model);
self.current_asr_model_id = message.model;
if(typeof message.options == 'undefined'){
console.error("transcribe: message.options was undefined!");
return null;
}
let asr_options = JSON.parse(JSON.stringify(message.options));
//console.log("transcribe: initial asr_options: ", JSON.stringify(asr_options,null,2));
/*
let asr_options = {
// Greedy
top_k: 0,
do_sample: false,
// Sliding window
chunk_length_s:20,
stride_length_s:3,
// Language and task
//language:'en',
//language:'english',
//task: "transcribe",
// Return timestamps
return_timestamps: 'word',
force_full_sequences: false,
// Callback functions
//streamer, // after each generation step
}
*/
const p = AutomaticSpeechRecognitionPipelineFactory;
//console.log("whisper_worker: transcribo: p.model: ", p.model);
if (p.model !== message.model){
// Invalidate model if different
//console.warn("whisper_worker: need to load a new ASR model: ", message.model);
p.model = message.model;
await delay(10);
if (p.instance !== null) {
console.warn("whisper_worker: disposing of old ASR instance first");
try{
(await p.getInstance()).dispose();
}
catch (err){
console.error("whisper_worker: notice only: caught error trying to dispose of old model first: ", err);
}
p.instance = null;
}
await delay(10);
}
//console.log("whisper_worker: transcribo: creating transcribot. message.model: ", message.model);
// Load transcribot model
const transcribot = await p.getInstance((data) => {
//console.log("whisper_worker: transcribot: got data: ", data);
self.postMessage(data);
}, message.model);
//console.warn("\n\nTRANSCRIBER CREATED SUCCESFULLY. preload: ", preload, "\n\n");
self.postMessage({
status: "transcriber_created",
});
//console.log("transcribot loaded?: ", transcribot);
//console.log("transcribot model: ", transcribot.tokenizer);
//console.log("transcribot model: ", transcribot.model);
//console.log("transcribot processor: ", transcribot.processor);
if(preload){
//console.log("Transcribe: preloading, so stopping here, and returning true");
// Run model with dummy input to compile shaders. Only needed if running via WebGPU
//await transcribot.model.generate({
// input_features: full([1, 80, 3000], 0.0),
// max_new_tokens: 1,
//});
return true
}
if(typeof message.task == 'undefined' || message.task == null || typeof message.task.recorded_audio == 'undefined'){
console.error("transcribo: NO AUDIO!");
return null;
}
const time_precision =
transcribot.processor.feature_extractor.config.chunk_length /
transcribot.model.config.max_source_positions;
//console.log("transcribo: time_precision: ", time_precision);
// TODO: Storage for fully-processed and merged chunks
// let decoded_chunks = [];
let chunk_count = 0;
let start_time;
let num_tokens = 0;
//console.log("creating streamer next. transcribot.tokenizer: ", transcribot.tokenizer);
if(typeof transcribot.tokenizer !== 'function'){
console.error("transcribot.tokenizer was invalid: ", transcribot.tokenizer);
//asr_options['streamer'] = streamer;
}
function streamCallback(value){
//console.error("GOT WHISPER STREAM CALLBACK: ", typeof value, value);
//previous_stream_stamp = stream_stamp;
self.postMessage({
task_index: task.index,
task_parent_index: task.parent_index,
task_assistant: task.assistant,
task_destination: task.destination,
status: "stream",
content: value,
});
}
const streamer = new TextStreamer(transcribot.tokenizer, {
skip_prompt: true,
skip_special_tokens: true,
callback_function:streamCallback,
});
/*
// For the WhisperTextStreamer
let chunk_offset = 0;
const streamer = new WhisperTextStreamer(transcribot.tokenizer, {
time_precision,
on_chunk_start: (x) => {
//console.log("WHISPER_WORKER: STREAM: chunk start: ", x);
const offset = (asr_options['chunk_length_s'] - asr_options['stride_length_s']) * chunk_count;
chunk_offset = offset;
//console.log("WHISPER_WORKER: STREAM: chunk offset: ", offset);
chunks.push({
text: "",
timestamp: [offset + x, null],
finalised: false,
offset,
});
},
token_callback_function: (x) => {
//console.log("WHISPER_WORKER: STREAM: chunk callback: ", x);
start_time ??= performance.now();
if (num_tokens++ > 0) {
tps = (num_tokens / (performance.now() - start_time)) * 1000;
}
},
callback_function: (x) => {
if (chunks.length === 0) return;
//console.log("WHISPER_WORKER: STREAM: + chunk: -->" + x + "<--");
// Append text to the last chunk
chunks.at(-1).text += x;
if(self.task != null && typeof self.task.index == 'number' && typeof self.task.assistant == 'string'){
self.postMessage({
task_index: task.index,
task_parent_index: task.parent_index,
task_assistant: task.assistant,
task_destination: task.destination,
status: "stream",
content: x,
});
}
//++chunk_count;
},
on_chunk_end: (x) => {
//console.log("whisper: stream: on chunk end. x: ", x);
const current = chunks.at(-1);
current.timestamp[1] = x + current.offset;
current.finalised = true;
},
on_finalize: () => {
//console.log("whisper: stream: on chunk finalize");
start_time = null;
num_tokens = 0;
++chunk_count;
},
});
*/
//console.log("asr_options: ", JSON.stringify(asr_options,null,4));
self.postMessage({ status: 'pipeline_ready' }); // technically only ASR could be loaded at this point
// Actually run transcription
output = await transcribot(message.task.recorded_audio, {
...asr_options,
streamer,
}).catch((error) => {
console.error("caught error in transcribot: ", error);
self.postMessage({
status: "error",
data: error,
});
return null;
});
//console.log("whisper_worker: RAW ASR output: ", output);
// SANITY CHECKS for Dutch language
if(output != null){
if(typeof output.text == 'string' && output.text.length < 24 && output.text.indexOf('TV GELDERLAND') != -1){
output = null;
}
else if(typeof output.text == 'string' && output.text == ' MUZIEK.'){ // TODO why filter out music? Or is this part of the TV Gelderlnd weirdness?
output = null;
}
else if(typeof output.text == 'string' && output.text.startsWith('!!!!!!!!!!!!!!!!!')){
self.postMessage({
status: "exclamation_marks",
});
output = null;
}
}
// Check if the words are sensible. In very rare occasions Whisper freaks out
if(output != null && typeof output.chunks != 'undefined' && output.chunks.length > 40){
let words_spotted = [];
for(let w = 0; w < output.chunks.length; w++){
if(typeof output.chunks[w].text == 'string' && words_spotted.indexOf(output.chunks[w].text) == -1){
words_spotted.push(output.chunks[w].text);
}
}
if(words_spotted.length < output.chunks.length/10){
console.error("Whisper went haywire, creating looping output");
let unlooped_text = '';
let found_the_loop = false;
let maximum_trim = output.text.length;
let best_loop = null;
let max_test_length = Math.round(output.text.length / 3);
if(max_test_length > 100){
max_test_length = 100;
}
for(let q = output.text.length; q > max_test_length; --q){
//console.log("q:",q);
let loop_text = '';
let test_text = output.text.substr(0,q);
//console.log("test_text:", test_text);
for(let e = test_text.length - 1; e > Math.round(test_text.length / 3); --e){
//console.log(e,test_text.charAt(e));
//break
loop_text = test_text.charAt(e) + loop_text;
if(loop_text.length > 7){
const tester = test_text.substr(e - loop_text.length,loop_text.length);
//console.log("tester: ", tester, loop_text);
if(tester == loop_text){
//console.log("BINGO: ", loop_text);
if(output.text.indexOf(loop_text) < maximum_trim){
//console.log("Found an even better loop: ", loop_text);
best_loop = loop_text;
}
//found_the_loop = true;
break
}
}
}
}
if(best_loop != null){
output.text = output.text.substr(0,(output.text.indexOf(best_loop) + best_loop.length));
//console.log("Fixed un-looped output.text: ", output.text);
let remake = '';
if(typeof output.chunks != 'undefined'){
for(let w = 0; w < output.chunks.length; w++){
remake += output.chunks[w] + ' ';
//console.log("remake: ", remake);
if(remake.length > output.text.length){
//console.log("remake: ", remake);
output.chunks.splice(w+1,output.chunks.length);
console.error("Fixed un-looped output.chunks: ", output.chunks);
break
}
}
}
}
else{
console.error("COULD NOT FIX WHISPER GONE HAYWIRE");
output = null;
}
}
}
if(self.interrupted){
self.postMessage({
task: task,
status: "interrupted",
});
return null
}
}
catch(err){
console.error("caught general error in transcribo: ", err);
self.postMessage({
status: "error",
data: err,
});
return null;
}
await delay(10);
return output;
};
async function dispose(dispose_type='all') {
//console.log("whisper_worker: in dispose. dispose_type: ", dispose_type);
if(typeof dispose_type != 'string'){
console.eror("whisper_worker: invalid dispose_type: ", dispose_type);
return false
}
self.busy_disposing_models = true;
const s = SegmentationSingleton;
if( (dispose_type == 'segmentation' || dispose_type == 'all') && s.instance_exists() === true){
//console.log("whisper dispose: should indeed dispose segmentation");
const [segmentation_processor,segmentation_model,verification_processor,verification_model] = await s.getInstance(null,self.segmentation_preferences);
if(segmentation_processor != null && typeof segmentation_processor.dispose == 'function'){
//console.log("whisper_worker: dispose: disposing of segmentation_processor");
await segmentation_processor.dispose();
segmentation_processor = null;
}
if(segmentation_model != null && typeof segmentation_model.dispose == 'function'){
//console.log("whisper_worker: dispose: disposing of segmentation_model");
await segmentation_model.dispose();
}
if(verification_processor != null && typeof verification_processor.dispose == 'function'){
//console.log("whisper_worker: dispose: disposing of verification_processor");
await verification_processor.dispose();
}
if(verification_model != null && typeof verification_model.dispose == 'function'){
//console.log("whisper_worker: dispose: disposing of verification_model");
await verification_model.dispose();
}
s.set_to_null('segmentation_processor');
s.set_to_null('segmentation_model');
s.set_to_null('verification_processor');
s.set_to_null('verification_model');
//console.log("segmentation dispose should now be complete");
}
const p = AutomaticSpeechRecognitionPipelineFactory;
if( (dispose_type == 'asr' || dispose_type == 'all') && p.instance_exists() === true){
//console.log("whisper_worker: disposing the transcribot");
try{
(await p.getInstance()).dispose();
p.instance = null;
//console.log("whisper_worker: dispose: ASR should now be disposed");
}
catch(err){
console.error("whisper_worker: caught error trying to dispose of ASR: ", err);
}
}
self.busy_disposing_models = false;
//console.log("whisper_worker: dispose done: ", dispose_type);
return true
}
// deprecated
async function unload_segmentation() {
//console.log("whisper worker: in unload_segmentation (dispose segmentation)");
if(SegmentationSingleton.segmentation_exists() === false){
//console.log("whisper worker: unload_segmentation: segmentation hasn't been created yet");
return true;
}
await dispose('segmentation');
//console.log("unload_segmentation: done");
return null;
}
// MESSAGE LISTENER
addEventListener('message', async (event) => {
//console.log("WHISPER WEB WORKER: RECEIVED MESSAGE");
//console.log("WHISPER WEB WORKER: RECEIVED MESSAGE. event.data: ", event.data);
if(typeof event.data.action == 'string' && (event.data.action == 'delete_speakers' || event.data.action == 'delete_speaker' || event.data.action == 'set_speaker_name' || event.data.action == 'dispose' || event.data.action == 'interrupt')){
//console.log("whisper_worker: received action command: ", event.data.action);
if(event.data.action == 'dispose'){
//console.log("whisper worker: action: dispose");
//await dispose_models();
if(self.busy_disposing_models == false){
if(self.busy_transcribing){
console.warn("whisper_worker: dispose was called while the worker was busy");
self.interrupted = true;
}
try{
await dispose('all');
self.postMessage({
status: "disposed"
});
}
catch(err){
console.error("caught error trying to dispose whisper: ", err);
self.postMessage({
status: "disposed"
});
}
self.task = null;
}
else{
console.error("whisper_worker: already busy disposing");
}
}
else if(event.data.action == 'interrupt'){
//console.log("whisper worker: action: interrupt");
self.interrupted = true;
}
else if(event.data.action == 'delete_speakers'){
//console.log("whisper worker: action: delete_speakers");
reset_fingerprints();
}
else if(event.data.action == 'delete_speaker'){
if(typeof event.data.id == 'number' && typeof event.data.parent_index == 'number' && self.task != null && typeof self.task.parent_index == 'number' && self.task.parent_index == event.data.parent_index){
for(let f = 0; f < self.fingerprints.length; f++){
if(self.fingerprints[f].id == event.data.id){
self.fingerprints.splice(f,1);
self.postMessage({
status: "success",
message: "Deleted"
});
break
}
}
}
}
else if(event.data.action == 'set_speaker_name'){
if(self.task && typeof self.task.parent_index == 'number'){
//console.log("whisper_worker: received set_speaker_name. parent_index to match: ", self.task.parent_index);
}
else{
console.error("set_speaker_name: self.task was null, so no parent index to match with");
}
if(typeof event.data.id == 'number' && typeof event.data.speaker_name == 'string' && typeof event.data.parent_index == 'number'){
//console.log("whisper_worker: set_speaker_name: received valid input. self.fingerprints.length: ", self.fingerprints.length);
if( (self.task != null && typeof self.task.parent_index == 'number' && self.task.parent_index == event.data.parent_index) || self.task == null){
//console.log("whisper_worker: set_speaker_name: OK. self.task: ", self.task);
for(let f = 0; f < self.fingerprints.length; f++){
if(self.fingerprints[f].id == event.data.id){
//console.log("set_speaker_name: found the fingerprint");
if(event.data.speaker_name == ''){
//console.log("set_speaker_name: should delete the speaker_name from the fingerprint");
if(typeof self.fingerprints[f].speaker_name != 'undefined'){
delete self.fingerprints[f].speaker_name;
}
//self.fingerprints[f].speaker_name = self.speaker_translation + ' ' + self.fingerprints[f].id;
}
else{
self.fingerprints[f].speaker_name = event.data.speaker_name;
//console.log('set_speaker_name: self.fingerprints[f].speaker_name is now: ', self.fingerprints[f].speaker_name);
}
self.postMessage({
status: "success",
message: "Saved"
});
break
}
}
}
else{
console.error("set_speaker_name: event.data.parent_index and task parent_index did not match: ", typeof event.data.parent_index, event.data.parent_index, typeof self.task.parent_index, self.task.parent_index);
}
}
else{
console.error("set_speaker_name: invalid input");
}
}
return null
}
if(self.busy_disposing_models){
console.error("whisper worker: ignoring incoming message, busy disposing of models");
self.postMessage({
task: task,
status: "error",
error: "whisper was busy disposing of models",
});
return null
}
if(self.busy_loading){
console.error("whisper worker: incoming message, but busy loading. aborting");
self.postMessage({
task: task,
status: "warning",
error: "already busy loading",
});
return null
}
if(self.busy_transcribing){
console.error("whisper worker: incoming message, but already busy transcribing");
self.postMessage({
task: task,
status: "error",
error: "already busy transcribing",
});
return null
}
if(gpu_checked == false){
//console.log("whisper_worker: calling check_gpu");
gpu_checked = true;
await check_gpu();
}
self.segmentation_preferences = {};
if(typeof event.data.mobile == 'boolean'){
self.is_mobile = event.data.mobile;
}
//console.log("whisper_worker: self.is_mobile is now: ", self.is_mobile);
if(self.is_mobile){
self.segmentation_preferences['quantized'] = true;
}
if(typeof event.data.action == 'string'){
if(event.data.action == 'preload'){
//console.log("whisper worker: action: preload");
self.busy_loading = true;
self.postMessage({
status: "preloading"
});
try{
const preloaded = await preload(event.data);
//console.log("whisper_worker: preloaded: ", preloaded)
self.busy_loading = false;
if(typeof preloaded == 'boolean' && preloaded == true){
self.postMessage({
status: "preload_complete"
});
}
}
catch(err){
console.error("whisper_worker: caught error calling preload: ", err);
self.busy_loading = false;
self.postMessage({
status: "error",
error:"Caught error in whisper preload: " + err
});
}
}
return null
}
else if(typeof event.data.task != 'undefined'){
self.task = event.data.task;
self.interrupted = false;
let output = boss(event.data);
}
else{
self.postMessage({
status: "error",
error: "no (task) data in incoming message",
});
}
});
const boss = async (message) => {
//console.warn("whisper_worker: BOSS GOT THE MESSAGE: ", message);
let merged_snippets = null;
let transcript = null;