Futuresony commited on
Commit
5e6ee7b
·
verified ·
1 Parent(s): 401ad90

Update static/script.js

Browse files
Files changed (1) hide show
  1. static/script.js +120 -195
static/script.js CHANGED
@@ -1,62 +1,76 @@
1
- let isRecording = false;
2
- let recognition;
3
- let responsesHistory = {}; // Holds all responses per prompt
4
- let currentIndex = {}; // Track current response index
5
-
6
- function initSpeechRecognition() {
7
- window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
8
- recognition = new SpeechRecognition();
9
- recognition.lang = 'en-US';
10
- recognition.interimResults = false;
11
- recognition.maxAlternatives = 1;
12
-
13
- recognition.onresult = function(event) {
14
- const transcript = event.results[0][0].transcript;
15
- sendMessageFromVoice(transcript);
16
- };
17
- recognition.onerror = function(event) {
18
- console.log("Speech recognition error:", event.error);
19
- };
20
  }
21
 
22
- const micIcon = document.getElementById('mic-icon');
23
- micIcon.addEventListener('mousedown', function() {
24
- isRecording = true;
25
- micIcon.textContent = 'mic_off';
26
- recognition.start();
27
- });
 
 
 
 
28
 
29
- micIcon.addEventListener('mouseup', function() {
 
 
 
 
 
30
  isRecording = false;
31
  micIcon.textContent = 'mic';
 
 
 
 
 
 
32
  recognition.stop();
33
- });
34
-
35
- function appendMessage(text, className) {
36
- let chatbox = document.getElementById('chatbox');
37
- let messageDiv = document.createElement('div');
38
- messageDiv.className = 'message ' + className;
39
- messageDiv.innerHTML = text;
40
- chatbox.appendChild(messageDiv);
41
- chatbox.scrollTop = chatbox.scrollHeight;
42
  }
 
 
 
 
 
 
 
 
 
 
43
 
44
- function sendMessageFromVoice(message) {
45
- appendMessage(message, 'user');
46
- fetchMessageFromAI(message);
47
- }
48
 
49
- function sendMessage() {
50
- let userInput = document.getElementById('user-input');
51
- let message = userInput.value.trim();
52
- if (message === '') return;
53
- appendMessage(message, 'user');
54
- userInput.value = '';
55
- fetchMessageFromAI(message);
56
- }
57
 
