Futuresony commited on
Commit
b7453ff
·
verified ·
1 Parent(s): c31429d

Create static/script.js

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