-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcommonUtils.js
More file actions
162 lines (140 loc) · 4.51 KB
/
commonUtils.js
File metadata and controls
162 lines (140 loc) · 4.51 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
// Common utilities for Nabla API demos
// This is the target API version for all API calls.
// Check this page before upgrading: https://docs.nabla.com/guides/api-versioning/changelog-and-upgrades
const API_VERSION = "2025-05-21"
let thinkingId;
let pcmWorker;
let audioContext;
let mediaSource;
// Element manipulation utilities
const disableElementById = (elementId) => {
const element = document.getElementById(elementId);
if (!element || element.hasAttribute("disabled")) return;
element.setAttribute("disabled", "disabled");
};
const enableElementById = (elementId) => {
const element = document.getElementById(elementId);
if (!element || !element.hasAttribute("disabled")) return;
element.removeAttribute("disabled");
};
// UI helpers
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");
if (thinking) {
parent.removeChild(thinking);
}
};
// Websocket utils
const endConnection = async (websocket, 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;
}
}
};
// Audio utilities
const initializeMediaStream = async (handleAudioChunk) => {
// Ask authorization to access the microphone
const 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("../shared/rawPcm16Processor.js");
pcmWorker = new AudioWorkletNode(audioContext, "raw-pcm-16-worker", {
outputChannelCount: [1],
});
mediaSource = audioContext.createMediaStreamSource(mediaStream);
mediaSource.connect(pcmWorker);
// pcm post on message
pcmWorker.port.onmessage = ({ data }) => {
const audioAsBase64String = btoa(
String.fromCodePoint(...new Uint8Array(data.buffer)),
);
handleAudioChunk(audioAsBase64String);
};
return pcmWorker;
};
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);
}
};
// UI utils
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 (Number(childStartOffset) > Number(elementStartOffset)) {
elementBefore = childElement;
break;
}
}
if (elementBefore) {
parentElement.insertBefore(element, elementBefore);
} else {
parentElement.appendChild(element);
}
};
// Time formatting
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)}`;
};
// Promises
const sleep = (duration) => new Promise((r) => setTimeout(r, duration));
export {
API_VERSION,
disableElementById,
enableElementById,
startThinking,
stopThinking,
endConnection,
initializeMediaStream,
stopAudio,
insertElementByStartOffset,
msToTime,
sleep
};