File size: 11,593 Bytes
31a7207
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
let websocket_uri = 'ws://localhost:6006';
let websocket_audio_uri = 'ws://localhost:8888';

let bufferSize = 4096,
    AudioContext,
    context,
    processor,
    input,
    websocket;
var intervalFunction = null;
var recordingTime = 0;
var server_state = 0;
var websocket_audio = null;
let audioContext_tts = null;
var you_name = "Marcus"

var audioContext = null;
var audioWorkletNode = null;
var audio_state = 0;
var available_transcription_elements = 0;
var available_llm_elements = 0;
var available_audio_elements = 0;
var llm_outputs = [];
var new_transcription_element_state = true;
var audio_sources = [];
var audio_source = null;

initWebSocket();

const zeroPad = (num, places) => String(num).padStart(places, '0')

const generateUUID = () => {
    let dt = new Date().getTime();
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        const r = (dt + Math.random() * 16) % 16 | 0;
        dt = Math.floor(dt / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
};

function recording_timer() {
    recordingTime++;
    document.getElementById("recording-time").innerHTML = zeroPad(parseInt(recordingTime / 60), 2) + ":" + zeroPad(parseInt(recordingTime % 60), 2) + "s";
}

const start_recording = async () => {
    console.log(audioContext)
    try {
        if (audioContext) {
            
            await audioContext.resume();
            
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            
            if (!audioContext) return;
            console.log(audioContext?.state);

            await audioContext.audioWorklet.addModule("js/audio-processor.js");

            const source = audioContext.createMediaStreamSource(stream);
            audioWorkletNode = new AudioWorkletNode(audioContext, "audio-stream-processor");

            audioWorkletNode.port.onmessage = (event) => {
                if (server_state != 1) {
                  console.log("server is not ready!!")
                  return;
                }
                const audioData = event.data;
                if (websocket && websocket.readyState === WebSocket.OPEN && audio_state == 0) {
                    websocket.send(audioData.buffer);
                    console.log("send data")
                }
            };

            source.connect(audioWorkletNode);
        }
    } catch (e) {
        console.log("Error", e);
    }
};

const handleStartRecording = async () => {
    start_recording();
};

const startRecording = async () => {
    document.getElementById("instructions-text").style.display = "none";
    document.getElementById("control-container").style.backgroundColor = "white";

    AudioContext = window.AudioContext || window.webkitAudioContext;
    audioContext = new AudioContext({ latencyHint: 'interactive', sampleRate: 16000 });

    audioContext_tts = new AudioContext({ sampleRate: 24000 });

    document.getElementById("recording-stop-btn").style.display = "block";
    document.getElementById("recording-dot").style.display = "block";
    document.getElementById("recording-line").style.display = "block";
    document.getElementById("recording-time").style.display = "block";
    
    intervalFunction = setInterval(recording_timer, 1000);

    await handleStartRecording();
};

function stopRecording() {
    audio_state = 1;
    clearInterval(intervalFunction);
}

function initWebSocket() {
    websocket_audio = new WebSocket(websocket_audio_uri);
    websocket_audio.binaryType = "arraybuffer";

    websocket_audio.onopen = function() { }
    websocket_audio.onclose = function(e) { }
    websocket_audio.onmessage = function(e) {
        available_audio_elements++;
        
        let float32Array = new Float32Array(e.data);
        let audioBuffer = audioContext_tts.createBuffer(1, float32Array.length, 24000);
        audioBuffer.getChannelData(0).set(float32Array);

        new_whisper_speech_audio_element("audio-" + available_audio_elements, Math.floor(audioBuffer.duration));

        audio_sources.push(audioBuffer);

        audio_source = audioContext_tts.createBufferSource();
        audio_source.buffer = audioBuffer;
        audio_source.connect(audioContext_tts.destination);
        audio_source.start();

        window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
    }

    websocket = new WebSocket(websocket_uri);
    websocket.binaryType = "arraybuffer";

    console.log("Websocket created.");
  
    websocket.onopen = function() {
      console.log("Connected to server.");
      
      websocket.send(JSON.stringify({
        uid: generateUUID(),
        multilingual: false,
        language: "en",
        task: "transcribe"
      }));
    }
    
    websocket.onclose = function(e) {
      console.log("Connection closed (" + e.code + ").");
    }
    
    websocket.onmessage = function(e) {
      var data = JSON.parse(e.data);

      if ("message" in data) {
        if (data["message"] == "SERVER_READY") {
            server_state = 1;
        }
      } else if ("segments" in data) {
        if (new_transcription_element_state) {
            available_transcription_elements = available_transcription_elements + 1;

            var img_src = "0.png";
            if (you_name.toLowerCase() == "marcus") {
                you_name = "Marcus";
                img_src = "0.png";
            } else if (you_name.toLowerCase() == "vineet") {
                you_name = "Vineet";
                img_src = "1.png";
            } else if (you_name.toLowerCase() == "jakub") {
                you_name = "Jakub";
                img_src = "2.png";
            }

            new_transcription_element(you_name, img_src);
            new_text_element("<p>" +  data["segments"][0].text + "</p>", "transcription-" + available_transcription_elements);
            new_transcription_element_state = false;
        }
        document.getElementById("transcription-" + available_transcription_elements).innerHTML = "<p>" + data["segments"][0].text + "</p>"; 

        if (data["eos"] == true) {
            new_transcription_element_state = true;
        }
      } else if ("llm_output" in data) {
            new_transcription_element("Phi-2", "Phi.svg");
            new_text_element("<p>" +  data["llm_output"][0] + "</p>", "llm-" + available_transcription_elements);
      }

      window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
    }
}

function new_transcription_element(speaker_name, speaker_avatar) {
    var avatar_container = document.createElement("div");
    avatar_container.className = "avatar-container";

    var avatar_img = document.createElement("div");
    avatar_img.innerHTML = "<img class='avatar' src='img/" + speaker_avatar + "' \>";

    var avatar_name = document.createElement("div");
    avatar_name.className = "avatar-name";
    avatar_name.innerHTML = speaker_name;

    var dummy_element = document.createElement("div");

    avatar_container.appendChild(avatar_img);
    avatar_container.appendChild(avatar_name);
    avatar_container.appendChild(dummy_element);

    document.getElementById("main-wrapper").appendChild(avatar_container);
}

function new_text_element(text, id) {
    var text_container = document.createElement("div");
    text_container.className = "text-container";
    text_container.style.maxWidth = "500px";

    var text_element = document.createElement("div");
    text_element.id = id;
    text_element.innerHTML = "<p>" + text + "</p>";

    var dummy_element = document.createElement("div");

    text_container.appendChild(text_element);
    text_container.appendChild(dummy_element);

    document.getElementById("main-wrapper").appendChild(text_container);
}

function new_transcription_time_element(time) {
    var text_container = document.createElement("div");
    text_container.className = "transcription-timing-container";
    text_container.style.maxWidth = "500px";

    var text_element = document.createElement("div");
    text_element.innerHTML = "<span>WhisperLive - Transcription time: " + time + "ms</span>";

    var dummy_element = document.createElement("div");

    text_container.appendChild(text_element);
    text_container.appendChild(dummy_element);

    document.getElementById("main-wrapper").appendChild(text_container);
}

function new_llm_time_element(time) {
    var text_container = document.createElement("div");
    text_container.className = "llm-timing-container";
    text_container.style.maxWidth = "500px";

    var first_response_text_element = document.createElement("div");
    first_response_text_element.innerHTML = "<span>Phi-2 first response time: " + time + "ms</span>";

    var complete_response_text_element = document.createElement("div");
    complete_response_text_element.innerHTML = "<span>Phi-2 complete response time: " + time + "ms</span>";

    var dummy_element = document.createElement("div");

    text_container.appendChild(first_response_text_element);
    text_container.appendChild(complete_response_text_element);
    text_container.appendChild(dummy_element);

    document.getElementById("main-wrapper").appendChild(text_container);
}

function new_whisper_speech_audio_element(id, duration) {
    var audio_container = document.createElement("div");
    audio_container.className = "whisperspeech-audio-container";
    audio_container.style.maxWidth = "500px";

    var audio_div_element = document.createElement("div");
    var audio_element = document.createElement("audio");
    audio_element.style.paddingTop = "20px";

    if (duration > 10)
        duration = 10;
    audio_element.src = "static/" + duration + ".mp3";

    audio_element.id = id;
    audio_element.onplay = function() {
        console.log(this.id)
        var id = this.id.split("-")[1] - 1;

        if (audio_source) {
            audio_source.disconnect();
        }

        audio_source = audioContext_tts.createBufferSource();
        audio_source.buffer = audio_sources[id];
        audio_source.connect(audioContext_tts.destination);
        audio_source.start()
    };
    audio_element.onpause = function() {
        this.currentTime = 0;
        console.log(this.id)
        var id = this.id.split("-")[1] - 1;
        if (audio_source) {
            audio_source.stop();
        }
    };
    audio_element.controls = true;

    audio_div_element.appendChild(audio_element);

    var dummy_element_a = document.createElement("div");
    var dummy_element_b = document.createElement("div");

    audio_container.appendChild(dummy_element_a);
    audio_container.appendChild(audio_div_element);
    audio_container.appendChild(dummy_element_b);

    document.getElementById("main-wrapper").appendChild(audio_container);
}

function new_whisper_speech_time_element(time) {
    var text_container = document.createElement("div");
    text_container.className = "whisperspeech-timing-container";
    text_container.style.maxWidth = "500px";

    var text_element = document.createElement("div");
    text_element.innerHTML = "<span>WhisperSpeech response time: " + time + "ms</span>";

    var dummy_element = document.createElement("div");

    text_container.appendChild(text_element);
    text_container.appendChild(dummy_element);

    document.getElementById("main-wrapper").appendChild(text_container);
}

document.addEventListener('DOMContentLoaded', function() {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    if (urlParams.has('name')) {
        you_name = urlParams.get('name')
    }
 }, false);