-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
625 lines (529 loc) · 19.9 KB
/
main.js
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
const API_KEY = "<YOUR_API_KEY>";
let generatedNote = undefined;
let websocket;
let transcriptItems = {};
let audioContext;
let pcmWorker;
let mediaSource;
let mediaStream
let thinkingId;
const rawPCM16WorkerName = "raw-pcm-16-worker";
// Common utilities -----------------------------------------------------------
const disableElementById = (elementId) => {
const element = document.getElementById(elementId);
if (element.hasAttribute("disabled")) return;
element.setAttribute("disabled", "disabled");
}
const enableElementById = (elementId) => {
const element = document.getElementById(elementId);
if (!element.hasAttribute("disabled")) return;
element.removeAttribute("disabled");
}
const startThinking = (parent) => {
const thinking = document.createElement("div");
thinking.setAttribute("id", "thinking");
let count = 0;
thinkingId = setInterval(() => {
const dots = ".".repeat(count % 3 + 1)
thinking.innerHTML = `Thinking${dots} `
count++;
}, 500);
parent.appendChild(thinking);
}
const stopThinking = (parent) => {
clearInterval(thinkingId);
if (!parent) return;
const thinking = document.getElementById("thinking");
parent.removeChild(thinking);
}
const endConnection = async (endObject) => {
if (!websocket || websocket.readyState !== WebSocket.OPEN) return;
websocket.send(JSON.stringify(endObject));
// Await server closing the WS
for (let i = 0; i < 50; i++) {
if (websocket.readyState === WebSocket.OPEN) {
await sleep(100);
} else {
break;
}
}
}
const initializeMediaStream = async (buildAudioChunk) => {
// Ask authorization to access the microphone
mediaStream = await navigator.mediaDevices.getUserMedia({
audio: {
deviceId: "default",
sampleRate: 16000,
sampleSize: 16,
channelCount: 1,
},
video: false,
});
audioContext = new AudioContext({ sampleRate: 16000 });
await audioContext.audioWorklet.addModule("rawPcm16Processor.js")
pcmWorker = new AudioWorkletNode(audioContext, rawPCM16WorkerName, {
outputChannelCount: [1],
});
mediaSource = audioContext.createMediaStreamSource(mediaStream);
mediaSource.connect(pcmWorker);
// pcm post on message
pcmWorker.port.onmessage = (msg) => {
const pcm16iSamples = msg.data;
const audioAsBase64String = btoa(
String.fromCodePoint(...new Uint8Array(pcm16iSamples.buffer)),
);
if (websocket.readyState !== websocket.OPEN) {
console.error("Websocket is no longer open")
return;
}
websocket.send(buildAudioChunk(audioAsBase64String))
}
}
const stopAudio = () => {
try {
audioContext?.close();
} catch (e) {
console.error("Error while closing AudioContext", e);
}
try {
pcmWorker?.port.close();
pcmWorker?.disconnect();
} catch (e) {
console.error("Error while closing PCM worker", e);
}
try {
mediaSource?.mediaStream.getTracks().forEach((track) => track.stop());
mediaSource?.disconnect();
} catch (e) {
console.error("Error while closing media stream", e);
}
}
const insertElementByStartOffset = (element, parentElement) => {
const elementStartOffset = element.getAttribute["data-start-offset"]
let elementBefore = null;
for (let childElement of parentElement.childNodes) {
const childStartOffset =
childElement.nodeName === element.nodeName && childElement.hasAttribute("data-start-offset")
? childElement.getAttribute("data-start-offset")
: 0
if (childStartOffset > elementStartOffset) {
elementBefore = childElement;
break;
}
}
if (elementBefore) {
parentElement.insertBefore(element, elementBefore);
} else {
parentElement.appendChild(element);
}
}
// Transcript -----------------------------------------------------------------
// Utilities
const disableAll = () => {
disableElementById("start-btn");
disableElementById("generate-btn");
disableElementById("normalize-btn");
disableElementById("patient-instructions-btn");
}
const enableAll = () => {
enableElementById("start-btn");
enableElementById("generate-btn");
enableElementById("normalize-btn");
enableElementById("patient-instructions-btn");
}
const clearTranscript = () => {
document.getElementById("transcript").innerHTML = "<h3>Transcript:</h3>";
}
const clearNoteContent = () => {
document.getElementById("note").innerHTML = "<h3>Note:</h3>";
}
const clearPatientInstructions = () => {
document.getElementById("patient-instructions").innerHTML = "<h3>Patient instructions:</h3>";
}
const clearNormalizedData = () => {
document.getElementById("normalized-data").innerHTML = "<h3>Normalized data:</h3>";
}
const msToTime = (milli) => {
const seconds = Math.floor((milli / 1000) % 60);
const minutes = Math.floor((milli / (60 * 1000)) % 60);
return `${String(minutes).padStart(2, 0)}:${String(seconds).padStart(2, 0)}`;
};
const insertTranscriptItem = (data) => {
transcriptItems[data.id] = data.text;
const transcriptContent =
`[${msToTime(data.start_offset_ms)} to ${msToTime(data.end_offset_ms)}]: ${data.text}`;
const transcriptContainer = document.getElementById("transcript");
let transcriptItem = document.getElementById(data.id)
if (!transcriptItem) {
transcriptItem = document.createElement("div");
transcriptItem.setAttribute("id", data.id);
transcriptItem.setAttribute("data-start-offset", data.start_offset_ms);
insertElementByStartOffset(transcriptItem, transcriptContainer)
}
transcriptItem.innerHTML = transcriptContent;
if (data.is_final) {
transcriptItem.classList.remove("temporary-item")
} else if (!transcriptItem.classList.contains("temporary-item")) {
transcriptItem.classList.add("temporary-item")
}
}
const initializeTranscriptConnection = () => {
// Ideally we'd send the authentication token in an 'Authorization': 'Bearer <YOUR_TOKEN>' header.
// But since JS WS client does not support sending additional headers,
// we rely on this alternative authentication mechanism.
// Keep in mind that, except for prototyping purposes, the Server API is not meant to be called from a browser
// because an API_KEY is too sensitive to be embedded in a front-end app.
websocket = new WebSocket(
"wss://api.nabla.com/v1/copilot-api/server/listen-ws",
["copilot-listen-protocol", "jwt-" + API_KEY],
);
websocket.onclose = (e) => {
console.log(`Websocket closed: ${e.code} ${e.reason}`);
};
websocket.onmessage = (mes) => {
if (websocket.readyState !== WebSocket.OPEN) return;
if (typeof mes.data === "string") {
const data = JSON.parse(mes.data);
if (data.object === "transcript_item") {
insertTranscriptItem(data);
} else if (data.object === "error_message") {
console.error(data.message);
}
}
};
}
const sleep = (duration) => new Promise((r) => setTimeout(r, duration));
const startRecording = async () => {
enableElementById("generate-btn");
initializeTranscriptConnection();
// Await websocket being open
for (let i = 0; i < 10; i++) {
if (websocket.readyState !== WebSocket.OPEN) {
await sleep(100);
} else {
break;
}
}
if (websocket.readyState !== WebSocket.OPEN) {
throw new Error("Websocket did not open");
}
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
await initializeMediaStream((audioAsBase64String) => {
return JSON.stringify({
object: "audio_chunk",
payload: audioAsBase64String,
stream_id: "stream1",
})
})
const config = {
object: "listen_config",
output_objects: ["transcript_item"],
encoding: "pcm_s16le",
sample_rate: 16000,
language: getTranscriptLocale(),
streams: [
{ id: "stream1", speaker_type: "unspecified" },
],
};
websocket.send(JSON.stringify(config));
// pcm start
pcmWorker.port.start();
} else {
console.error("Microphone audio stream is not accessible on this browser");
}
}
const getTranscriptLocale = () => (
document.getElementById("transcript-locale")?.selectedOptions[0]?.value ?? "en-US"
)
const generateNote = async () => {
if (Object.keys(transcriptItems).length === 0) return;
disableAll();
stopAudio();
await endConnection({ object: "end" });
clearNoteContent();
await digest();
enableAll();
}
const digest = async () => {
startThinking(document.getElementById("note"));
const response = await fetch('https://api.nabla.com/v1/copilot-api/server/digest', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
output_objects: ['note'],
section_style: getNoteSectionStyle(),
note_template: getNoteTemplate(),
language: getNoteLanguage(),
patient_context: getPatientContext(),
transcript_items: Object.values(transcriptItems).map((it) => ({ text: it, speaker: "unspecified" })),
})
});
const note = document.getElementById("note");
stopThinking(note);
if (!response.ok) {
console.error('Error during note generation:', response.status);
const errData = await response.json();
const errText = document.createElement("p");
errText.classList.add("error");
errText.innerHTML = errData.message;
note.appendChild(errText)
return;
}
const data = await response.json();
generatedNote = data.note;
data.note.sections.forEach((section) => {
const title = document.createElement("h4");
title.innerHTML = section.title;
const text = document.createElement("p");
text.innerHTML = section.text;
note.appendChild(title);
note.appendChild(text);
})
}
const getNoteSectionStyle = () => (
document.getElementById("section-style")?.selectedOptions[0]?.value ?? "auto"
)
const getNoteTemplate = () => (
document.getElementById("note-template")?.selectedOptions[0]?.value ?? "GENERAL_MEDICINE"
)
const getPatientContext = () => (
document.getElementById("patient-context")?.value
)
const getNoteLanguage = () => (
document.getElementById("note-locale")?.selectedOptions[0]?.value ?? "en-US"
)
const generateNormalizedData = async () => {
if (!generatedNote) return;
disableAll();
clearNormalizedData();
const normalizationContainer = document.getElementById("normalized-data");
startThinking(normalizationContainer);
const note_locale = getNoteLanguage();
if (["es-ES", "es-MX"].includes(note_locale)) {
const errorMessage = document.createElement("p");
errorMessage.classList.add("error");
errorMessage.innerText = "Normalized data are only available for note with locale fr-FR, en-US, en-GB"
note.appendChild(errorMessage)
return;
}
const response = await fetch('https://api.nabla.com/v1/copilot-api/server/generate_normalized_data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY} `
},
body: JSON.stringify({
note: generatedNote,
note_locale
})
});
stopThinking(normalizationContainer);
if (!response.ok) {
console.error('Error during normalized data generation:', response.status);
const errData = await response.json();
const errText = document.createElement("p");
errText.classList.add("error");
errText.innerHTML = errData.message;
normalizationContainer.appendChild(errText);
return;
}
const data = await response.json();
const conditionTitle = document.createElement("h4");
conditionTitle.innerHTML = "Conditions:";
normalizationContainer.appendChild(conditionTitle);
addConditions(data.conditions, normalizationContainer);
const familyHistoryTitle = document.createElement("h4");
familyHistoryTitle.innerHTML = "Family history:";
normalizationContainer.appendChild(familyHistoryTitle);
const historyList = document.createElement("ul");
data.family_history.forEach((member) => {
const memberListItem = document.createElement("li");
const relationship = document.createElement("span");
relationship.innerText = member.relationship;
memberListItem.appendChild(relationship);
addConditions(member.conditions, memberListItem);
historyList.appendChild(memberListItem);
})
normalizationContainer.appendChild(historyList);
enableAll();
}
const addConditions = (conditions, parent) => {
const conditionsList = document.createElement("ul");
conditions.forEach((condition) => {
const element = document.createElement("li");
element.innerHTML = `${condition.coding.display.toUpperCase()} (${condition.coding.code})<br /><u>Clinical status:</u> ${condition.clinical_status}<br />`;
if (condition.categories.length > 0) {
element.innerHTML += "<u>Categories:</u> [${ condition.categories.join() }]";
}
conditionsList.appendChild(element);
})
parent.appendChild(conditionsList);
}
const generatePatientInstructions = async () => {
if (!generatedNote) return;
clearPatientInstructions();
disableAll();
const patientInstructions = document.getElementById("patient-instructions");
startThinking(patientInstructions);
const response = await fetch('https://api.nabla.com/v1/copilot-api/server/generate_patient_instructions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY} `
},
body: JSON.stringify({
note: generatedNote,
note_locale: "en-US",
instructions_locale: "en-US",
consultation_type: "IN_PERSON"
})
});
if (!response.ok) {
console.error('Error during note generation:', response.status);
}
const data = await response.json();
stopThinking(patientInstructions);
const instructionsTitle = document.createElement("h4");
instructionsTitle.innerHTML = "Instructions: ";
patientInstructions.appendChild(instructionsTitle);
const text = document.createElement("p");
text.innerHTML = data.instructions;
patientInstructions.appendChild(text);
enableAll();
}
const clearEncounter = async () => {
disableElementById("start-btn");
disableAll();
stopAudio();
await endConnection({ object: "end" });
clearNoteContent();
clearNormalizedData();
clearPatientInstructions();
clearTranscript();
enableElementById("start-btn");
enableAll();
}
// Dictated notes -------------------------------------------------------------
const insertedDictatedItem = (data) => {
const dictationContainer = document.getElementById("dictated-note");
let dicatedItem = document.getElementById(data.id)
if (!dicatedItem) {
dicatedItem = document.createElement("span");
dicatedItem.setAttribute("id", data.id);
dicatedItem.setAttribute("data-start-offset", data.start_offset_ms);
insertElementByStartOffset(dicatedItem, dictationContainer)
}
dicatedItem.innerHTML = data.text + " ";
if (data.is_final) {
dicatedItem.classList.remove("temporary-item")
} else if (!dicatedItem.classList.contains("temporary-item")) {
dicatedItem.classList.add("temporary-item")
}
}
const initializeDictationConnection = async () => {
websocket = new WebSocket(
"wss://api.nabla.com/v1/copilot-api/server/dictate-ws",
["copilot-dictate-protocol", "jwt-" + API_KEY]
);
websocket.onclose = (e) => {
console.log(`Websocket closed: ${e.code} ${e.reason}`);
};
websocket.onmessage = (mes) => {
if (websocket.readyState !== WebSocket.OPEN) {
console.log("ws not open");
return;
}
if (typeof mes.data === "string") {
const data = JSON.parse(mes.data);
if (data.type === "dictation_item") {
insertedDictatedItem(data);
} else if (data.object === "error_message") {
console.error(data.message);
}
}
};
}
const getDictationLocale = () => {
const dictationLocaleSelect = document.getElementById("dictationLocale");
return dictationLocaleSelect.selectedOptions && dictationLocaleSelect.selectedOptions.length > 0
? dictationLocaleSelect.selectedOptions[0].value
: "en-US";
}
const isPunctuationExplicit = () => {
return document.getElementById("punctuation-switch").checked;
}
const startDictating = async () => {
disableElementById("dictate-btn");
enableElementById("pause-btn");
initializeDictationConnection();
// Await websocket being open
for (let i = 0; i < 10; i++) {
if (websocket.readyState !== WebSocket.OPEN) {
await sleep(100);
} else {
break;
}
}
if (websocket.readyState !== WebSocket.OPEN) {
throw new Error("Websocket did not open");
}
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
await initializeMediaStream((audioAsBase64String) => (JSON.stringify({
type: "audio_chunk",
payload: audioAsBase64String,
})));
const locale = getDictationLocale();
const config = {
type: "dictate_config",
encoding: "pcm_s16le",
sample_rate: 16000,
locale,
dictate_punctuation: isPunctuationExplicit(),
};
websocket.send(JSON.stringify(config));
// pcm start
pcmWorker.port.start();
} else {
console.error("Microphone audio stream is not accessible on this browser");
}
}
const pauseDictating = async () => {
disableElementById("pause-btn");
stopAudio();
await endConnection({ type: "end" });
enableElementById("dictate-btn");
}
// Switch ambient encounter / dictated note ------------------------------------------
const showAmbientEncounter = () => {
let ambientEncounterLink = document.getElementById("ambient-encounter-link");
let dictatedNoteLink = document.getElementById("dictated-note-link");
if (ambientEncounterLink.className.match("active")) return;
ambientEncounterLink.classList.add("active");
dictatedNoteLink.classList.remove("active");
for (let element of document.getElementsByClassName("encounter")) {
element.classList.remove("hide");
}
for (let element of document.getElementsByClassName("dictation")) {
element.classList.add("hide");
};
}
const showDictatedNote = () => {
let ambientEncounterLink = document.getElementById("ambient-encounter-link");
let dictatedNoteLink = document.getElementById("dictated-note-link");
if (dictatedNoteLink.className.match("active")) return;
ambientEncounterLink.classList.remove("active");
dictatedNoteLink.classList.add("active");
for (let element of document.getElementsByClassName("encounter")) {
element.classList.add("hide");
}
for (let element of document.getElementsByClassName("dictation")) {
element.classList.remove("hide");
}
}
window.onload = () => {
document.getElementById("ambient-encounter-link").addEventListener("click", showAmbientEncounter);
document.getElementById("dictated-note-link").addEventListener("click", showDictatedNote);
}