Arghet6 commited on
Commit
f067b98
·
verified ·
1 Parent(s): f8aa834

Update static/script.js

Browse files
Files changed (1) hide show
  1. static/script.js +100 -272
static/script.js CHANGED
@@ -18,65 +18,10 @@ document.addEventListener("DOMContentLoaded", () => {
18
  const savedChatId = localStorage.getItem('currentChatId');
19
 
20
  fetch("/get_chats")
21
- .then(response => response.json())
22
- .then(chats => {
23
- renderChatList(chats);
24
-
25
- if (savedChatId && chats.some(c => c.chat_id === savedChatId)) {
26
- loadChat(savedChatId);
27
- } else if (chats.length > 0) {
28
- loadChat(chats[0].chat_id);
29
- } else {
30
- startNewChat();
31
- }
32
  })
33
- .catch(error => {
34
- console.error("Ошибка загрузки чатов:", error);
35
- startNewChat();
36
- });
37
- }
38
-
39
- function renderChatList(chats) {
40
- chatList.innerHTML = '';
41
- chats.forEach(chat => {
42
- const chatItem = document.createElement("div");
43
- chatItem.className = "chat-item";
44
- chatItem.dataset.chatId = chat.chat_id;
45
- chatItem.innerHTML = `
46
- <i class="fas fa-comment"></i>
47
- <span class="chat-title">${chat.title}</span>
48
- `;
49
- chatItem.addEventListener("click", () => {
50
- loadChat(chat.chat_id);
51
- localStorage.setItem('currentChatId', chat.chat_id);
52
- });
53
- chatList.appendChild(chatItem);
54
- });
55
- }
56
-
57
- newChatBtn.addEventListener("click", startNewChat);
58
-
59
- document.addEventListener("DOMContentLoaded", () => {
60
- let mediaRecorder, audioChunks = [], audioStream, currentChatId = null;
61
- const recordBtn = document.getElementById("record-btn");
62
- const stopBtn = document.getElementById("stop-btn");
63
- const sendBtn = document.getElementById("send-btn");
64
- const uploadBtn = document.getElementById("upload-btn");
65
- const userInput = document.getElementById("user-input");
66
- const chatBox = document.getElementById("chat-box");
67
- const audioFileInput = document.getElementById("audio-file");
68
- const newChatBtn = document.getElementById("new-chat-btn");
69
- const chatList = document.getElementById("chat-list");
70
- const currentChatTitle = document.getElementById("current-chat-title");
71
-
72
- // Инициализация при загрузке
73
- initializeChats();
74
-
75
- function initializeChats() {
76
- const savedChatId = localStorage.getItem('currentChatId');
77
-
78
- fetch("/get_chats")
79
- .then(response => response.json())
80
  .then(chats => {
81
  renderChatList(chats);
82
 
@@ -112,30 +57,49 @@ document.addEventListener("DOMContentLoaded", () => {
112
  });
113
  }
114
 
115
- newChatBtn.addEventListener("click", startNewChat);
116
-
117
  function startNewChat() {
118
  fetch("/start_chat", {
119
  method: "POST",
120
  headers: { "Content-Type": "application/json" },
121
  })
122
- .then(response => response.json())
 
 
 
123
  .then(data => {
124
  currentChatId = data.chat_id;
125
  currentChatTitle.textContent = data.title;
126
  chatBox.innerHTML = '<div class="message bot-message">Привет! Отправьте текст или голосовое сообщение для анализа эмоций.</div>';
127
- initializeChats(); // Обновляем список чатов
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
  localStorage.setItem('currentChatId', data.chat_id);
129
  })
130
- .catch(console.error);
 
 
 
131
  }
132
 
133
  function loadChat(chatId) {
134
  fetch(`/load_chat/${chatId}`)
135
- .then(response => response.json())
 
 
 
136
  .then(data => {
137
- if (data.error) throw new Error(data.error);
138
-
139
  currentChatId = chatId;
140
  currentChatTitle.textContent = data.title;
141
  updateActiveChat(chatId);
@@ -159,59 +123,59 @@ document.addEventListener("DOMContentLoaded", () => {
159
  });
160
  }
161
 
162
- sendBtn.addEventListener("click", sendMessage);
163
-
164
- async function sendMessage() {
165
  const text = userInput.value.trim();
166
  if (!text || !currentChatId) return;
167
 
168
  appendAndSaveMessage("user", text);
169
  userInput.value = "";
170
 
171
- try {
172
- const response = await fetch("/analyze", {
173
- method: "POST",
174
- headers: { "Content-Type": "application/json" },
175
- body: JSON.stringify({ text })
176
- });
177
- const data = await response.json();
 
 
 
178
  appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
179
- } catch (error) {
 
180
  console.error("Ошибка:", error);
181
  appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
182
- }
183
  }
184
 
185
- uploadBtn.addEventListener("click", async () => {
186
  const file = audioFileInput.files[0];
187
  if (!file || !currentChatId) return;
188
 
189
  appendAndSaveMessage("user", "Загружен аудиофайл...");
190
 
191
- try {
192
- const formData = new FormData();
193
- formData.append("audio", file);
194
 
195
- const response = await fetch("/analyze_audio", {
196
- method: "POST",
197
- body: formData
198
- });
199
- const data = await response.json();
200
-
201
- // Добавляем распознанный текст в чат
 
 
202
  if (data.transcribed_text) {
203
  appendAndSaveMessage("user", `Распознанный текст: ${data.transcribed_text}`);
204
  }
205
-
206
  appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
207
- } catch (error) {
 
208
  console.error("Ошибка:", error);
209
  appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
210
- }
211
- });
212
-
213
- recordBtn.addEventListener("click", startRecording);
214
- stopBtn.addEventListener("click", stopRecording);
215
 
216
  async function startRecording() {
217
  try {
@@ -220,33 +184,7 @@ document.addEventListener("DOMContentLoaded", () => {
220
  audioChunks = [];
221
 
222
  mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
223
- mediaRecorder.onstop = async () => {
224
- try {
225
- const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
226
- appendAndSaveMessage("user", "Отправлено голосовое сообщение...");
227
-
228
- const formData = new FormData();
229
- formData.append("audio", audioBlob, "recording.wav");
230
-
231
- const response = await fetch("/analyze_audio", {
232
- method: "POST",
233
- body: formData
234
- });
235
- const data = await response.json();
236
-
237
- // Добавляем распознанный текст в чат
238
- if (data.transcribed_text) {
239
- appendAndSaveMessage("user", `Распознанный текст: ${data.transcribed_text}`);
240
- }
241
-
242
- appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
243
- } catch (error) {
244
- console.error("Ошибка:", error);
245
- appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
246
- } finally {
247
- audioStream.getTracks().forEach(track => track.stop());
248
- }
249
- };
250
 
251
  mediaRecorder.start();
252
  recordBtn.disabled = true;
@@ -257,163 +195,39 @@ document.addEventListener("DOMContentLoaded", () => {
257
  }
258
  }
259
 
260
- function stopRecording() {
261
- if (mediaRecorder?.state === "recording") {
262
- mediaRecorder.stop();
263
- recordBtn.disabled = false;
264
- stopBtn.disabled = true;
265
- }
266
- }
267
-
268
- function appendMessage(sender, text) {
269
- const message = document.createElement("div");
270
- message.className = `message ${sender}-message`;
271
- message.innerHTML = text;
272
- chatBox.appendChild(message);
273
- chatBox.scrollTop = chatBox.scrollHeight;
274
- }
275
-
276
- function appendAndSaveMessage(sender, text) {
277
- appendMessage(sender, text);
278
-
279
- if (currentChatId) {
280
- fetch("/save_message", {
281
- method: "POST",
282
- headers: { "Content-Type": "application/json" },
283
- body: JSON.stringify({
284
- chat_id: currentChatId,
285
- sender: sender,
286
- content: text
287
- })
288
- }).catch(console.error);
289
- }
290
- }
291
- });
292
-
293
- function loadChat(chatId) {
294
- fetch(`/load_chat/${chatId}`)
295
- .then(response => response.json())
296
- .then(data => {
297
- if (data.error) throw new Error(data.error);
298
-
299
- currentChatId = chatId;
300
- currentChatTitle.textContent = data.title;
301
- updateActiveChat(chatId);
302
-
303
- chatBox.innerHTML = "";
304
- data.messages.forEach(msg => {
305
- appendMessage(msg.sender, msg.content);
306
- });
307
-
308
- localStorage.setItem('currentChatId', chatId);
309
- })
310
- .catch(error => {
311
- console.error("Ошибка загрузки чата:", error);
312
- appendMessage("bot", `❌ Ошибка: ${error.message}`);
313
- });
314
- }
315
-
316
- function updateActiveChat(chatId) {
317
- document.querySelectorAll(".chat-item").forEach(item => {
318
- item.classList.toggle("active", item.dataset.chatId === chatId);
319
- });
320
- }
321
-
322
- sendBtn.addEventListener("click", sendMessage);
323
-
324
- async function sendMessage() {
325
- const text = userInput.value.trim();
326
- if (!text || !currentChatId) return;
327
-
328
- appendAndSaveMessage("user", text);
329
- userInput.value = "";
330
-
331
  try {
332
- const response = await fetch("/analyze", {
333
- method: "POST",
334
- headers: { "Content-Type": "application/json" },
335
- body: JSON.stringify({ text })
336
- });
337
- const data = await response.json();
338
- appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
339
- } catch (error) {
340
- console.error("Ошибка:", error);
341
- appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
342
- }
343
- }
344
 
345
- uploadBtn.addEventListener("click", async () => {
346
- const file = audioFileInput.files[0];
347
- if (!file || !currentChatId) return;
348
-
349
- appendAndSaveMessage("user", "Загружен аудиофайл...");
350
-
351
- try {
352
  const formData = new FormData();
353
- formData.append("audio", file);
354
 
355
- const response = await fetch("/analyze_audio", {
356
  method: "POST",
357
  body: formData
 
 
 
 
 
 
 
 
 
 
 
 
 
 
358
  });
359
- const data = await response.json();
360
-
361
- // Добавляем распознанный текст в чат
362
- if (data.transcribed_text) {
363
- appendAndSaveMessage("user", `Распознанный текст: ${data.transcribed_text}`);
364
- }
365
-
366
- appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
367
  } catch (error) {
368
  console.error("Ошибка:", error);
369
  appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
370
- }
371
- });
372
-
373
- recordBtn.addEventListener("click", startRecording);
374
- stopBtn.addEventListener("click", stopRecording);
375
-
376
- async function startRecording() {
377
- try {
378
- audioStream = await navigator.mediaDevices.getUserMedia({ audio: true });
379
- mediaRecorder = new MediaRecorder(audioStream);
380
- audioChunks = [];
381
-
382
- mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
383
- mediaRecorder.onstop = async () => {
384
- try {
385
- const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
386
- appendAndSaveMessage("user", "Отправлено голосовое сообщение...");
387
-
388
- const formData = new FormData();
389
- formData.append("audio", audioBlob, "recording.wav");
390
-
391
- const response = await fetch("/analyze_audio", {
392
- method: "POST",
393
- body: formData
394
- });
395
- const data = await response.json();
396
-
397
- // Добавляем распознанный текст в чат
398
- if (data.transcribed_text) {
399
- appendAndSaveMessage("user", `Распознанный текст: ${data.transcribed_text}`);
400
- }
401
-
402
- appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
403
- } catch (error) {
404
- console.error("Ошибка:", error);
405
- appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
406
- } finally {
407
- audioStream.getTracks().forEach(track => track.stop());
408
- }
409
- };
410
-
411
- mediaRecorder.start();
412
- recordBtn.disabled = true;
413
- stopBtn.disabled = false;
414
- } catch (error) {
415
- console.error("Ошибка записи:", error);
416
- appendMessage("bot", "❌ Не удалось получить доступ к микрофону");
417
  }
418
  }
419
 
@@ -428,7 +242,7 @@ document.addEventListener("DOMContentLoaded", () => {
428
  function appendMessage(sender, text) {
429
  const message = document.createElement("div");
430
  message.className = `message ${sender}-message`;
431
- message.innerHTML = text;
432
  chatBox.appendChild(message);
433
  chatBox.scrollTop = chatBox.scrollHeight;
434
  }
@@ -445,7 +259,21 @@ document.addEventListener("DOMContentLoaded", () => {
445
  sender: sender,
446
  content: text
447
  })
448
- }).catch(console.error);
449
  }
450
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
  });
 
18
  const savedChatId = localStorage.getItem('currentChatId');
19
 
20
  fetch("/get_chats")
21
+ .then(response => {
22
+ if (!response.ok) throw new Error("Network response was not ok");
23
+ return response.json();
 
 
 
 
 
 
 
 
24
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  .then(chats => {
26
  renderChatList(chats);
27
 
 
57
  });
58
  }
59
 
 
 
60
  function startNewChat() {
61
  fetch("/start_chat", {
62
  method: "POST",
63
  headers: { "Content-Type": "application/json" },
64
  })
65
+ .then(response => {
66
+ if (!response.ok) throw new Error("Network response was not ok");
67
+ return response.json();
68
+ })
69
  .then(data => {
70
  currentChatId = data.chat_id;
71
  currentChatTitle.textContent = data.title;
72
  chatBox.innerHTML = '<div class="message bot-message">Привет! Отправьте текст или голосовое сообщение для анализа эмоций.</div>';
73
+
74
+ // Добавляем новый чат в список без полной перезагрузки
75
+ const chatItem = document.createElement("div");
76
+ chatItem.className = "chat-item active";
77
+ chatItem.dataset.chatId = data.chat_id;
78
+ chatItem.innerHTML = `
79
+ <i class="fas fa-comment"></i>
80
+ <span class="chat-title">${data.title}</span>
81
+ `;
82
+ chatItem.addEventListener("click", () => {
83
+ loadChat(data.chat_id);
84
+ localStorage.setItem('currentChatId', data.chat_id);
85
+ });
86
+ chatList.prepend(chatItem);
87
+
88
  localStorage.setItem('currentChatId', data.chat_id);
89
  })
90
+ .catch(error => {
91
+ console.error("Ошибка создания чата:", error);
92
+ appendMessage("bot", `❌ Ошибка: ${error.message}`);
93
+ });
94
  }
95
 
96
  function loadChat(chatId) {
97
  fetch(`/load_chat/${chatId}`)
98
+ .then(response => {
99
+ if (!response.ok) throw new Error("Network response was not ok");
100
+ return response.json();
101
+ })
102
  .then(data => {
 
 
103
  currentChatId = chatId;
104
  currentChatTitle.textContent = data.title;
105
  updateActiveChat(chatId);
 
123
  });
124
  }
125
 
126
+ function sendMessage() {
 
 
127
  const text = userInput.value.trim();
128
  if (!text || !currentChatId) return;
129
 
130
  appendAndSaveMessage("user", text);
131
  userInput.value = "";
132
 
133
+ fetch("/analyze", {
134
+ method: "POST",
135
+ headers: { "Content-Type": "application/json" },
136
+ body: JSON.stringify({ text })
137
+ })
138
+ .then(response => {
139
+ if (!response.ok) throw new Error("Network response was not ok");
140
+ return response.json();
141
+ })
142
+ .then(data => {
143
  appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
144
+ })
145
+ .catch(error => {
146
  console.error("Ошибка:", error);
147
  appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
148
+ });
149
  }
150
 
151
+ function handleAudioUpload() {
152
  const file = audioFileInput.files[0];
153
  if (!file || !currentChatId) return;
154
 
155
  appendAndSaveMessage("user", "Загружен аудиофайл...");
156
 
157
+ const formData = new FormData();
158
+ formData.append("audio", file);
 
159
 
160
+ fetch("/analyze_audio", {
161
+ method: "POST",
162
+ body: formData
163
+ })
164
+ .then(response => {
165
+ if (!response.ok) throw new Error("Network response was not ok");
166
+ return response.json();
167
+ })
168
+ .then(data => {
169
  if (data.transcribed_text) {
170
  appendAndSaveMessage("user", `Распознанный текст: ${data.transcribed_text}`);
171
  }
 
172
  appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
173
+ })
174
+ .catch(error => {
175
  console.error("Ошибка:", error);
176
  appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
177
+ });
178
+ }
 
 
 
179
 
180
  async function startRecording() {
181
  try {
 
184
  audioChunks = [];
185
 
186
  mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
187
+ mediaRecorder.onstop = handleRecordingStop;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
  mediaRecorder.start();
190
  recordBtn.disabled = true;
 
195
  }
196
  }
197
 
198
+ function handleRecordingStop() {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  try {
200
+ const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
201
+ appendAndSaveMessage("user", "Отправлено голосовое сообщение...");
 
 
 
 
 
 
 
 
 
 
202
 
 
 
 
 
 
 
 
203
  const formData = new FormData();
204
+ formData.append("audio", audioBlob, "recording.wav");
205
 
206
+ fetch("/analyze_audio", {
207
  method: "POST",
208
  body: formData
209
+ })
210
+ .then(response => {
211
+ if (!response.ok) throw new Error("Network response was not ok");
212
+ return response.json();
213
+ })
214
+ .then(data => {
215
+ if (data.transcribed_text) {
216
+ appendAndSaveMessage("user", `Распознанный текст: ${data.transcribed_text}`);
217
+ }
218
+ appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
219
+ })
220
+ .catch(error => {
221
+ console.error("Ошибка:", error);
222
+ appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
223
  });
 
 
 
 
 
 
 
 
224
  } catch (error) {
225
  console.error("Ошибка:", error);
226
  appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
227
+ } finally {
228
+ if (audioStream) {
229
+ audioStream.getTracks().forEach(track => track.stop());
230
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
  }
232
  }
233
 
 
242
  function appendMessage(sender, text) {
243
  const message = document.createElement("div");
244
  message.className = `message ${sender}-message`;
245
+ message.textContent = text; // Используем textContent вместо innerHTML для безопасности
246
  chatBox.appendChild(message);
247
  chatBox.scrollTop = chatBox.scrollHeight;
248
  }
 
259
  sender: sender,
260
  content: text
261
  })
262
+ }).catch(error => console.error("Ошибка сохранения сообщения:", error));
263
  }
264
  }
265
+
266
+ // Назначаем обработчики событий
267
+ newChatBtn.addEventListener("click", startNewChat);
268
+ sendBtn.addEventListener("click", sendMessage);
269
+ uploadBtn.addEventListener("click", handleAudioUpload);
270
+ recordBtn.addEventListener("click", startRecording);
271
+ stopBtn.addEventListener("click", stopRecording);
272
+
273
+ // Обработка отправки по Enter
274
+ userInput.addEventListener("keypress", (e) => {
275
+ if (e.key === "Enter") {
276
+ sendMessage();
277
+ }
278
+ });
279
  });