File size: 8,881 Bytes
27b3bb8 |
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 |
document.addEventListener("DOMContentLoaded", () => {
let mediaRecorder, audioChunks = [], audioStream, currentChatId = null;
const recordBtn = document.getElementById("record-btn");
const stopBtn = document.getElementById("stop-btn");
const sendBtn = document.getElementById("send-btn");
const uploadBtn = document.getElementById("upload-btn");
const userInput = document.getElementById("user-input");
const chatBox = document.getElementById("chat-box");
const audioFileInput = document.getElementById("audio-file");
const newChatBtn = document.getElementById("new-chat-btn");
const chatList = document.getElementById("chat-list");
const currentChatTitle = document.getElementById("current-chat-title");
// Инициализация при загрузке
initializeChats();
function initializeChats() {
const savedChatId = localStorage.getItem('currentChatId');
fetch("/get_chats")
.then(response => response.json())
.then(chats => {
renderChatList(chats);
if (savedChatId && chats.some(c => c.chat_id === savedChatId)) {
loadChat(savedChatId);
} else if (chats.length > 0) {
loadChat(chats[0].chat_id);
} else {
startNewChat();
}
})
.catch(error => {
console.error("Ошибка загрузки чатов:", error);
startNewChat();
});
}
function renderChatList(chats) {
chatList.innerHTML = '';
chats.forEach(chat => {
const chatItem = document.createElement("div");
chatItem.className = "chat-item";
chatItem.dataset.chatId = chat.chat_id;
chatItem.innerHTML = `
<i class="fas fa-comment"></i>
<span class="chat-title">${chat.title}</span>
`;
chatItem.addEventListener("click", () => {
loadChat(chat.chat_id);
localStorage.setItem('currentChatId', chat.chat_id);
});
chatList.appendChild(chatItem);
});
}
newChatBtn.addEventListener("click", startNewChat);
function startNewChat() {
fetch("/start_chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
})
.then(response => response.json())
.then(data => {
currentChatId = data.chat_id;
currentChatTitle.textContent = data.title;
chatBox.innerHTML = '<div class="message bot-message">Привет! Отправьте текст или голосовое сообщение для анализа эмоций.</div>';
initializeChats(); // Обновляем список чатов
localStorage.setItem('currentChatId', data.chat_id);
})
.catch(console.error);
}
function loadChat(chatId) {
fetch(`/load_chat/${chatId}`)
.then(response => response.json())
.then(data => {
if (data.error) throw new Error(data.error);
currentChatId = chatId;
currentChatTitle.textContent = data.title;
updateActiveChat(chatId);
chatBox.innerHTML = "";
data.messages.forEach(msg => {
appendMessage(msg.sender, msg.content);
});
localStorage.setItem('currentChatId', chatId);
})
.catch(error => {
console.error("Ошибка загрузки чата:", error);
appendMessage("bot", `❌ Ошибка: ${error.message}`);
});
}
function updateActiveChat(chatId) {
document.querySelectorAll(".chat-item").forEach(item => {
item.classList.toggle("active", item.dataset.chatId === chatId);
});
}
sendBtn.addEventListener("click", sendMessage);
async function sendMessage() {
const text = userInput.value.trim();
if (!text || !currentChatId) return;
appendAndSaveMessage("user", text);
userInput.value = "";
try {
const response = await fetch("/analyze", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text })
});
const data = await response.json();
appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
} catch (error) {
console.error("Ошибка:", error);
appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
}
}
uploadBtn.addEventListener("click", async () => {
const file = audioFileInput.files[0];
if (!file || !currentChatId) return;
appendAndSaveMessage("user", "Загружен аудиофайл...");
try {
const formData = new FormData();
formData.append("audio", file);
const response = await fetch("/analyze_audio", {
method: "POST",
body: formData
});
const data = await response.json();
// Добавляем распознанный текст в чат
if (data.transcribed_text) {
appendAndSaveMessage("user", `Распознанный текст: ${data.transcribed_text}`);
}
appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
} catch (error) {
console.error("Ошибка:", error);
appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
}
});
recordBtn.addEventListener("click", startRecording);
stopBtn.addEventListener("click", stopRecording);
async function startRecording() {
try {
audioStream = await navigator.mediaDevices.getUserMedia({ audio: true });
mediaRecorder = new MediaRecorder(audioStream);
audioChunks = [];
mediaRecorder.ondataavailable = e => audioChunks.push(e.data);
mediaRecorder.onstop = async () => {
try {
const audioBlob = new Blob(audioChunks, { type: "audio/wav" });
appendAndSaveMessage("user", "Отправлено голосовое сообщение...");
const formData = new FormData();
formData.append("audio", audioBlob, "recording.wav");
const response = await fetch("/analyze_audio", {
method: "POST",
body: formData
});
const data = await response.json();
// Добавляем распознанный текст в чат
if (data.transcribed_text) {
appendAndSaveMessage("user", `Распознанный текст: ${data.transcribed_text}`);
}
appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`);
} catch (error) {
console.error("Ошибка:", error);
appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`);
} finally {
audioStream.getTracks().forEach(track => track.stop());
}
};
mediaRecorder.start();
recordBtn.disabled = true;
stopBtn.disabled = false;
} catch (error) {
console.error("Ошибка записи:", error);
appendMessage("bot", "❌ Не удалось получить доступ к микрофону");
}
}
function stopRecording() {
if (mediaRecorder?.state === "recording") {
mediaRecorder.stop();
recordBtn.disabled = false;
stopBtn.disabled = true;
}
}
function appendMessage(sender, text) {
const message = document.createElement("div");
message.className = `message ${sender}-message`;
message.innerHTML = text;
chatBox.appendChild(message);
chatBox.scrollTop = chatBox.scrollHeight;
}
function appendAndSaveMessage(sender, text) {
appendMessage(sender, text);
if (currentChatId) {
fetch("/save_message", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
chat_id: currentChatId,
sender: sender,
content: text
})
}).catch(console.error);
}
}
}); |