-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.html
377 lines (329 loc) · 13.5 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
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
<!DOCTYPE html>
<html>
<head>
<title>Personal AI Language Tutor</title>
<!-- Add Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
/* Overlay to blur the background */
.card-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5); /* Adjust the alpha value to control the opacity */
backdrop-filter: blur(5px); /* For modern browsers that support backdrop-filter */
z-index: 9999;
display: none;
}
/* Card content */
.card-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 400px;
background-color: #fff;
border-radius: 10px;
}
</style>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-JJ2HKRJL6Z"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-JJ2HKRJL6Z');
</script>
</head>
<body>
<!-- Add this inside the <body> tag -->
<div class="card-overlay" id="infoCard">
<div class="card card-content">
<div class="card-body">
<h5 class="card-title">Important Information</h5>
<p class="card-text">This is some useful information that you want to display to the user.</p>
<button type="button" class="close" id="closeCard">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
<div class="container mt-5">
<div>
<h1 class="h-1">Personal AI Tutor</h1>
<label for="voiceSelect">Select a Voice:</label>
<select id="voiceSelect"></select>
<br>
<br>
<label for="promptSelect">Select a Topic:</label>
<select id="promptSelect"></select>
<br>
<button class="btn btn-primary" onclick="tryPrompt()" id="promptBtn">Try Prompt</button>
</div>
<br>
<div class="form-group">
<label for="apiKeyInput">Enter your ChatGPT API Key:</label>
<input type="text" class="form-control" id="apiKeyInput" placeholder="API Key" value="">
</div>
<div class="card">
<div class="card-body" id="chatContainer">
<!-- Chat messages will be displayed here -->
<div class="alert">Welcome to the ESL student helper!</div>
</div>
</div>
<div class="card mt-3">
<div class="card-body">
<textarea class="form-control mb-3" id="textInput" rows="2" placeholder="Edit your text"></textarea>
<button class="btn btn-primary ml-2" onclick="toggleRecording()" id="recorderToggle">Start Recording</button>
<button class="btn btn-success" onclick="continueConversation()">Ask Tutor</button>
</div>
</div>
</div>
<!-- Add Bootstrap JS and your custom script -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Add this inside the <body> tag, after the Bootstrap JavaScript import -->
<script>
// Function to show the card on page load
document.ready(function() {
document.getElementById("infoCard").fadeIn();
});
document.getElementById("closeCard").onclick = function() {
document.getElementById("infoCard").fadeOut();
}
</script>
<script>
// Your custom JavaScript code will go here
// Global variables
let recognition;
let isRecording = false;
const chatContainer = document.getElementById('chatContainer');
const textInput = document.getElementById('textInput');
const apiKeyInput = document.getElementById('apiKeyInput');
const recorderToggle = document.getElementById('recorderToggle');
const voiceSelect = document.getElementById("voiceSelect");
const promptSelect = document.getElementById("promptSelect");
const preprompt = "You are a tutor for students interested in learning English. You must help them learn new vocabulary and help them speak in realistic scenarios. Use simple language and be sure to define complicated words.";
let conversation = [preprompt, "AI Tutor: Hi! It's nice to meet you!"];
const prompts = [
["Vocabulary", "Make a list of words about "],
["Grammar", "What are some common parts of speech?"],
["Conversation", "Let's talk about "]
];
const topics = [
"Family",
"Weather",
"Food",
"Colors",
"Animals",
"Clothing",
"Jobs",
"Transportation",
"Daily routines",
"Hobbies",
"Sports",
"Body parts",
"Numbers",
"Time",
"Seasons",
"Holidays",
"School",
"Shopping",
"Travel",
"Emotions",
"Music",
"Countries and nationalities",
"Fruits",
"Vegetables",
"In the city",
"In the countryside",
"At the beach",
"At the park",
"At the airport",
"At the restaurant",
"At the doctor's office",
"At the supermarket",
"At the movie theater",
"At the zoo",
"At the museum",
"At the library",
"At the post office",
"At the bank",
"At the gym",
"At the hotel",
"At the office",
"At the gas station",
"At the farm",
"At the bakery",
"At the hair salon",
"At the amusement park",
"At the aquarium",
"At the train station",
"At the bus stop",
"At the police station"
]
for (let prompt of prompts) {
let option = document.createElement("option");
option.text = prompt[0];
promptSelect.add(option);
}
window.onload(
doStuff()
)
function doStuff() {
speak("")
createChatMessage("AI Tutor: Hi! It's nice to meet you!")
apiKeyInput.value = (new URL(document.location)).searchParams.get('apiKey');
}
function tryPrompt() {
let prompt = promptSelect.value;
let text = prompts.find(x => x[0] == prompt)[1];
textInput.value += text;
textInput.value += topics[Math.floor(Math.random() * topics.length)];
}
function returnFullString() {
let fullString = "";
for (let i = 0; i < conversation.length; i++) {
fullString += conversation[i] + " \n";
}
return fullString;
}
// Function to create a new chat message element
function createChatMessage(text, isUser = false) {
const messageDiv = document.createElement('div');
messageDiv.className = isUser ? 'alert alert-primary' : 'alert alert-secondary';
const textSpan = document.createElement('span');
textSpan.textContent = text;
const speakerIcon = document.createElement('i');
speakerIcon.className = 'fas fa-volume-up ml-2'; // Assuming you have Font Awesome for the speaker icon
speakerIcon.addEventListener('click', () => {
speak(text);
});
messageDiv.appendChild(textSpan);
messageDiv.appendChild(speakerIcon);
chatContainer.appendChild(messageDiv);
let name = isUser ? 'Student: ' : 'AI Tutor: ';
conversation.push(isUser + text);
}
function toggleRecording() {
if (!isRecording) {
recorderToggle.innerText = "Stop Recording";
recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
recognition.onresult = event => {
let text ="";
for (let i = 0; i < event.results.length; i++) {
text += event.results[i][0].transcript;
}
textInput.value = text;
console.log(text);
};
recognition.start();
} else {
recognition.stop();
recorderToggle.innerText = "Start Recording";
}
isRecording = !isRecording;
}
// Function to call ChatGPT API for text-to-speech
async function continueConversation() {
const textToSpeak = textInput.value;
if (textToSpeak.length === 0) {
createChatMessage('Please enter something to send!');
return;
}
createChatMessage(`You: ${textToSpeak}`, true);
isRecording = false;
textInput.value = "";
if (recognition != undefined) {
recognition.stop();
recorderToggle.innerText = "Start Recording";
}
const apiKey = apiKeyInput.value.trim(); // Get the API key from the input
if (apiKey === '') {
createChatMessage("AI Tutor: Sorry you haven't entered your API key, so I can't respond. ");
return;
}
const apiUrl = 'https://api.openai.com/v1/engines/text-davinci-002/completions';
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
};
const body = JSON.stringify({
prompt: returnFullString(),
max_tokens: 150,
temperature: 0.7
});
try {
const response = await fetch(apiUrl, { method: 'POST', headers: headers, body: body });
const data = await response.json();
console.log(response);
console.log(data);
const chatGptResponse = removeFalse(data.choices[0].text.trim());
createChatMessage(`${chatGptResponse}`);
speak(chatGptResponse); // Call the text-to-speech function
textInput.value = "";
textInput.scrollIntoView();
} catch (error) {
console.error('Error calling ChatGPT API:', error);
createChatMessage('AI Tutor: Sorry, something went wrong. ');
}
}
// function to remove the random falses at the beginning of the string
function removeFalse(string) {
if (string.substring(0, 5) === "false") {
return removeFalse(string.substring(5));
}
return string;
}
function getSubstringBefore(string, substring) {
// Get the index of the specified string in the original string.
const index = string.indexOf(substring);
// If the specified string is not found, return string.
if (index === -1) {
return string;
}
// Get the substring before the specified string.
const substringBefore = string.slice(index + substring.length, string.length);
// Return the substring.
return substringBefore;
}
// Function to convert AI responses to spoken audio
function speak(text) {
if ('speechSynthesis' in window) {
const msg = new SpeechSynthesisUtterance(getSubstringBefore(text, "AI Tutor: "));
// Get available voices
let voices = [];
voices = window.speechSynthesis.getVoices();
function populateVoices() {
voices = window.speechSynthesis.getVoices();
voiceSelect.innerHTML = "";
voices.forEach(voice => {
const option = document.createElement('option');
option.value = voice.lang;
option.textContent = voice.name + ' (' + voice.lang + ')';
voiceSelect.appendChild(option);
});
}
// Chrome fires 'voiceschanged' event when voices are loaded
if ('onvoiceschanged' in window.speechSynthesis) {
window.speechSynthesis.onvoiceschanged = populateVoices;
}
if (voiceSelect.length <= 0) {
populateVoices();
}
// Set the desired voice based on the selection
const selectedVoice = voiceSelect.value;
msg.voice = voices.find(voice => voice.lang === selectedVoice);
window.speechSynthesis.speak(msg);
} else {
alert('Text-to-speech is not supported in this browser.');
}
}
</script>
</body>
</html>