Voice-to-text / script.js
rushidarge's picture
Update script.js
f6fb820 verified
const startBtn = document.getElementById("startBtn");
const stopBtn = document.getElementById("stopBtn");
const transcript = document.getElementById("transcript");
// const fetch = require('node-fetch');
console.log("script.js is running");
let recognition; // Speech recognition object
let accumulatedTranscript = ""; // Store accumulated text
startBtn.addEventListener("click", () => {
recognition = new webkitSpeechRecognition();
// Set language, interim results (optional), continuous mode, and confidence threshold
recognition.lang = "en-US"; // "hi-IN" for Hindi
recognition.interimResults = false; // Disable interim results to avoid excessive repetition
recognition.continuous = true;
recognition.maxAlternatives = 1;
recognition.start();
startBtn.disabled = true; // Disable start button while recording
stopBtn.disabled = false; // Enable stop button
recognition.onresult = (event) => {
let text = "";
for (let i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i][0].confidence > 0.8) { // Filter based on confidence
text += event.results[i][0].transcript;
}
}
// Append the new text to the existing transcript, avoiding excessive repetition
if (text !== accumulatedTranscript.slice(-text.length)) {
accumulatedTranscript += text;
transcript.value = accumulatedTranscript.trim();
}
};
});
stopBtn.addEventListener("click", () => {
recognition.stop();
startBtn.disabled = false; // Enable start button
stopBtn.disabled = true; // Disable stop button
console.log(transcript.value);
var formattedText = formatText(transcript.value);
console.log(formattedText);
transcript.value = formattedText;
});
function formatText(rawText) {
// Add a space after each period if there isn't one already
rawText = rawText.replace(/\./g, '. ');
// Capitalize the first letter of the text
rawText = rawText.charAt(0).toUpperCase() + rawText.slice(1);
// Ensure there is a period at the end of the text
if (!rawText.endsWith('.')) {
rawText += '.';
}
return rawText;
}
console.log("punctuate is running");
async function addPunctuation(text) {
const response = await fetch('http://bark.phon.ioc.ee/punctuator/', {
method: 'POST',
body: `text=${encodeURIComponent(text)}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
if (response.ok) {
const punctuatedText = await response.text();
console.log(punctuatedText);
console.log(response);
return punctuatedText;
} else {
throw formatText(text)
// new Error('Failed to punctuate text');
}
};