-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathscribearRecognizer.tsx
More file actions
273 lines (239 loc) · 11.2 KB
/
Copy pathscribearRecognizer.tsx
File metadata and controls
273 lines (239 loc) · 11.2 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
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
import { Recognizer } from '../recognizer';
import { TranscriptBlock } from '../../../react-redux&middleware/redux/types/TranscriptTypes';
import { ScribearServerStatus, STATUS } from '../../../react-redux&middleware/redux/typesImports';
import RecordRTC, { StereoAudioRecorder } from 'recordrtc';
import { store } from '../../../store'
import { setModelOptions, setSelectedModel } from '../../../react-redux&middleware/redux/reducers/modelSelectionReducers';
import type { SelectedOption } from '../../../react-redux&middleware/redux/types/modelSelection';
enum BackendTranscriptBlockType {
Final = 0,
InProgress = 1,
}
type BackendTranscriptBlock = {
type: BackendTranscriptBlockType;
start: number;
end: number;
text: string;
};
export class ScribearRecognizer implements Recognizer {
private scribearServerStatus: ScribearServerStatus
private selectedModelOption: SelectedOption
private socket: WebSocket | null = null
private ready = false;
private transcribedCallback: any
private errorCallback?: (e: Error) => void;
private language: string
private recorder?: RecordRTC;
private kSampleRate = 16000;
private lastAudioTimestamp: number | null = null;
private inactivityInterval: any = null;
urlParams = new URLSearchParams(window.location.search);
mode = this.urlParams.get('mode');
/**
* Creates an Azure recognizer instance that listens to the default microphone
* and expects speech in the given language
* @param audioSource Not implemented yet
* @param language Expected language of the speech to be transcribed
*/
constructor(scribearServerStatus: ScribearServerStatus, selectedModelOption: SelectedOption, language: string) {
console.log("ScribearRecognizer, new recognizer being created!")
this.language = language;
this.selectedModelOption = selectedModelOption;
this.scribearServerStatus = scribearServerStatus;
}
private async _startRecording() {
let mic_stream: MediaStream;
try {
mic_stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
} catch (e) {
console.error('Failed to access microphone', e);
try {
store.dispatch({ type: 'SET_MIC_INACTIVITY', payload: true });
} catch (dispatchErr) {
console.error('Failed to dispatch SET_MIC_INACTIVITY after mic access error', dispatchErr);
}
// Surface an API status error to prompt UI; recognizer encapsulates flag setting here
try {
store.dispatch({ type: 'CHANGE_API_STATUS', payload: { scribearServerStatus: STATUS.ERROR, scribearServerMessage: 'Microphone permission denied or unavailable' } });
} catch (dispatchErr) {
console.error('Failed to dispatch CHANGE_API_STATUS after mic access error', dispatchErr);
}
throw e;
}
this.recorder = new RecordRTC(mic_stream, {
type: 'audio',
mimeType: 'audio/wav',
desiredSampRate: this.kSampleRate,
timeSlice: 50,
ondataavailable: async (blob: Blob) => {
// update last audio timestamp and mark that we've received at least one audio chunk
this.lastAudioTimestamp = performance.now();
try {
const controlState = (store.getState() as any).ControlReducer;
if (controlState?.micNoAudio === true) {
store.dispatch({ type: 'SET_MIC_INACTIVITY', payload: false });
}
} catch (e) {
console.warn('Failed to clear mic inactivity', e);
}
this.socket?.send(blob);
},
recorderType: StereoAudioRecorder,
numberOfAudioChannels: 1,
});
this.recorder.startRecording();
// start inactivity monitor
const thresholdMs = 3000;
if (this.inactivityInterval == null) {
this.inactivityInterval = setInterval(() => {
try {
const state: any = store.getState();
const listening = state.ControlReducer?.listening === true;
const micNoAudio = state.ControlReducer?.micNoAudio === true;
if (listening) {
if (!this.lastAudioTimestamp || (Date.now() - this.lastAudioTimestamp > thresholdMs)) {
if (!micNoAudio) {
store.dispatch({ type: 'SET_MIC_INACTIVITY', payload: true });
}
} else {
if (micNoAudio) {
store.dispatch({ type: 'SET_MIC_INACTIVITY', payload: false });
}
}
} else {
if (micNoAudio) store.dispatch({ type: 'SET_MIC_INACTIVITY', payload: false });
}
} catch (e) {
console.warn('Error in mic inactivity interval', e);
}
}, 1000);
}
}
/**
* Makes the Azure recognizer start transcribing speech asynchronously, if it has not started already
* Throws exception if recognizer fails to start
*/
start() {
console.log("ScribearRecognizer.start()");
if (this.socket) { return; }
const scribearURL = new URL(this.scribearServerStatus.scribearServerAddress)
if (scribearURL.pathname !== '/api/sink') {
this._startRecording();
}
this.socket = new WebSocket(this.scribearServerStatus.scribearServerAddress);
this.socket.onopen = (event) => {
this.socket?.send(JSON.stringify({
api_key: this.scribearServerStatus.scribearServerKey,
sourceToken: this.scribearServerStatus.scribearServerKey,
sessionToken: this.scribearServerStatus.scribearServerSessionToken,
}));
// Notify UI that the socket is open/available
try {
store.dispatch({ type: 'CHANGE_API_STATUS', payload: { scribearServerStatus: STATUS.AVAILABLE } });
} catch (e) {
console.warn('Failed to dispatch API status AVAILABLE', e);
}
}
const inProgressBlock = new TranscriptBlock();
this.socket.onmessage = (event) => {
if (!this.ready && this.mode !== 'student') {
const message = JSON.parse(event.data);
console.log(message);
if (message['error'] || !Array.isArray(message)) return;
store.dispatch(setModelOptions(message));
if (this.selectedModelOption) {
this.socket?.send(JSON.stringify(this.selectedModelOption));
this.ready = true;
// Client has informed server which model to use — consider the connection active/ready
try {
store.dispatch({ type: 'CHANGE_API_STATUS', payload: { scribearServerStatus: STATUS.TRANSCRIBING } });
} catch (e) {
console.warn('Failed to dispatch API status TRANSCRIBING', e);
}
}
return;
}
const server_block: BackendTranscriptBlock = JSON.parse(event.data);
// Todo: extract type of message (inprogress v final) and the text from the message
const inProgress = server_block.type === BackendTranscriptBlockType.InProgress;
const text = server_block.text;
if (inProgress) {
inProgressBlock.text = text; // replace text
this.transcribedCallback([], inProgressBlock);
} else {
inProgressBlock.text = "" //reset in progress
const finalBlock = new TranscriptBlock();
finalBlock.text = text
this.transcribedCallback([finalBlock], inProgressBlock)
}
};
this.socket.onerror = (event) => {
const error = new Error("WebSocket error");
console.error("WebSocket error event:", event);
try {
store.dispatch({ type: 'CHANGE_API_STATUS', payload: { scribearServerStatus: STATUS.ERROR } });
} catch (e) {
console.warn('Failed to dispatch API status ERROR', e);
}
this.errorCallback?.(error);
};
this.socket.onclose = (event) => {
console.warn(`WebSocket closed: code=${event.code}, reason=${event.reason}`);
this.socket = null;
try {
store.dispatch({ type: 'CHANGE_API_STATUS', payload: { scribearServerStatus: STATUS.UNAVAILABLE } });
} catch (e) {
console.warn('Failed to dispatch API status UNAVAILABLE', e);
}
if (event.code == 3000) { // API key error
try {
store.dispatch({ type: 'CHANGE_API_STATUS', payload: { scribearServerStatus: STATUS.ERROR, scribearServerMessage: 'ScribeAR Server rejected credentials (invalid API key/token)' } });
} catch (e) {
console.warn('Failed to dispatch API status for code 3000', e);
}
} else if (event.code !== 1000) { // 1000 = normal closure
const error = new Error(`WebSocket closed unexpectedly: code=${event.code}`);
this.errorCallback?.(error);
}
};
}
/**
* Makes the Azure recognizer stop transcribing speech asynchronously
* Throws exception if recognizer fails to stop
*/
stop() {
console.log("ScribearRecognizer.stop()");
this.recorder?.stopRecording();
if (!this.socket) { return; }
this.socket.close();
this.socket = null;
if (this.inactivityInterval) {
clearInterval(this.inactivityInterval);
this.inactivityInterval = null;
}
try {
store.dispatch({ type: 'SET_MIC_INACTIVITY', payload: false });
} catch (e) {
console.warn('Failed to clear mic inactivity on stop', e);
}
}
/**
* Subscribe a callback function to the transcript update event, which is usually triggered
* when the recognizer has processed more speech or some transcript has been finalized
* @param callback A callback function called with the updates to the transcript
*/
onTranscribed(callback: (newFinalBlocks: Array<TranscriptBlock>, newInProgressBlock: TranscriptBlock) => void) {
console.log("ScribearRecognizer.onTranscribed()");
// "recognizing" event signals that the in-progress block has been updated
this.transcribedCallback = callback;
}
/**
* Subscribe a callback function to the error event, which is triggered
* when the recognizer has encountered an error that it cannot handle
* @param callback A callback function called with the error object when the event is triggered
*/
onError(callback: (e: Error) => void) {
console.log("ScribearRecognizer.onError()");
this.errorCallback = callback;
}
}