Spaces:
Runtime error
Runtime error
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 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"); | |
const fileInfo = document.getElementById("file-info"); | |
const fileName = document.getElementById("file-name"); | |
const clearFileBtn = document.getElementById("clear-file"); | |
// Инициализация при загрузке | |
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 { | |
showEmptyChatUI(); | |
} | |
}) | |
.catch(error => { | |
console.error("Ошибка загрузки чатов:", error); | |
showEmptyChatUI(); | |
}); | |
} | |
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 = ` | |
<div class="chat-item-main"> | |
<i class="fas fa-comment chat-icon"></i> | |
<div class="chat-item-content"> | |
<span class="chat-title">${chat.title}</span> | |
<span class="chat-date">${formatDate(chat.created_at)}</span> | |
</div> | |
</div> | |
<button class="delete-chat-btn" title="Удалить чат"> | |
<i class="fas fa-trash"></i> | |
</button> | |
`; | |
// Обработчик клика по чату | |
chatItem.querySelector('.chat-item-main').addEventListener('click', () => { | |
loadChat(chat.chat_id); | |
localStorage.setItem('currentChatId', chat.chat_id); | |
}); | |
// Обработчик удаления чата | |
chatItem.querySelector('.delete-chat-btn').addEventListener('click', (e) => { | |
e.stopPropagation(); | |
deleteChat(chat.chat_id); | |
}); | |
chatList.appendChild(chatItem); | |
}); | |
} | |
function formatDate(dateString) { | |
if (!dateString) return ''; | |
const date = new Date(dateString); | |
return date.toLocaleDateString('ru-RU'); | |
} | |
async function deleteChat(chatId) { | |
if (!confirm('Вы точно хотите удалить этот чат? Это действие нельзя отменить.')) { | |
return; | |
} | |
try { | |
const response = await fetch(`/delete_chat/${chatId}`, { | |
method: 'DELETE', | |
headers: { | |
'Content-Type': 'application/json', | |
'X-CSRFToken': getCSRFToken() | |
} | |
}); | |
const result = await response.json(); | |
if (result.success) { | |
if (currentChatId === chatId) { | |
startNewChat(); | |
} | |
initializeChats(); | |
} else { | |
throw new Error(result.error || 'Ошибка при удалении чата'); | |
} | |
} catch (error) { | |
console.error('Delete chat error:', error); | |
appendMessage('bot', `❌ Ошибка при удалении: ${error.message}`); | |
} | |
} | |
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); | |
userInput.addEventListener("keypress", (e) => { | |
if (e.key === "Enter") 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, chat_id: currentChatId }) | |
}); | |
const data = await response.json(); | |
appendAndSaveMessage("bot", `Эмоция: ${data.emotion} (${(data.confidence * 100).toFixed(1)}%)`); | |
} catch (error) { | |
console.error("Ошибка:", error); | |
appendAndSaveMessage("bot", `❌ Ошибка: ${error.message}`); | |
} | |
} | |
// Обработчики аудио | |
audioFileInput.addEventListener("change", handleAudioUpload); | |
clearFileBtn.addEventListener("click", clearAudioFile); | |
function handleAudioUpload() { | |
const file = audioFileInput.files[0]; | |
if (file) { | |
fileName.textContent = file.name; | |
fileInfo.style.display = 'flex'; | |
sendAudioFile(file); | |
} | |
} | |
function clearAudioFile() { | |
audioFileInput.value = ''; | |
fileInfo.style.display = 'none'; | |
} | |
async function sendAudioFile(file) { | |
if (!currentChatId) return; | |
appendAndSaveMessage("user", "Загружен аудиофайл..."); | |
try { | |
const formData = new FormData(); | |
formData.append("audio", file); | |
formData.append("chat_id", currentChatId); | |
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)}%)`); | |
clearAudioFile(); | |
} 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 () => { | |
const audioBlob = new Blob(audioChunks, { type: "audio/wav" }); | |
sendAudioBlob(audioBlob); | |
}; | |
mediaRecorder.start(); | |
recordBtn.disabled = true; | |
stopBtn.disabled = false; | |
appendMessage("user", "Запись начата..."); | |
} catch (error) { | |
console.error("Ошибка записи:", error); | |
appendMessage("bot", "❌ Не удалось получить доступ к микрофону"); | |
} | |
} | |
function stopRecording() { | |
if (mediaRecorder?.state === "recording") { | |
mediaRecorder.stop(); | |
recordBtn.disabled = false; | |
stopBtn.disabled = true; | |
audioStream.getTracks().forEach(track => track.stop()); | |
} | |
} | |
async function sendAudioBlob(audioBlob) { | |
if (!currentChatId) return; | |
appendAndSaveMessage("user", "Отправлено голосовое сообщение..."); | |
try { | |
const formData = new FormData(); | |
formData.append("audio", audioBlob, "recording.wav"); | |
formData.append("chat_id", currentChatId); | |
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}`); | |
} | |
} | |
// Вспомогательные функции | |
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", | |
"X-CSRFToken": getCSRFToken() | |
}, | |
body: JSON.stringify({ | |
chat_id: currentChatId, | |
sender: sender, | |
content: text | |
}) | |
}).catch(console.error); | |
} | |
} | |
function getCSRFToken() { | |
const meta = document.querySelector('meta[name="csrf-token"]'); | |
return meta ? meta.content : ''; | |
} | |
}); |