Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 1x 1x 14x 14x 1x 1x 14x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 14x 4x 2x 2x 4x 14x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 14x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 2x 14x 5x 5x 144012x 144012x 144012x 5x 5x 5x 2x 2x 2x 2x 3x 5x 14x | import { SpeechConverterInterface, transcribedLogEntry, TranscriptionResponse, SeparatedTranscriptionResponse } from "./SpeechConverterInterface";
import { AudioInputHandler } from "./AudioInputHandler";
import { CommandConverter } from "./CommandConverter";
export class SpeechConverterOnline implements SpeechConverterInterface{
/** Used to capture microphone input */
private audioHandler: AudioInputHandler | null = null;
/** Processes transcribed text and matches commands */
private commandConverter: CommandConverter | null = null;
/** Keeps a log of all text that has been transcribed*/
private textLog: transcribedLogEntry[] | null = null;
private transcriptionInterval?: ReturnType<typeof setInterval>;
private useSeparation: boolean = false;
private url: string;
private callTranscribe: string = "/transcription/";
private callSeparation: string = "/transcription/separation/"
/**
* updates the url to point to the correct backend on initialization
*
* @param backendURL url of hosted backend
*/
constructor(domainName: string, useSeparation: boolean = false) {
this.commandConverter = CommandConverter.getInstance();
this.useSeparation = useSeparation;
this.url = useSeparation
? `${domainName}${this.callSeparation}`
: `${domainName}${this.callTranscribe}`;
console.log(`Using endpoint: ${this.url}`);
}
/**
* Get whether speaker separation is enabled
*
* @returns true if using separation endpoint
*/
public getUseSeparation(): boolean {
return this.useSeparation;
}
/**
*
* Is not implemented for this version, throws an error if called
*
*/
public init(modelPath: string, lang: string): Promise<void> {
console.log("This implementation does not support this method. Please switch implementation to offline to use: ", modelPath, lang)
throw new Error("init() is not applicable for this Online transcription.");
}
/**
*
* Starts listening to the user's microphone input, collects audio chunks,
* and feeds them into the backend for transcription in real time.
*
* The method continuously gathers small chunks from `AudioInputHandler`,
* combines them into fixed-size blocks and sends them to the model for inference.
*
* @throws {Error} Throws if fetch status is not 200
* @throws {Error} Throws if Promise fails to resolve
*
*/
public startListening(): void {
const inputSampleRate = this.audioHandler?.getSampleRate() || 48000; //default from browser is 48000
const bufferSeconds = 3; //may need to adjust if too short of a time frame
const largeBlock = inputSampleRate * bufferSeconds; //creates the block size for x amount of seconds
let buffer: Float32Array[] = [];
let bufferLength = 0;
this.audioHandler = new AudioInputHandler(async (chunk: Float32Array) => {
//collects chunks until enough data is recieved
buffer.push(chunk);
bufferLength += chunk.length;
while (bufferLength >= largeBlock) {
//only send to speechbrain when enough chunks exist
const combined = this.combineChunks(buffer, largeBlock);
bufferLength -= largeBlock;
//throws away chunk if silence is detected
if(this.isSilence(combined)){
break;
}
const audioBuffer = new Float32Array(combined).buffer;
try{
const response = await fetch(this.url, {
method: "POST",
headers: {
"Content-Type": "application/octet-stream",
"X-Sample-Rate": inputSampleRate.toString()
},
body: audioBuffer
});
if(!response.ok){
throw new Error(`Did not return status:200 ${response.status}`)
}
const transcribed: TranscriptionResponse = await response.json();
console.log(transcribed);
if (transcribed.success) {
if ('speakers' in transcribed && Array.isArray((transcribed as any).speakers)) {
// Multi speaker response
const sepResponse = transcribed as SeparatedTranscriptionResponse;
sepResponse.speakers.forEach(speaker => {
if (speaker.text && speaker.text.trim()) {
this.processText(speaker.text, speaker.speaker_id);
this.logText(speaker.text, speaker.speaker_id);
}
});
} else {
// Single speaker response
if (transcribed.transcription && transcribed.transcription.trim()) {
this.processText(transcribed.transcription);
this.logText(transcribed.transcription);
}
}
}
}
catch (err){
console.log("Issue trancsribing voice on Backend: ", err);
throw new Error("Issue transcribing voice on Backend.");
}
}
});
this.audioHandler.startListening();
}
/**
* Stops the audio input stream and halts the real-time transcription process.
*
* This should be called after `startListening()` to stop capturing microphone input
* and free up system audio resources.
*
*/
public stopListening(): void {
this.audioHandler?.stopListening();
}
/**
* Retrieves the latest transcription result from the Whisper model and logs it.
*
* This method calls the underlying Whisper API to obtain the most recently
* transcribed text. If any text has been returned from whisper, it logs it.
*
* @returns {string} - The transcribed text from the current audio chunk.
*
*/
public getTranscribed(): string {
//adds text to logger
const text = this.getTextLog();
return text.toString();
}
/**
* Is not implemented for this implementation of SpeechConverter
* @throws {Error} Method not implemented
*/
getStatus(): string {
throw new Error("Method not implemented.");
}
private combineChunks(buffer: Float32Array[], blockSize: number): Float32Array {
const combined = new Float32Array(blockSize);
let offset = 0;
while (offset < blockSize && buffer.length > 0) {
const currentChunk = buffer[0];
const needed = blockSize - offset;
if (currentChunk.length <= needed) {
combined.set(currentChunk, offset);
offset += currentChunk.length;
buffer.shift();
} else {
combined.set(currentChunk.subarray(0, needed), offset);
buffer[0] = currentChunk.subarray(needed);
offset += needed;
}
}
return combined;
}
/**
* Takes in text and calls CommandConverter for processing and
* command matching.
*
* @param text transcribed words that have been recognized by whisper
* @param speakerId optional speaker identifier for multi-speaker mode
*/
private processText(text: string, speakerId?: string): void {
if (text && text.trim() && !text.includes('[BLANK_AUDIO]')) {
this.commandConverter?.processTranscription(text, speakerId);
}
}
/**
* Takes any recognized words and logs them into an array that contains a timestamp
* Excludes the string [BLANK_AUDIO]
*
* @param text transcribed words that have been recognized
*/
private logText(text: string, speakerId?: string): void {
if (text.includes('[BLANK_AUDIO]')) {
return;
}
const entry: transcribedLogEntry = {
timestamp: new Date(),
transcribedText: text,
speakerId: speakerId
};
//adds text to log if there is any
if (!this.textLog) {
this.textLog = [];
}
this.textLog.push(entry);
}
/**
* takes the array of objects that hold the transcribed logs
* and converts it into a string of the following format
* Timestamp: Transcribed text
*
* @returns {string[]} Returns an array of transcribed logs
*/
public getTextLog(): string[] {
const logOfText = [];
if (!this.textLog) return [];
for (let i = 0; i < this.textLog.length; i++) {
const date = this.textLog[i].timestamp.toLocaleTimeString();
const text = this.textLog[i].transcribedText;
const speakerId = this.textLog[i].speakerId;
const speakerPrefix = speakerId ? `[Speaker ${speakerId}] ` : '';
logOfText.push(`${date} : ${speakerPrefix}${text}\n`);
}
return logOfText;
}
/**
* Checks the audio chunk for voice.
* Uses root mean square method to determine if voice has been detected
*
* @param {Float32Array} waveform Audio sample
* @returns {boolean} True if audio has detected no sound
*/
private isSilence(waveform: Float32Array): boolean {
// Compute RMS (root mean square) of waveform
let sumSquares = 0;
for (let i = 0; i < waveform.length; i++) {
const sample = waveform[i];
sumSquares += sample * sample;
}
const mean = sumSquares / waveform.length;
const rms = Math.sqrt(mean);
if (rms < .01) {
const dates = new Date();
console.log("No voice detected at time: ", dates.toLocaleTimeString());
return true;
}
return false;
}
} |