58
  function fetchMessageFromAI(message) {
59
- document.getElementById('typing-indicator').style.display = 'flex';
 
60
 
61
  fetch('/message', {
62
  method: 'POST',
@@ -65,163 +79,74 @@ function fetchMessageFromAI(message) {
65
  },
66
  body: JSON.stringify({ text: message })
67
  })
68
- .then(response => {
69
- if (!response.ok) {
70
- throw new Error(`Server error: ${response.statusText}`);
71
- }
72
- return response.json();
73
- })
74
- .then(data => {
75
- document.getElementById('typing-indicator').style.display = 'none';
76
-
77
- if (data.response) {
78
- addAIResponse(data.response, message);
79
- } else {
80
- console.error("No response from the server.");
81
- }
82
- })
83
- .catch(error => {
84
- document.getElementById('typing-indicator').style.display = 'none';
85
- console.error('Error:', error);
86
- appendMessage("An error occurred. Please try again later.", 'ai');
87
- });
88
- }
89
-
90
-
91
-
92
- function addAIResponse(responseText, userPrompt) {
93
- const responseId = Date.now();
94
- responsesHistory[responseId] = [responseText];
95
- currentIndex[responseId] = 0;
96
- renderAIResponse(responseText, responseId, userPrompt);
97
- }
98
-
99
- function renderAIResponse(responseText, responseId, userPrompt) {
100
- let chatbox = document.getElementById('chatbox');
101
- let messageDiv = document.createElement('div');
102
- messageDiv.className = 'message ai';
103
- messageDiv.dataset.responseId = responseId;
104
- messageDiv.dataset.userPrompt = userPrompt; // Store the prompt
105
-
106
- let responseTextDiv = document.createElement('div');
107
- responseTextDiv.className = 'response-text';
108
- responseTextDiv.innerHTML = responseText;
109
- messageDiv.appendChild(responseTextDiv);
110
-
111
- let iconsDiv = document.createElement('div');
112
- iconsDiv.className = 'icons';
113
-
114
- let speakerIcon = document.createElement('span');
115
- speakerIcon.className = 'material-icons';
116
- speakerIcon.innerText = 'volume_up';
117
- speakerIcon.onclick = () => speakText(responseId);
118
-
119
- let copyIcon = document.createElement('span');
120
- copyIcon.className = 'material-icons';
121
- copyIcon.innerText = 'content_copy';
122
- copyIcon.onclick = () => copyResponse(responseId);
123
-
124
- let regenerateIcon = document.createElement('span');
125
- regenerateIcon.className = 'material-icons';
126
- regenerateIcon.innerText = 'replay';
127
- regenerateIcon.onclick = () => regenerateResponse(responseId, responseTextDiv, iconsDiv);
128
-
129
- iconsDiv.appendChild(speakerIcon);
130
- iconsDiv.appendChild(copyIcon);
131
- iconsDiv.appendChild(regenerateIcon);
132
- messageDiv.appendChild(iconsDiv);
133
- chatbox.appendChild(messageDiv);
134
- chatbox.scrollTop = chatbox.scrollHeight;
135
- }
136
-
137
- function regenerateResponse(responseId, responseTextDiv, iconsDiv) {
138
- responseTextDiv.innerHTML = 'Generating new response...';
139
-
140
- // Get the original prompt from the dataset
141
- const messageDiv = document.querySelector(`[data-response-id="${responseId}"]`);
142
- const originalPrompt = messageDiv.dataset.userPrompt;
143
-
144
- fetch('/message', {
145
- method: 'POST',
146
- headers: {
147
- 'Content-Type': 'application/json',
148
- },
149
- body: JSON.stringify({ text: originalPrompt }) // Use the original prompt
150
  })
151
- .then(response => response.json())
152
  .then(data => {
 
 
153
  if (data.response) {
154
- responsesHistory[responseId].push(data.response);
155
- currentIndex[responseId] = responsesHistory[responseId].length - 1;
156
- displayUpdatedResponse(responseId, data.response, iconsDiv);
157
  } else {
158
- responseTextDiv.innerHTML = 'Error generating response';
 
159
  }
160
  })
161
  .catch(error => {
 
162
  console.error('Error:', error);
163
- responseTextDiv.innerHTML = 'Error generating response';
164
  });
165
- }
166
-
167
- function displayUpdatedResponse(responseId, newResponse, iconsDiv) {
168
- let messageDiv = document.querySelector(`[data-response-id="${responseId}"]`);
169
- let responseTextDiv = messageDiv.querySelector('.response-text');
170
- responseTextDiv.innerHTML = newResponse;
171
-
172
- // Remove existing navigation if present
173
- const existingNav = messageDiv.querySelector('.navigation');
174
- if (existingNav) {
175
- existingNav.remove();
176
- }
177
-
178
- let navigationDiv = document.createElement('div');
179
- navigationDiv.className = 'navigation';
180
- iconsDiv.appendChild(navigationDiv);
181
-
182
- let backIcon = document.createElement('span');
183
- backIcon.className = 'material-icons';
184
- backIcon.innerText = 'arrow_back';
185
- backIcon.onclick = () => navigateResponse(responseId, -1, responseTextDiv, navigationDiv);
186
-
187
- let nextIcon = document.createElement('span');
188
- nextIcon.className = 'material-icons';
189
- nextIcon.innerText = 'arrow_forward';
190
- nextIcon.onclick = () => navigateResponse(responseId, 1, responseTextDiv, navigationDiv);
191
-
192
- let responseIndexText = document.createElement('span');
193
- responseIndexText.className = 'response-index';
194
-
195
- navigationDiv.appendChild(backIcon);
196
- navigationDiv.appendChild(responseIndexText);
197
- navigationDiv.appendChild(nextIcon);
198
-
199
- updateResponseIndex(responseId, responseIndexText);
200
- }
201
-
202
- function navigateResponse(responseId, direction, responseTextDiv, navigationDiv) {
203
- currentIndex[responseId] += direction;
204
- currentIndex[responseId] = Math.max(0, Math.min(currentIndex[responseId], responsesHistory[responseId].length - 1));
205
- responseTextDiv.innerHTML = responsesHistory[responseId][currentIndex[responseId]];
206
- updateResponseIndex(responseId, navigationDiv.querySelector('.response-index'));
207
- }
208
 
