-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstt-worker.js
More file actions
201 lines (172 loc) · 5.04 KB
/
stt-worker.js
File metadata and controls
201 lines (172 loc) · 5.04 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
import {
env,
AutoTokenizer,
AutoProcessor,
WhisperForConditionalGeneration,
TextStreamer,
full,
} from "@huggingface/transformers";
const MAX_NEW_TOKENS = 64;
const isAndroid = /Android/i.test(navigator.userAgent || "");
// Configure backends for Android
env.backends ??= {};
env.backends.webgpu ??= {};
env.backends.onnx ??= {};
env.backends.onnx.webgpu ??= {};
env.backends.onnx.wasm ??= {};
if (isAndroid) {
// transformers.js kernels
env.backends.webgpu.preferFloat16 = false;
// onnxruntime-web WebGPU EP
env.backends.onnx.webgpu.enableMixedPrecision = false;
env.backends.onnx.webgpu.preferredOutputType = 'float32';
// WASM threads optimization
env.backends.onnx.wasm.numThreads = Math.min(4, (navigator.hardwareConcurrency || 4));
}
/**
* This class uses the Singleton pattern to ensure that only one instance of the model is loaded.
*/
class AutomaticSpeechRecognitionPipeline {
static model_id = "onnx-community/whisper-base"; // Use HF models for tokenizer/processor, local for model weights
static tokenizer = null;
static processor = null;
static model = null;
static async getInstance(progress_callback = null) {
// Load tokenizer and processor from HF (these are small)
this.tokenizer ??= AutoTokenizer.from_pretrained(this.model_id, {
progress_callback,
});
this.processor ??= AutoProcessor.from_pretrained(this.model_id, {
progress_callback,
});
// Try to use local models if available, fallback to HF
this.model ??= WhisperForConditionalGeneration.from_pretrained(
this.model_id,
{
dtype: {
encoder_model: "fp32",
decoder_model_merged: "q4",
},
device: "webgpu",
progress_callback,
},
);
return Promise.all([this.tokenizer, this.processor, this.model]);
}
static dispose() {
try { this.model?.dispose?.(); } catch {}
this.model = null;
this.tokenizer = null;
this.processor = null;
}
}
let processing = false;
async function generate({ audio, language }) {
if (processing) return;
processing = true;
self.postMessage({ status: "start" });
try {
const [tokenizer, processor, model] =
await AutomaticSpeechRecognitionPipeline.getInstance();
let startTime;
let numTokens = 0;
let tps;
const token_callback_function = () => {
startTime ??= performance.now();
if (numTokens++ > 0) {
tps = (numTokens / (performance.now() - startTime)) * 1000;
}
};
const callback_function = (output) => {
self.postMessage({
status: "update",
output,
tps,
numTokens,
});
};
const streamer = new TextStreamer(tokenizer, {
skip_prompt: true,
skip_special_tokens: true,
callback_function,
token_callback_function,
});
const inputs = await processor(audio);
const outputs = await model.generate({
...inputs,
max_new_tokens: isAndroid ? 32 : MAX_NEW_TOKENS,
language,
streamer,
});
const decoded = tokenizer.batch_decode(outputs, {
skip_special_tokens: true,
});
self.postMessage({ status: "complete", output: decoded });
} catch (err) {
console.error("STT generate error:", err);
self.postMessage({ status: "error", data: String(err?.message || err) });
} finally {
processing = false;
}
}
async function load() {
self.postMessage({
status: "loading",
data: "Loading STT model...",
});
try {
await AutomaticSpeechRecognitionPipeline.getInstance((x) => {
self.postMessage(x);
});
self.postMessage({
status: "loading",
data: "Compiling shaders and warming up STT model...",
});
const [, , model] = await AutomaticSpeechRecognitionPipeline.getInstance();
await model.generate({
input_features: full([1, 80, 3000], 0.0),
max_new_tokens: 1,
});
self.postMessage({ status: "ready" });
} catch (e) {
console.error("STT load error:", e);
self.postMessage({ status: "error", data: String(e?.message || e) });
}
}
async function warmup() {
try {
// Reset processing state first
processing = false;
const [tokenizer, processor, model] = await AutomaticSpeechRecognitionPipeline.getInstance();
// Run model with dummy input to warm up again
await model.generate({
input_features: full([1, 80, 3000], 0.0),
max_new_tokens: 1,
});
self.postMessage({ status: "ready" });
} catch (error) {
console.error('Warmup error:', error);
self.postMessage({ status: "error", data: error.message });
}
}
// Listen for messages from the main thread
self.addEventListener("message", async (e) => {
const { type, data } = e.data;
switch (type) {
case "load":
load();
break;
case "generate":
generate(data);
break;
case "reset":
// Reset processing state to clear working memory
console.log('Resetting STT worker...');
processing = false;
AutomaticSpeechRecognitionPipeline.dispose();
break;
case "warmup":
warmup();
break;
}
});