-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
529 lines (467 loc) · 19.1 KB
/
scripts.js
File metadata and controls
529 lines (467 loc) · 19.1 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
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
/*
const historyContainer = document.getElementById('history-container');
const chatContainer = document.getElementById('chat-container');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
const newChatButton = document.getElementById('new-chat-button');
const modeToggle = document.getElementById('mode-toggle');
const modelSelect = document.getElementById('model-select');
let conversationHistory = [];
let currentConversation = [];
let onlineMode = true;
let selectedModel = 'model1';
let isNewChat = true; // Flag to track if it's a new chat
modeToggle.addEventListener('change', () => {
onlineMode = modeToggle.checked;
});
modelSelect.addEventListener('change', () => {
selectedModel = modelSelect.value;
});
function addMessage(message, sender) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', `${sender}-message`);
messageDiv.textContent = message;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
currentConversation.push({ sender, message });
}
function getBotResponse(userMessage) {
if (onlineMode) {
console.log(`Online mode, model: ${selectedModel}`);
const responses = {
'hello': 'Hello from online mode!',
'how are you': 'I am doing well in the cloud!',
'what is your name': `I am online model ${selectedModel}.`,
'default': 'Online mode: I do not understand.'
};
const lowerUserMessage = userMessage.toLowerCase();
return responses[lowerUserMessage] || responses['default'];
} else {
console.log("Offline mode");
const responses = {
'hello': 'Hello from offline mode!',
'how are you': 'I am doing well locally!',
'what is your name': 'I am an offline chatbot.',
'default': 'Offline mode: I do not understand.'
};
const lowerUserMessage = userMessage.toLowerCase();
return responses[lowerUserMessage] || responses['default'];
}
}
function saveConversation() {
if (currentConversation.length > 0 && isNewChat) { // Only save if it's a new chat
conversationHistory.push(currentConversation);
updateHistoryDisplay();
isNewChat = false; // Reset the flag
}
}
function updateHistoryDisplay() {
historyContainer.innerHTML = '<h2>History</h2><button id="new-chat-button">New Chat</button>';
document.getElementById('new-chat-button').addEventListener('click', newChat);
conversationHistory.forEach((conversation, index) => {
const historyItem = document.createElement('div');
historyItem.classList.add('history-item');
historyItem.innerHTML = `<span>Conversation ${index + 1}</span><button class="delete-button" data-index="${index}">X</button>`;
historyItem.addEventListener('click', (event) => {
if (event.target.classList.contains('delete-button')) {
return;
}
loadConversation(index);
});
historyContainer.appendChild(historyItem);
const deleteButtons = document.querySelectorAll('.delete-button');
deleteButtons.forEach(button => {
button.addEventListener('click', (event) => {
const indexToDelete = parseInt(event.target.dataset.index);
deleteConversation(indexToDelete);
});
});
});
}
function loadConversation(index) {
chatContainer.innerHTML = ''; // Clear the chat
currentConversation = conversationHistory[index].slice(); // Copy the conversation
conversationHistory[index].forEach(messageObj => {
addMessage(messageObj.message, messageObj.sender);
});
isNewChat = false; // It's not a new chat when loading a conversation
}
function deleteConversation(index) {
conversationHistory.splice(index, 1);
updateHistoryDisplay();
chatContainer.innerHTML = '';
currentConversation = [];
isNewChat = true; // Start a new chat after deleting
}
function newChat() {
chatContainer.innerHTML = '';
currentConversation = [];
addMessage("Hello! How can I help you?", "bot");
isNewChat = true; // It's a new chat
}
sendButton.addEventListener('click', () => {
const message = messageInput.value.trim();
if (message) {
addMessage(message, 'user');
messageInput.value = '';
setTimeout(() => {
const botResponse = getBotResponse(message);
addMessage(botResponse, 'bot');
saveConversation();
}, 500);
}
});
messageInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
sendButton.click();
}
});
setTimeout(() => {
addMessage("Hello! How can I help you?", "bot");
}, 200);
newChatButton.addEventListener('click', newChat);
*/// scripts.js
// scripts.js
const historyContainer = document.getElementById('history-container');
const chatContainer = document.getElementById('chat-container');
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
const newChatButton = document.getElementById('new-chat-button');
const modeToggle = document.getElementById('mode-toggle');
const modelSelect = document.getElementById('model-select');
let conversationHistory = [];
let currentConversation = [];
let onlineMode = false;
let selectedModel = modelSelect.value;
let isNewChat = true; // Flag to track if it's a new chat
async function checkInternetConnection() {
try {
const response = await fetch('https://1.1.1.1/cdn-cgi/trace', {
method: 'HEAD',
cache: 'no-store',
});
return response.ok;
} catch (error) {
return false;
}
}
modeToggle.addEventListener('change', async () => {
if (modeToggle.checked) {
const isConnected = await checkInternetConnection();
if (isConnected) {
onlineMode = true;
console.log('Online mode enabled.');
} else {
modeToggle.checked = false;
alert('Internet connection is required for online mode.');
}
} else {
onlineMode = false;
console.log('Offline mode enabled.');
}
});
modelSelect.addEventListener('change', () => {
selectedModel = modelSelect.value;
console.log('Selected model:', selectedModel);
});
checkInternetConnection().then((isConnected) => {
if (!isConnected && modeToggle.checked) {
modeToggle.checked = false;
alert('Internet connection lost. Online mode disabled.');
}
});
window.addEventListener('online', (event) => {
console.log('You are now online.');
//If the toggle is already on, or if the toggle is off, but the user is trying to turn it on, do not alert.
if (!modeToggle.checked) {
alert('Internet connection restored. Online mode available.');
}
});
window.addEventListener('offline', (event) => {
console.log('You are now offline.');
if (modeToggle.checked) {
modeToggle.checked = false;
alert('Internet connection lost. Online mode disabled.');
}
});
/*
function addMessage(message, sender) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', `${sender}-message`);
messageDiv.textContent = message;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
currentConversation.push({ sender, message });
}
*/
document.addEventListener('DOMContentLoaded', () => {
const messageInput = document.getElementById('message-input');
const sendButton = document.getElementById('send-button');
const chatContainer = document.getElementById('chat-container');
const modeToggle = document.getElementById('mode-toggle');
const modelSelect = document.getElementById('model-select');
const newChatButton = document.getElementById('new-chat-button');
/*
function appendMessage(sender, message) {
const messageDiv = document.createElement('div');
messageDiv.textContent = `${sender}: ${message}`;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
}
*/
async function loadModels() {
try {
const response = await fetch('/models');
if (response.ok) {
const data = await response.json();
const onlineModels = data.online_models;
const offlineModels = data.offline_models;
const models = modeToggle.checked ? onlineModels : offlineModels;
modelSelect.innerHTML = '';
for (const modelId in models) {
const option = document.createElement('option');
option.value = modelId;
option.textContent = models[modelId];
modelSelect.appendChild(option);
}
} else {
console.error('Failed to load models:', response.status);
}
} catch (error) {
console.error('Error loading models:', error);
}
}
loadModels();
modeToggle.addEventListener('change', loadModels);
sendButton.addEventListener('click', async () => {
const message = messageInput.value;
if (message) {
addMessage(message, 'user');
messageInput.value = '';
const mode = modeToggle.checked ? 'online' : 'offline';
const model = modelSelect.value;
try {
const response = await fetch('/ask/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ question: message, mode: mode, model: model }),
});
if (response.ok) {
const data = await response.json();
const answer = data.response;
if (answer) {
addMessage(answer, 'bot');
} else {
addMessage('Error: No answer received.', 'bot');
}
} else {
addMessage('Error: Could not get response.', 'bot');
}
// Save the conversation when the page loads
} catch (error) {
addMessage('Error: ' + error.message, 'bot');
}
saveConversation(); // Save the conversation after each message
}
});
}
);
function saveConversation() {
if (currentConversation.length > 0 && isNewChat) { // Only save if it's a new chat
conversationHistory.push(currentConversation);
updateHistoryDisplay();
isNewChat = false; // Reset the flag
}
//send request to save conversation to server
sendConversationToServer(currentConversation);
}
function updateHistoryDisplay() {
historyContainer.innerHTML = '<h2>History</h2><button id="new-chat-button">New Chat</button>';
document.getElementById('new-chat-button').addEventListener('click', newChat);
conversationHistory.forEach((conversation, index) => {
const historyItem = document.createElement('div');
historyItem.classList.add('history-item');
historyItem.innerHTML = `<span>Conversation ${index + 1}</span><button class="delete-button" data-index="${index}">X</button>`;
historyItem.addEventListener('click', (event) => {
if (event.target.classList.contains('delete-button')) {
return;
}
loadConversation(index);
});
historyContainer.appendChild(historyItem);
const deleteButtons = document.querySelectorAll('.delete-button');
deleteButtons.forEach(button => {
button.addEventListener('click', (event) => {
const indexToDelete = parseInt(event.target.dataset.index);
deleteConversation(indexToDelete);
});
});
});
}
function loadConversation(index) {
chatContainer.innerHTML = ''; // Clear the chat
currentConversation = conversationHistory[index].slice(); // Copy the conversation
conversationHistory[index].forEach(messageObj => {
addMessage(messageObj.message, messageObj.sender);
});
isNewChat = false; // It's not a new chat when loading a conversation
}
function deleteConversation(index) {
conversationHistory.splice(index, 1);
updateHistoryDisplay();
chatContainer.innerHTML = '';
currentConversation = [];
isNewChat = true; // Start a new chat after deleting
}
function newChat() {
chatContainer.innerHTML = '';
currentConversation = [];
addMessage("Hello! How can I help you?", "bot");
isNewChat = true; // It's a new chat
}
// Function to send the conversation to the server
function sendConversationToServer(conversationData) {
fetch('/save_conversation', { // Replace '/save_conversation' with your server endpoint
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Cache-Control': 'no-cache' // Prevent caching
},
body: JSON.stringify({ conversation: conversationData }),
})
.then(response => response.json())
.then(data => {
if (data.success) {
console.log('Conversation saved successfully on the server.');
// Optionally, display a success message to the user
} else {
console.error('Failed to save conversation on the server:', data.error);
// Optionally, display an error message to the user
}
})
.catch(error => {
console.error('Error sending conversation to server:', error);
// Optionally, display an error message to the user
});
}
/*
sendButton.addEventListener('click', () => {
const message = messageInput.value.trim();
if (message) {
addMessage(message, 'user');
messageInput.value = '';
setTimeout(() => {
const botResponse = getBotResponse(message);
addMessage(botResponse, 'bot');
saveConversation();
}, 500);
}
});
*/
messageInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
if (event.shiftKey) {
// Shift + Enter: Insert a newline character
event.preventDefault(); // Prevent default Enter behavior (form submission or similar)
const start = messageInput.selectionStart;
const end = messageInput.selectionEnd;
messageInput.value = messageInput.value.substring(0, start) + '\n' + messageInput.value.substring(end);
messageInput.selectionStart = messageInput.selectionEnd = start + 1; // Move cursor to the newline
} else {
// Just Enter: Simulate send button click
sendButton.click();
}
}
});
setTimeout(() => {
addMessage("Hello! How can I help you?", "bot");
}, 200);
newChatButton.addEventListener('click', newChat);
function addMessage(message, sender) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', `${sender}-message`);
// Check if marked is available
if (typeof marked === 'undefined') {
console.error("marked.js is not loaded. Please include it in your HTML.");
messageDiv.textContent = message; // Fallback to plain text
} else {
messageDiv.innerHTML = marked.parse(message); // Render Markdown
}
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
currentConversation.push({ sender, message });
}
// Ensure marked.js is loaded (if not already)
function ensureMarkedLoaded() {
if (typeof marked === 'undefined') {
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/npm/marked/marked.min.js';
document.head.appendChild(script);
}
}
// Call ensureMarkedLoaded somewhere before addMessage is used.
ensureMarkedLoaded();
function setupVoiceRecording(recordButtonId, textareaId) {
const recordButton = document.getElementById(recordButtonId);
const textarea = document.getElementById(textareaId);
let mediaRecorder;
let audioChunks = [];
recordButton.addEventListener('click', async () => {
if (recordButton.classList.contains('recording')) {
mediaRecorder.stop();
recordButton.textContent = 'Record';
recordButton.classList.remove('recording');
} else {
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(stream);
audioChunks = [];
mediaRecorder.ondataavailable = (event) => {
if (event.data.size > 0) {
audioChunks.push(event.data);
}
};
mediaRecorder.onstop = async () => {
const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
// Send audio to FastAPI backend
const formData = new FormData();
formData.append('file', audioBlob, 'temp/temp_audio.wav');
const response = await fetch('http://127.0.0.1:80/voice_record', {
method: 'POST',
body: formData
});
if (response.ok) {
const result = await response.json();
textarea.value = result.recognized_text || 'Could not recognize speech.';
} else {
console.error('Error:', response.statusText);
textarea.value = 'Error in speech recognition.';
}
};
mediaRecorder.start();
recordButton.textContent = 'Stop Recording';
recordButton.classList.add('recording');
} catch (error) {
console.error('Microphone access denied:', error);
alert('Please allow microphone access.');
}
}
});
}
function clearMessageInput() {
const messageInput = document.getElementById('message-input');
const clearBtn = document.getElementById('clear-button');
clearBtn.addEventListener('click', () => {
messageInput.value = ''; // Clear the input field
messageInput.focus(); // Set focus back to the input field
console.log('Message input cleared and focused.');
});
}
document.addEventListener('DOMContentLoaded', () => {
setupVoiceRecording('record-button', 'message-input');
});
document.addEventListener('DOMContentLoaded', () => {
clearMessageInput();
});