Spaces:
Running
Running
File size: 11,371 Bytes
022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 022e8a2 f7fbf77 |
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 |
import {
// VAD
AutoModel,
// LLM
AutoTokenizer,
AutoModelForCausalLM,
TextStreamer,
InterruptableStoppingCriteria,
// Speech recognition
Tensor,
pipeline,
} from "@huggingface/transformers";
import { KokoroTTS, TextSplitterStream } from "kokoro-js";
import {
MAX_BUFFER_DURATION,
INPUT_SAMPLE_RATE,
SPEECH_THRESHOLD,
EXIT_THRESHOLD,
SPEECH_PAD_SAMPLES,
MAX_NUM_PREV_BUFFERS,
MIN_SILENCE_DURATION_SAMPLES,
MIN_SPEECH_DURATION_SAMPLES,
} from "./constants";
// WebGPU availability check - fail fast
if (!navigator.gpu) {
self.postMessage({
type: "error",
error: new Error("WebGPU not supported. This app requires Chrome 113+, Edge 113+, or Chrome Canary with WebGPU enabled.")
});
throw new Error("WebGPU not available");
}
// TTS Configuration
const model_id = "onnx-community/Kokoro-82M-v1.0-ONNX";
let voice;
const tts = await KokoroTTS.from_pretrained(model_id, {
dtype: "fp16", // Keep fp16 for memory efficiency
device: "webgpu",
}).catch((error) => {
self.postMessage({ error: new Error(`TTS loading failed: ${error.message}`) });
throw error;
});
const device = "webgpu";
self.postMessage({ type: "info", message: `Using device: "${device}"` });
self.postMessage({
type: "info",
message: "Loading models...",
duration: "until_next",
});
// Load VAD model
const silero_vad = await AutoModel.from_pretrained(
"onnx-community/silero-vad",
{
config: { model_type: "custom" },
dtype: "fp32",
},
).catch((error) => {
self.postMessage({ error: new Error(`VAD loading failed: ${error.message}`) });
throw error;
});
// Whisper configuration
const DEVICE_DTYPE_CONFIGS = {
webgpu: {
encoder_model: "fp32",
decoder_model_merged: "fp32",
},
wasm: {
encoder_model: "fp32",
decoder_model_merged: "q8",
},
};
const transcriber = await pipeline(
"automatic-speech-recognition",
"onnx-community/whisper-base",
{
device,
dtype: DEVICE_DTYPE_CONFIGS[device],
// Specify language to avoid warnings
language: "en",
task: "transcribe",
},
).catch((error) => {
self.postMessage({ error: new Error(`Whisper loading failed: ${error.message}`) });
throw error;
});
// Warm up the transcriber
await transcriber(new Float32Array(INPUT_SAMPLE_RATE));
// LLM Configuration - Split tokenizer and model sources
const TOKENIZER_MODEL_ID = "Qwen/Qwen3-1.7B"; // Original repo has tokenizer
const ONNX_MODEL_ID = "onnx-community/Qwen3-1.7B-ONNX"; // ONNX weights
// Load tokenizer from original repo
const tokenizer = await AutoTokenizer.from_pretrained(TOKENIZER_MODEL_ID).catch((error) => {
self.postMessage({ error: new Error(`Tokenizer loading failed: ${error.message}`) });
throw error;
});
// Load ONNX model weights
const llm = await AutoModelForCausalLM.from_pretrained(ONNX_MODEL_ID, {
dtype: "q4f16",
device: "webgpu",
// Add model-specific config for Qwen3
model_config: {
use_cache: true,
attention_bias: false,
}
}).catch((error) => {
self.postMessage({ error: new Error(`LLM loading failed: ${error.message}`) });
throw error;
});
// System prompt optimized for conversational AI
const SYSTEM_MESSAGE = {
role: "system",
content:
"You're a helpful and conversational voice assistant. Keep your responses short, clear, and casual. Focus on being natural and engaging in conversation.",
};
// Warm up the LLM
await llm.generate({ ...tokenizer("x"), max_new_tokens: 1 });
// Conversation state
let messages = [SYSTEM_MESSAGE];
let past_key_values_cache;
let stopping_criteria;
const MAX_CONTEXT_MESSAGES = 20; // Prevent unbounded memory growth
// Send ready signal with available voices
self.postMessage({
type: "status",
status: "ready",
message: "Ready!",
voices: tts.voices,
});
// Audio processing state
const BUFFER = new Float32Array(MAX_BUFFER_DURATION * INPUT_SAMPLE_RATE);
let bufferPointer = 0;
// VAD state
const sr = new Tensor("int64", [INPUT_SAMPLE_RATE], []);
let state = new Tensor("float32", new Float32Array(2 * 1 * 128), [2, 1, 128]);
// Recording state
let isRecording = false;
let isPlaying = false;
/**
* Perform Voice Activity Detection (VAD)
* @param {Float32Array} buffer The new audio buffer
* @returns {Promise<boolean>} `true` if the buffer is speech, `false` otherwise.
*/
async function vad(buffer) {
const input = new Tensor("float32", buffer, [1, buffer.length]);
const { stateN, output } = await silero_vad({ input, sr, state });
state = stateN;
const isSpeech = output.data[0];
return (
isSpeech > SPEECH_THRESHOLD ||
(isRecording && isSpeech >= EXIT_THRESHOLD)
);
}
/**
* Handle speech-to-speech pipeline
* @param {Float32Array} buffer The audio buffer
* @param {Object} data Additional timing data
*/
const speechToSpeech = async (buffer, data) => {
isPlaying = true;
try {
// 1. Transcribe audio
const transcription = await transcriber(buffer);
const text = transcription.text?.trim() || "";
if (!text || text === "[BLANK_AUDIO]") {
isPlaying = false;
return;
}
// Add user message
messages.push({ role: "user", content: text });
// Manage context window
if (messages.length > MAX_CONTEXT_MESSAGES) {
messages = [SYSTEM_MESSAGE, ...messages.slice(-(MAX_CONTEXT_MESSAGES - 1))];
past_key_values_cache = null; // Reset cache when context changes
}
// Set up TTS streaming
const splitter = new TextSplitterStream();
const stream = tts.stream(splitter, { voice });
// Stream TTS output
(async () => {
try {
for await (const { text, phonemes, audio } of stream) {
self.postMessage({ type: "output", text, result: audio });
}
} catch (error) {
console.error("TTS streaming error:", error);
}
})();
// 2. Generate LLM response
const inputs = tokenizer.apply_chat_template(messages, {
add_generation_prompt: true,
return_dict: true,
// Qwen3 specific - disable thinking mode for conversational use
enable_thinking: false,
});
const streamer = new TextStreamer(tokenizer, {
skip_prompt: true,
skip_special_tokens: true,
callback_function: (text) => {
splitter.push(text);
},
token_callback_function: () => {},
});
stopping_criteria = new InterruptableStoppingCriteria();
// Generate with appropriate settings for Qwen3
const { past_key_values, sequences } = await llm.generate({
...inputs,
past_key_values: past_key_values_cache,
// Qwen3 optimal settings for non-thinking mode
do_sample: true,
temperature: 0.7,
top_p: 0.8,
top_k: 20,
max_new_tokens: 512, // Keep responses concise for voice
streamer,
stopping_criteria,
return_dict_in_generate: true,
// Ensure proper EOS handling for Qwen3
eos_token_id: [151643, 151645],
pad_token_id: tokenizer.pad_token_id,
});
past_key_values_cache = past_key_values;
// Close the TTS stream
splitter.close();
// Decode and store assistant response
const decoded = tokenizer.batch_decode(
sequences.slice(null, [inputs.input_ids.dims[1], null]),
{ skip_special_tokens: true },
);
messages.push({ role: "assistant", content: decoded[0] });
} catch (error) {
console.error("Speech-to-speech error:", error);
self.postMessage({
type: "error",
error: new Error(`Processing failed: ${error.message}`)
});
} finally {
isPlaying = false;
}
};
// Audio buffer management
let postSpeechSamples = 0;
let prevBuffers = [];
const resetAfterRecording = (offset = 0) => {
self.postMessage({
type: "status",
status: "recording_end",
message: "Transcribing...",
duration: "until_next",
});
BUFFER.fill(0, offset);
bufferPointer = offset;
isRecording = false;
postSpeechSamples = 0;
};
const dispatchForTranscriptionAndResetAudioBuffer = (overflow) => {
const now = Date.now();
const end = now - ((postSpeechSamples + SPEECH_PAD_SAMPLES) / INPUT_SAMPLE_RATE) * 1000;
const start = end - (bufferPointer / INPUT_SAMPLE_RATE) * 1000;
const duration = end - start;
const overflowLength = overflow?.length ?? 0;
// Prepare padded buffer
const buffer = BUFFER.slice(0, bufferPointer + SPEECH_PAD_SAMPLES);
const prevLength = prevBuffers.reduce((acc, b) => acc + b.length, 0);
const paddedBuffer = new Float32Array(prevLength + buffer.length);
let offset = 0;
for (const prev of prevBuffers) {
paddedBuffer.set(prev, offset);
offset += prev.length;
}
paddedBuffer.set(buffer, offset);
// Process speech
speechToSpeech(paddedBuffer, { start, end, duration });
// Handle overflow
if (overflow) {
BUFFER.set(overflow, 0);
}
resetAfterRecording(overflowLength);
};
// Message handler
self.onmessage = async (event) => {
const { type, buffer } = event.data;
// Block audio during playback
if (type === "audio" && isPlaying) return;
switch (type) {
case "start_call": {
const name = tts.voices[voice ?? "af_heart"]?.name ?? "Heart";
greet(`Hey there, my name is ${name}! How can I help you today?`);
return;
}
case "end_call":
messages = [SYSTEM_MESSAGE];
past_key_values_cache = null;
// Fall through to interrupt
case "interrupt":
stopping_criteria?.interrupt();
return;
case "set_voice":
voice = event.data.voice;
return;
case "playback_ended":
isPlaying = false;
return;
}
// Process audio buffer
const wasRecording = isRecording;
const isSpeech = await vad(buffer);
if (!wasRecording && !isSpeech) {
// Queue non-speech buffers for padding
if (prevBuffers.length >= MAX_NUM_PREV_BUFFERS) {
prevBuffers.shift();
}
prevBuffers.push(buffer);
return;
}
const remaining = BUFFER.length - bufferPointer;
if (buffer.length >= remaining) {
// Buffer overflow - trigger transcription
BUFFER.set(buffer.subarray(0, remaining), bufferPointer);
bufferPointer += remaining;
const overflow = buffer.subarray(remaining);
dispatchForTranscriptionAndResetAudioBuffer(overflow);
return;
} else {
// Add to buffer
BUFFER.set(buffer, bufferPointer);
bufferPointer += buffer.length;
}
if (isSpeech) {
if (!isRecording) {
self.postMessage({
type: "status",
status: "recording_start",
message: "Listening...",
duration: "until_next",
});
}
isRecording = true;
postSpeechSamples = 0;
return;
}
postSpeechSamples += buffer.length;
// Check for end of speech
if (postSpeechSamples < MIN_SILENCE_DURATION_SAMPLES) {
return;
}
if (bufferPointer < MIN_SPEECH_DURATION_SAMPLES) {
resetAfterRecording();
return;
}
dispatchForTranscriptionAndResetAudioBuffer();
};
// Greeting function
function greet(text) {
isPlaying = true;
const splitter = new TextSplitterStream();
const stream = tts.stream(splitter, { voice });
(async () => {
for await (const { text: chunkText, audio } of stream) {
self.postMessage({ type: "output", text: chunkText, result: audio });
}
})();
splitter.push(text);
splitter.close();
messages.push({ role: "assistant", content: text });
} |