209
- function updateResponseIndex(responseId, responseIndexText) {
210
- responseIndexText.innerText = `${currentIndex[responseId] + 1}/${responsesHistory[responseId].length}`;
211
- }
 
 
 
212
 
213
- // Updated function to speak the current response
214
- function speakText(responseId) {
215
- const text = responsesHistory[responseId][currentIndex[responseId]];
216
- const utterance = new SpeechSynthesisUtterance(text);
217
- speechSynthesis.speak(utterance);
218
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
- // Updated function to copy the current response
221
- function copyResponse(responseId) {
222
- const text = responsesHistory[responseId][currentIndex[responseId]];
223
- navigator.clipboard.writeText(text);
224
- alert("Copied: " + text);
225
- }
226
 
227
- document.addEventListener('DOMContentLoaded', initSpeechRecognition);
 
1
+ let isRecording = false;
2
+ let recognition;
3
+ let responsesHistory = {}; // Holds all responses per prompt
4
+ let currentIndex = {}; // Track current response index
5
+
6
+ function initSpeechRecognition() {
7
+ // Check for SpeechRecognition compatibility
8
+ if (!('SpeechRecognition' in window || 'webkitSpeechRecognition' in window)) {
9
+ alert("Speech recognition is not supported in your browser.");
10
+ return;
 
 
 
 
 
 
 
 
 
11
  }
12
 
13
+ window.SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
14
+ recognition = new SpeechRecognition();
15
+ recognition.lang = 'en-US';
16
+ recognition.interimResults = false;
17
+ recognition.maxAlternatives = 1;
18
+
19
+ recognition.onresult = function (event) {
20
+ const transcript = event.results[0][0].transcript;
21
+ sendMessageFromVoice(transcript);
22
+ };
23
 
24
+ recognition.onerror = function (event) {
25
+ console.log("Speech recognition error:", event.error);
26
+ alert("Error in speech recognition: " + event.error);
27
+ };
28
+
29
+ recognition.onend = function () {
30
  isRecording = false;
31
  micIcon.textContent = 'mic';
32
+ };
33
+ }
34
+
35
+ const micIcon = document.getElementById('mic-icon');
36
+ micIcon.addEventListener('click', function () {
37
+ if (isRecording) {
38
  recognition.stop();
39
+ isRecording = false;
40
+ micIcon.textContent = 'mic';
41
+ } else {
42
+ recognition.start();
43
+ isRecording = true;
44
+ micIcon.textContent = 'mic_off';
 
 
 
45
  }
46
+ });
47
+
48
+ function appendMessage(text, className) {
49
+ const chatbox = document.getElementById('chatbox');
50
+ const messageDiv = document.createElement('div');
51
+ messageDiv.className = 'message ' + className;
52
+ messageDiv.innerHTML = text;
53
+ chatbox.appendChild(messageDiv);
54
+ chatbox.scrollTop = chatbox.scrollHeight;
55
+ }
56
 
57
+ function sendMessageFromVoice(message) {
58
+ appendMessage(message, 'user');
59
+ fetchMessageFromAI(message);
60
+ }
61
 
62
+ function sendMessage() {
63
+ const userInput = document.getElementById('user-input');
64
+ const message = userInput.value.trim();
65
+ if (message === '') return;
66
+ appendMessage(message, 'user');
67
+ userInput.value = '';
68
+ fetchMessageFromAI(message);
69
+ }
70
 
71
  function fetchMessageFromAI(message) {
72
+ const typingIndicator = document.getElementById('typing-indicator');
73
+ typingIndicator.style.display = 'flex';
74
 
75
  fetch('/message', {
76
  method: 'POST',
 
79
  },
80
  body: JSON.stringify({ text: message })
81
  })
82
+ .then(response => {
83
+ if (!response.ok) {
84
+ throw new Error(`Server error: ${response.statusText}`);
85
+ }
86
+ return response.json();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  })
 
88
  .then(data => {
89
+ typingIndicator.style.display = 'none';
90
+
91
  if (data.response) {
92
+ addAIResponse(data.response, message);
 
 
93
  } else {
94
+ console.error("No response from the server.");
95
+ appendMessage("No response from the AI.", 'ai');
96
  }
97
  })
98
  .catch(error => {
99
+ typingIndicator.style.display = 'none';
100
  console.error('Error:', error);
101
+ appendMessage("An error occurred. Please try again later.", 'ai');
102
  });
103
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
+ function addAIResponse(responseText, userPrompt) {
106
+ const responseId = Date.now();
107
+ responsesHistory[responseId] = [responseText];
108
+ currentIndex[responseId] = 0;
109
+ renderAIResponse(responseText, responseId, userPrompt);
110
+ }
111
 
112
+ function renderAIResponse(responseText, responseId, userPrompt) {
113
+ const chatbox = document.getElementById('chatbox');
114
+ const messageDiv = document.createElement('div');
115
+ messageDiv.className = 'message ai';
116
+ messageDiv.dataset.responseId = responseId;
117
+ messageDiv.dataset.userPrompt = userPrompt; // Store the prompt
118
+
119
+ const responseTextDiv = document.createElement('div');
120
+ responseTextDiv.className = 'response-text';
121
+ responseTextDiv.innerHTML = responseText;
122
+ messageDiv.appendChild(responseTextDiv);
123
+
124
+ const iconsDiv = document.createElement('div');
125
+ iconsDiv.className = 'icons';
126
+
127
+ const speakerIcon = document.createElement('span');
128
+ speakerIcon.className = 'material-icons';
129
+ speakerIcon.innerText = 'volume_up';
130
+ speakerIcon.onclick = () => speakText(responseId);
131
+
132
+ const copyIcon = document.createElement('span');
133
+ copyIcon.className = 'material-icons';
134
+ copyIcon.innerText = 'content_copy';
135
+ copyIcon.onclick = () => copyResponse(responseId);
136
+
137
+ const regenerateIcon = document.createElement('span');
138
+ regenerateIcon.className = 'material-icons';
139
+ regenerateIcon.innerText = 'replay';
140
+ regenerateIcon.onclick = () => regenerateResponse(responseId, responseTextDiv, iconsDiv);
141
+
142
+ iconsDiv.appendChild(speakerIcon);
143
+ iconsDiv.appendChild(copyIcon);
144
+ iconsDiv.appendChild(regenerateIcon);
145
+ messageDiv.appendChild(iconsDiv);
146
+ chatbox.appendChild(messageDiv);
147
+ chatbox.scrollTop = chatbox.scrollHeight;
148
+ }
149
 
150
+ // Other functions (regenerateResponse, displayUpdatedResponse, navigateResponse, etc.) remain unchanged.
 
 
 
 
 
151
 
152
+ document.addEventListener('DOMContentLoaded', initSpeechRecognition);