Futuresony commited on
Commit
401ad90
·
verified ·
1 Parent(s): 6f3f16b

Update static/script.js

Browse files
Files changed (1) hide show
  1. static/script.js +213 -26
static/script.js CHANGED
@@ -1,40 +1,227 @@
1
- async function fetchMessageFromAI() {
2
- const messageInput = document.getElementById("user-message");
3
- const responseParagraph = document.getElementById("ai-response");
4
- const typingIndicator = document.getElementById("typing-indicator");
5
 
6
- const message = messageInput.value;
 
 
 
 
 
7
 
8
- if (!message) {
9
- responseParagraph.innerText = "Please enter a message.";
10
- return;
 
 
 
 
11
  }
12
 
13
- typingIndicator.style.display = "block";
 
 
 
 
 
14
 
15
- try {
16
- const response = await fetch("/message", {
17
- method: "POST",
18
- headers: {
19
- "Content-Type": "application/json",
20
- },
21
- body: JSON.stringify({ text: message }),
22
- });
 
 
 
 
 
 
 
 
 
 
 
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  if (!response.ok) {
25
  throw new Error(`Server error: ${response.statusText}`);
26
  }
27
-
28
- const data = await response.json();
29
- typingIndicator.style.display = "none";
 
30
 
31
  if (data.response) {
32
- responseParagraph.innerText = data.response;
33
  } else {
34
- responseParagraph.innerText = "No response from the AI.";
35
  }
36
- } catch (error) {
37
- typingIndicator.style.display = "none";
38
- responseParagraph.innerText = `Error: ${error.message}`;
39
- }
 
 
40
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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',
63
+ headers: {
64
+ 'Content-Type': 'application/json',
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);