// Основные функции для работы с приложением
async function analyzeEmotions() {
const text = document.getElementById('textInput').value;
if (!text.trim()) {
showError('Пожалуйста, введите текст для анализа');
return;
}
showLoading('analysisResult', 'Анализируем эмоции...');
try {
const response = await fetch('/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: text,
type: 'emotion'
})
});
const data = await response.json();
if (data.error) {
showError(data.error, 'analysisResult');
return;
}
displayEmotionAnalysis(data);
} catch (error) {
showError('Ошибка при анализе: ' + error.message, 'analysisResult');
}
}
async function analyzePersonality() {
const text = document.getElementById('textInput').value;
if (!text.trim()) {
showError('Пожалуйста, введите текст для анализа');
return;
}
showLoading('analysisResult', 'Анализируем паттерны мышления...');
try {
const response = await fetch('/analyze', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: text,
type: 'personality'
})
});
const data = await response.json();
if (data.error) {
showError(data.error, 'analysisResult');
return;
}
displayPersonalityAnalysis(data);
} catch (error) {
showError('Ошибка при анализе: ' + error.message, 'analysisResult');
}
}
async function saveToJournal() {
const text = document.getElementById('textInput').value;
if (!text.trim()) {
showError('Пожалуйста, введите запись для дневника');
return;
}
try {
const response = await fetch('/journal', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
entry: text
})
});
const data = await response.json();
if (data.error) {
showError(data.error);
return;
}
// Очищаем поле ввода
document.getElementById('textInput').value = '';
// Добавляем запись в дневник
addJournalEntry(data.entry);
showSuccess('Запись успешно сохранена в дневник!');
} catch (error) {
showError('Ошибка при сохранении: ' + error.message);
}
}
async function getInsights() {
showLoading('insightsResult', 'Генерируем инсайты...');
try {
const response = await fetch('/insights');
const data = await response.json();
if (data.error) {
showError(data.error, 'insightsResult');
return;
}
displayInsights(data.insights);
} catch (error) {
showError('Ошибка при получении инсайтов: ' + error.message, 'insightsResult');
}
}
// Функции отображения результатов
function displayEmotionAnalysis(data) {
const container = document.getElementById('analysisResult');
let html = '
Эмоциональный анализ:
';
if (data.dominant_emotion) {
html += `
Преобладающая эмоция: ${data.dominant_emotion.label}
(${(data.dominant_emotion.score * 100).toFixed(1)}%)
`;
}
html += 'Все обнаруженные эмоции:
';
if (data.emotions && data.emotions.length > 0) {
data.emotions.forEach(emotion => {
const percentage = (emotion.score * 100).toFixed(1);
html += `
${emotion.label}
${percentage}%
`;
});
} else {
html += 'Не удалось определить эмоции
';
}
container.innerHTML = html;
}
function displayPersonalityAnalysis(data) {
const container = document.getElementById('analysisResult');
let html = 'Анализ паттернов:
';
if (data.traits) {
html += `
Эмоциональная стабильность:
${(data.traits.emotional_stability * 100).toFixed(1)}%
Позитивность:
${(data.traits.positivity * 100).toFixed(1)}%
Сложность мышления:
${(data.traits.complexity * 100).toFixed(1)}%
Последовательность:
${(data.traits.consistency * 100).toFixed(1)}%
`;
} else {
html += 'Не удалось проанализировать паттерны
';
}
container.innerHTML = html;
}
function displayInsights(insights) {
const container = document.getElementById('insightsResult');
container.innerHTML = `
"${insights}"
`;
}
function addJournalEntry(entry) {
const container = document.getElementById('journalEntries');
const entryElement = document.createElement('div');
entryElement.className = 'journal-entry';
const date = new Date(entry.timestamp).toLocaleString('ru-RU');
let emotionsHtml = '';
if (entry.emotions && entry.emotions.length > 0) {
emotionsHtml = '';
entry.emotions.forEach(emotion => {
emotionsHtml += `${emotion.label} (${(emotion.score * 100).toFixed(0)}%)`;
});
emotionsHtml += '
';
}
entryElement.innerHTML = `
${date}
${entry.text}
${emotionsHtml}
`;
container.insertBefore(entryElement, container.firstChild);
}
// Загрузка записей дневника при старте
async function loadJournalEntries() {
try {
const response = await fetch('/journal_entries');
const data = await response.json();
if (data.entries && data.entries.length > 0) {
data.entries.forEach(entry => {
addJournalEntry(entry);
});
}
} catch (error) {
console.error('Ошибка загрузки записей:', error);
}
}
async function loadProgress() {
try {
const response = await fetch('/progress');
const data = await response.json();
const progressContainer = document.getElementById('progressContent');
if (data.message) {
progressContainer.innerHTML = `${data.message}
`;
return;
}
if (data.error) {
progressContainer.innerHTML = `${data.error}
`;
return;
}
let html = `
${data.total_entries}
Всего записей
${(data.consistency_score * 100).toFixed(0)}%
Регулярность
`;
progressContainer.innerHTML = html;
} catch (error) {
console.error('Ошибка загрузки прогресса:', error);
document.getElementById('progressContent').innerHTML =
'Ошибка загрузки прогресса
';
}
}
// Вспомогательные функции
function showLoading(containerId, message = 'Загрузка...') {
const container = document.getElementById(containerId);
if (container) {
container.innerHTML = `
${message}
`;
}
}
function showError(message, containerId = null) {
if (containerId) {
const container = document.getElementById(containerId);
if (container) {
container.innerHTML = `
${message}
`;
}
} else {
// Показываем временное уведомление
const notification = document.createElement('div');
notification.className = 'error';
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #fed7d7;
color: #c53030;
padding: 15px 20px;
border-radius: 8px;
z-index: 1000;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
border-left: 4px solid #c53030;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
if (document.body.contains(notification)) {
document.body.removeChild(notification);
}
}, 5000);
}
}
function showSuccess(message) {
const notification = document.createElement('div');
notification.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
background: #48bb78;
color: white;
padding: 15px 20px;
border-radius: 8px;
z-index: 1000;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
border-left: 4px solid #38a169;
`;
notification.textContent = message;
document.body.appendChild(notification);
setTimeout(() => {
if (document.body.contains(notification)) {
document.body.removeChild(notification);
}
}, 3000);
}
// Инициализация при загрузке страницы
document.addEventListener('DOMContentLoaded', function() {
console.log('Приложение загружено');
loadJournalEntries();
loadProgress();
});