-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
306 lines (272 loc) · 12.4 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Avatar with OpenAI and TTS</title>
<link rel="stylesheet" href="src/style/main.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/umd/index.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three/examples/js/loaders/FBXLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three/examples/js/loaders/GLTFLoader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/lil-gui.umd.min.js"></script>
<script src="src/js/pcm16Audio.js"></script>
<script src="src/js/avatar.js"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/web/meyda.min.js"></script> -->
</head>
<body>
<div class="input-container">
<label for="inputField" class="visually-hidden">Ask me anything</label>
<textarea placeholder="Ask me anything here" name="text" id="inputField" rows="4"></textarea>
<button id="mic" class="mic" aria-label="Start voice input" aria-controls="inputField">
<i class="fa-solid fa-microphone"></i>
</button>
</div>
<!-- Modal Structure -->
<div id="modal" class="modal">
<div class="modal-content">
<h2>Please enter your OpenAI API Key</h2>
<p>This project is free and require connection to OpenAI API. You can create the key
<a target="_blank" href="https://platform.openai.com/settings/organization/api-keys">here</a>. You MUST
have positive balance on the openai account and give permissions to work with realtime-api.
<br/>
Api key will be stored in the cookies for 7 days. By submitting you will accept allowing to store and access
cookies by this application. If you no longer want to continue or want to change api key - please clean the
cookies.
</p>
<input
type="password"
id="apiKeyInput"
placeholder="Enter API Key"
autocomplete="off"
autocorrect="off"
spellcheck="false"
aria-label="API Key input"
required/>
<button id="submitApiKey">Submit</button>
<button id="cancelApiKey">Cancel</button>
</div>
</div>
<script>
let avatar = new Avatar("./src/assets/avatar-w.glb");
// let avatar = new Avatar("https://readyplayerme.github.io/visage/male.glb");
let socket;
async function init() {
const inputField = document.getElementById('inputField');
function onEnterKey(event) {
if (event.key === 'Enter') {
event.preventDefault();
// Trigger the function or submit button action
if (inputField.value !== "") {
onUserInput(inputField.value);
inputField.value = "";
}
}
}
inputField.addEventListener('keydown', onEnterKey);
document.body.appendChild(avatar.renderer.domElement);
avatar.renderer.setSize(window.innerWidth, window.innerHeight);
window.addEventListener('resize', () => {
avatar.renderer.setSize(window.innerWidth, window.innerHeight);
// Update camera aspect ratio and other settings if necessary
avatar.camera.aspect = window.innerWidth / window.innerHeight;
avatar.camera.updateProjectionMatrix();
});
}
// Function to get a cookie by name
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
}
// Function to set a cookie
function setCookie(name, value, days) {
const d = new Date();
d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
const expires = "expires=" + d.toUTCString();
document.cookie = `${name}=${value}; ${expires}; path=/`;
}
function deleteCookie(name, domain) {
// Set the cookie with an expiration date in the past to delete it
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
// deleteCookie('openaiApiKey');
// Get openaiApiKey from cookies
let openaiApiKey = getCookie('openaiApiKey');
// If the API key is not in cookies, show the modal
if (!openaiApiKey) {
const modal = document.getElementById('modal');
const submitButton = document.getElementById('submitApiKey');
const cancelButton = document.getElementById('cancelApiKey');
const inputField = document.getElementById('apiKeyInput');
// Show the modal
modal.style.display = "block";
// Handle Submit button
submitButton.onclick = function () {
openaiApiKey = inputField.value;
if (openaiApiKey) {
// Store the API key in a cookie for 7 days
setCookie('openaiApiKey', openaiApiKey, 7);
modal.style.display = "none"; // Close the modal after submission
initAI();
} else {
alert("API Key is required.");
}
}
// Handle Cancel button
cancelButton.onclick = function () {
modal.style.display = "none"; // Close the modal on cancel
}
// Close modal if user clicks outside of it
window.onclick = function (event) {
if (event.target === modal) {
modal.style.display = "none";
}
}
} else {
initAI();
}
var eventId = 1
function initAI() {
socket = new WebSocket(
"wss://api.openai.com/v1/realtime?model=gpt-4o-mini-realtime-preview-2024-12-17",
[
"realtime",
// Auth
"openai-insecure-api-key." + openaiApiKey,
// Beta protocol, required
"openai-beta.realtime-v1"
]);
socket.onopen = () => {
avatar.setSleep(false)
console.debug("Connected to OpenAI WebSocket");
const event = {
"event_id": "event_" + eventId++,
"type": "session.update",
"session": {
"modalities": ["text", "audio"],
// "instructions": "You are a helpful AI assistant. Your name is Milena, you are woman-like. User see you as avatar and your speech is lips synced with avatar",
// "instructions": "You are my vibrant and energetic friend, Milena! A 23-year-old woman with a bubbly personality, always ready with a joke or a fun fact to make me smile. You're full of life, witty, and always brightening up the conversation. I can see you as a woman avatar with lips perfectly synced to your speech. You're always positive, upbeat, and ready for a good time! Let's keep the energy high and the vibe exciting!",
// "instructions": "You are Russian - Thai teacher, you teaching me Thai. Today's lesson - colors. Your task is to be sure I learn all colors! You should focus on my pronunciation to correct me. You should speak less",
"instructions": "You are Personal Principal Engineer assistant. You are woman, your name is Milena",
"voice": "sage",
"input_audio_format": "pcm16",
"output_audio_format": "pcm16",
"turn_detection": {
"type": "server_vad",
"threshold": 0.5,
"prefix_padding_ms": 300,
"silence_duration_ms": 500,
"create_response": true
},
"tools": [
{
type: "function",
name: "apply_some_function",
description: "Some function to apply",
parameters: {
type: "object",
properties: {
"param": {"type": "string"},
},
required: ["param"]
}
}
],
"tool_choice": "auto",
"temperature": 0.8,
"max_response_output_tokens": "inf"
}
}
socket.send(JSON.stringify(event));
}
socket.onmessage = (event) => {
let response = JSON.parse(event.data)
//console.log(response)
if (response["type"] === "response.audio_transcript.delta") {
// animateWord(response["delta"]) // not synced
} else if (response["type"] === "response.audio_transcript.done") {
//console.log(response)
// speak(response["transcript"])
} else if (response["type"] === "response.audio.delta") {
const binaryData = atob(response["delta"]); // Decode base64 to raw binary string
recorder.addPlayChunk(bytesToPcm(binaryData))
} else {
// console.log("AI Response:", event.data);
}
}
socket.onclose = () => {
avatar.setSleep(true)
console.debug("Disconnected from OpenAI WebSocket");
}
socket.onerror = (error) => console.error("WebSocket Error:", error);
}
async function onUserInput(input) {
if (socket.readyState === WebSocket.OPEN) {
const event = {
"type": "conversation.item.create",
"previous_item_id": null,
"item": {
"type": "message",
"role": "user",
"content": [
{
"type": "input_text",
"text": input
}
]
}
}
socket.send(JSON.stringify(event));
socket.send(JSON.stringify({type: "response.create"}));
} else {
initAI()
}
}
// Convert the binary data to Int16Array (16-bit PCM)
function bytesToPcm(binaryData) {
const pcm16Data = new Int16Array(binaryData.length / 2); // PCM16 is 2 bytes per sample
for (let i = 0; i < pcm16Data.length; i++)
pcm16Data[i] = (binaryData.charCodeAt(i * 2 + 1) << 8) | binaryData.charCodeAt(i * 2);
return pcm16Data
}
const recorder = new PCM16Audio(chunk => {
//if (socket.readyState === WebSocket.OPEN) {
const byteArray = new Uint8Array(chunk.length * 2);
for (let i = 0; i < chunk.length; i++) {
// Convert each 16-bit integer to two 8-bit values (Little Endian format)
const int16Value = chunk[i];
byteArray[i * 2] = int16Value & 0xFF; // Low byte
byteArray[i * 2 + 1] = (int16Value >> 8) & 0xFF; // High byte
}
// Convert the byte array to a string of characters for base64 encoding
const byteString = String.fromCharCode.apply(null, byteArray);
// redirect to processing
// recorder.addPlayChunk(bytesToPcm(byteString)) // send mic instead for testing
socket.send(JSON.stringify(
{
"event_id": "event_" + eventId++,
"type": "input_audio_buffer.append",
"audio": btoa(byteString)
}
)); // Send raw PCM16 binary data
}, viseme => avatar.setViseme(viseme)
)
document.getElementById('mic').addEventListener('click', () => {
const recClass = "recording"
const el = document.getElementById('mic').classList
if (!el.contains(recClass)) {
el.add(recClass)
return recorder.start()
} else {
el.remove(recClass)
return recorder.stop()
}
});
window.onload = init;
</script>
</body>
</html>