Use web speech api instead: import dynamicImportESM from…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Use web speech api instead: import dynamicImportESM from "../../common-utils/dynamic-import-esm.js";
export async function handleSpeechToText(app, plugin) {
try {
await app.context.replaceSelection(Loading...);
app.openSidebarEmbed(1, {openSpeechToText: true});
while (!(await plugin.isEmbedOpen(app))) {
await new Promise(resolve => setTimeout(resolve, 1000));
}
const pipeline = (await dynamicImportESM('@huggingface/transformers')).pipeline;
const speechPipe = await pipeline('automatic-speech-recognition', 'Xenova/whisper-tiny', {
dtype: 'q8',
device: 'wasm'
});
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
const mediaRecorder = new MediaRecorder(stream);
const audioContext = new AudioContext({ sampleRate: 16_000 });
await plugin.sendMessageToEmbed(app, 'speechtotext', 'ready');
let i = 0, transcribeResult = '', audioChunks = [], processing = false;
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
audioChunks.push(event.data);
processAudioChunks();
}
console.log('MediaRecorder data available.', event.data.size);
}
mediaRecorder.onstop = () => {
console.log('MediaRecorder stopped.');
processAudioChunks(); // Process any remaining audio chunks
}
const processAudioChunks = async () => {
if (audioChunks.length === 0) return;
while (processing) {
console.log('awaiting lock');
await new Promise(resolve => setTimeout(resolve, 1000));
}
processing = true;
const blob = new Blob(audioChunks, { type: mediaRecorder.mimeType });
console.log('audioChunks', audioChunks);
const fileReader = new FileReader();
fileReader.onloadend = async () => {
try {
const arrayBuffer = fileReader.result;
const decoded = await audioContext.decodeAudioData(arrayBuffer);
let audio = decoded.getChannelData(0);
const MAX_SAMPLES = 16_000 * 30; // 30 seconds * 16,000 samples per second is limit
if (audio.length > MAX_SAMPLES) { // Get first MAX_SAMPLES
audio = audio.slice(0, MAX_SAMPLES);
}
const result = await transcribe(speechPipe, audio);
transcribeResult += result.text;
console.log('transcribeResult', transcribeResult, 'result.text', result.text);
} catch (e) {console.error(e);}
// audioChunks = []; - fails to decode otherwise
processing = false;
}
fileReader.readAsArrayBuffer(blob);
}
mediaRecorder.start(5000);
console.log('Speech to Text app is processing');
while ((await plugin.isEmbedOpen(app))|| processing === true) {
await new Promise(resolve => setTimeout(resolve, 500));
await app.context.replaceSelection(transcribeResult.trim() === '' ?
'Say something...' : transcribeResult.trim());
i++;
}
if (mediaRecorder.state === "recording" || mediaRecorder.state === "paused") {
mediaRecorder.stop();
}
} catch (e) {
try { // Reset selection
await app.context.replaceSelection('');
} catch (e) {}
await plugin.sendMessageToEmbed(app, 'speechtotext', e);
throw e;
}
}
function transcribe(speechPipe, audio) { return speechPipe(audio); }
Okay, let's refactor the code to use the Web Speech API instead of the Hugging Face transformers library.
The Web Speech API handles the audio capture, processing, and transcription natively in the browser, simplifying the code significantly.
// import dynamicImportESM from "../../common-utils/dynamic-import-esm.js"; // No longer needed
export async function handleSpeechToText(app, plugin) {
// Check for Web Speech API support
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) {
const errorMessage = 'Web Speech API is not supported in this browser. Please try a modern browser like Chrome or Edge.';
console.error(errorMessage);
// Update selection with error message
await app.context.replaceSelection(errorMessage);
// Send error message to embed
await plugin.sendMessageToEmbed(app, 'speechtotext', errorMessage);
// Optionally throw an error to halt further execution
throw new Error(errorMessage);
}
let recognition = null; // Variable to hold the SpeechRecognition instance
let transcribeResult = ''; // Variable to accumulate the final transcribed text
const initialPrompt = 'Say something...';
try {
// Set initial text in the selection
await app.context.replaceSelection(initialPrompt);
// Open the sidebar embed (assuming it's used to show state or provide a stop button)
app.openSidebarEmbed(1, { openSpeechToText: true });
// Wait for the embed to be open (existing logic)
// This loop also serves to keep the main function scope alive
// while the recognition is active and the embed is open.
let embedIsOpen = await plugin.isEmbedOpen(app);
while (!embedIsOpen) {
console.log('Waiting for embed...');
await new Promise(resolve => setTimeout(resolve, 500));
embedIsOpen = await plugin.isEmbedOpen(app);
}
// Initialize SpeechRecognition
recognition = new SpeechRecognition();
recognition.continuous = true; // Keep listening even after pauses
recognition.interimResults = false; // We only care about final results for accumulating text
recognition.lang = 'en-US'; // Set the language (e.g., 'en-US', 'es-ES', etc.)
console.log('Web Speech API recognition initialized.');
// --- Event Handlers ---
recognition.onstart = () => {
console.log('Speech recognition started.');
// Optional: Send a message to the embed indicating state
plugin.sendMessageToEmbed(app, 'speechtotext', 'listening');
// Update selection to reflect listening state if it's still the initial prompt
if (app.context.getSelection().text === initialPrompt) {
app.context.replaceSelection('Listening...');
}
};
recognition.onresult = (event) => {
console.log('Speech recognition result received.');
let finalTranscript = '';
// event.results is a SpeechRecognitionResultList
// Iterate through results to find final ones
for (let i = event.resultIndex; i < event.results.length; ++i) {
const result = event.results[i]; // SpeechRecognitionResult
if (result.isFinal) {
// result[0] is the highest confidence SpeechRecognitionAlternative
finalTranscript += result[0].transcript;
}
}
if (finalTranscript) {
transcribeResult += finalTranscript; // Accumulate the final text
// Update the selection with the current accumulated text
// Trim trailing whitespace that might come from the API results
const currentText = transcribeResult.trim();
console.log('Accumulated text:', currentText);
// Replace the selection content
// Only replace if there's new text to avoid unnecessary updates/cursor jumps
// unless the current selection is still the initial prompt/loading text
const currentSelectionText = app.context.getSelection().text;
if (currentSelectionText === initialPrompt || currentSelectionText === 'Listening...' || currentText !== currentSelectionText.trim()) {
app.context.replaceSelection(currentText);
}
// Optional: Send updated text to the embed
// plugin.sendMessageToEmbed(app, 'speechtotext', currentText);
}
};
recognition.onerror = (event) => {
console.error('Speech recognition error:', event.error);
// Stop recognition on error to prevent it from continuing
if (recognition && (recognition.state === 'listening' || recognition.state === 'recognizing')) {
recognition.stop(); // Use stop to allow onend to fire gracefully
}
// Update selection/embed with error message
const errorMessage = `Speech recognition error: ${event.error}`;
app.context.replaceSelection(`Error: ${event.error}`);
plugin.sendMessageToEmbed(app, 'speechtotext', errorMessage);
// You might want to re-throw or handle the error here
// Depending on desired behavior (e.g., stop process or try again)
// Let's rely on the outer catch for final cleanup and re-throwing
};
recognition.onend = () => {
console.log('Speech recognition ended.');
// Optional: Send message to embed
plugin.sendMessageToEmbed(app, 'speechtotext', 'ended');
// The main loop will check isEmbedOpen and likely exit after this.
// The final result should already be in transcribeResult and the selection.
};
// --- Start Recognition ---
recognition.start();
console.log('Speech recognition process started via API.');
// --- Keep Function Alive While Embed Open ---
// The event listeners handle the recognition process asynchronously.
// This loop simply keeps the function scope alive and responsive,
// periodically checking if the embed is still open.
// The user closing the embed will cause this loop to exit.
embedIsOpen = await plugin.isEmbedOpen(app); // Re-check state after start()
while (embedIsOpen) {
await new Promise(resolve => setTimeout(resolve, 500)); // Check every 500ms
embedIsOpen = await plugin.isEmbedOpen(app);
}
// --- Stop Recognition When Embed Closes ---
console.log('Embed closed. Stopping recognition.');
// Check if recognition is currently active before stopping
if (recognition && (recognition.state === 'listening' || recognition.state === 'recognizing')) {
recognition.stop(); // Request recognition to stop gracefully
}
// Final state should be in the selection already from the last onresult
} catch (e) {
console.error("Error in handleSpeechToText (Web Speech API):", e);
// Ensure recognition stops on any unexpected errors
if (recognition && (recognition.state === 'listening' || recognition.state === 'recognizing')) {
recognition.abort(); // Use abort for immediate stop on critical error
}
try {
// Clean up selection if it still contains the initial prompt or an old error
const currentSelectionText = app.context.getSelection().text;
if (currentSelectionText === initialPrompt || currentSelectionText.startsWith('Listening...') || currentSelectionText.startsWith('Error:')) {
// Replace with a generic error message, or clear it if preferred
await app.context.replaceSelection(`Error: ${e.message || 'An unexpected error occurred.'}`);
}
// If there was already some transcribed text, you might choose to leave it.
} catch (cleanupErr) {
console.error("Error during selection cleanup:", cleanupErr);
}
// Send the error message to the embed
await plugin.sendMessageToEmbed(app, 'speechtotext', `Error: ${e.message || e}`);
// Re-throw the error to be handled by the caller or plugin's error handling
throw e;
} finally {
// Any final resource cleanup can go here, if needed.
// The event handlers and outer catch already handle recognition stop/abort.
}
}
// The separate 'transcribe' function and associated audio processing logic are no longer needed.
Key Changes and Explanations:
window.SpeechRecognition || window.webkitSpeechRecognition to see if the browser supports the Web Speech API. If not, an error is displayed, and the function exits.dynamicImportESM and associated model loading (pipeline) are removed as the browser handles the recognition engine.getUserMedia, MediaRecorder, AudioContext, ondataavailable, onstop, processAudioChunks, audioChunks, and the transcribe function are all removed. The browser's API takes care of audio input and processing.SpeechRecognition Instance: A new SpeechRecognition object is created.continuous = true: This is important for a live, streaming experience. It tells the API to keep listening even during pauses, rather than stopping after the first detected silence.interimResults = false: We are accumulating final results into transcribeResult and updating the selection. Setting this to false means the onresult event will only fire when the API has a final, confident phrase. If you wanted to display real-time, changing text as the user speaks, you would set this to true and handle interim results differently (e.g., display them in a separate, temporary area).lang = 'en-US': Sets the recognition language. Change this as needed.onstart: Fired when recognition begins. Used here to log and optionally update the selection or embed state.onresult: Crucial. Fired when the API detects speech and processes it. The event.results contains the recognition results. We loop through event.results to find entries where result.isFinal is true, extract the transcript, and append it to transcribeResult. The selection is then updated with the accumulated text.onerror: Fired if an error occurs during recognition (e.g., mic permission denied, no audio input, network issues for cloud recognition). It logs the error, stops recognition, updates the selection, and sends a message to the embed.onend: Fired when the recognition session ends (either naturally due to prolonged silence if continuous were false, or because stop() or abort() was called). Used here for logging and sending an embed message.recognition.start() begins the listening process. This might trigger a browser permission prompt for microphone access.while (embedIsOpen) loop structure is kept. Its purpose is no longer to process audio chunks but simply to keep the async function running and periodically check if the sidebar embed (presumably the user's control interface) is still open.while loop exits (because the user closed the embed), recognition.stop() is called to gracefully end the recognition session. If an error occurs, recognition.abort() is used in the catch block for a more immediate stop.onresult handler whenever new final text is available, ensuring the document reflects the transcription in near real-time. The check currentText !== currentSelectionText.trim() prevents unnecessary DOM updates if the transcribed text hasn't changed from what's already there.try...catch remains to catch any errors during setup or execution outside the specific recognition events. It also ensures that the recognition is stopped (abort on error) and the selection/embed are updated with an error message.This version is much cleaner and relies on the browser's optimized, built-in speech recognition capabilities. Remember that the quality and features (like language support) of the Web Speech API can vary between browsers.