File size: 11,219 Bytes
b8b23c0
 
 
 
 
 
 
 
 
 
2821b6c
b8b23c0
 
 
 
 
 
 
 
 
 
 
2821b6c
 
b8b23c0
 
 
2821b6c
b8b23c0
 
2821b6c
b8b23c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2821b6c
 
 
b8b23c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2821b6c
 
 
 
 
 
 
 
 
 
 
9e1764c
2821b6c
 
 
 
 
 
 
 
 
 
 
 
 
b8b23c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2821b6c
b8b23c0
9e1764c
2821b6c
9e1764c
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// Основные функции для работы с приложением
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 = '<h3>Эмоциональный анализ:</h3>';
    
    if (data.dominant_emotion) {
        html += `<div class="dominant-emotion">
            <strong>Преобладающая эмоция:</strong> ${data.dominant_emotion.label} 
            (${(data.dominant_emotion.score * 100).toFixed(1)}%)
        </div>`;
    }
    
    html += '<h4>Все обнаруженные эмоции:</h4>';
    if (data.emotions && data.emotions.length > 0) {
        data.emotions.forEach(emotion => {
            const percentage = (emotion.score * 100).toFixed(1);
            html += `
                <div class="emotion-item">
                    <span>${emotion.label}</span>
                    <span class="emotion-score">${percentage}%</span>
                </div>
            `;
        });
    } else {
        html += '<p>Не удалось определить эмоции</p>';
    }
    
    container.innerHTML = html;
}

function displayPersonalityAnalysis(data) {
    const container = document.getElementById('analysisResult');
    let html = '<h3>Анализ паттернов:</h3>';
    
    if (data.traits) {
        html += `
            <div class="trait-item">
                <strong>Эмоциональная стабильность:</strong> 
                ${(data.traits.emotional_stability * 100).toFixed(1)}%
            </div>
            <div class="trait-item">
                <strong>Позитивность:</strong> 
                ${(data.traits.positivity * 100).toFixed(1)}%
            </div>
            <div class="trait-item">
                <strong>Сложность мышления:</strong> 
                ${(data.traits.complexity * 100).toFixed(1)}%
            </div>
            <div class="trait-item">
                <strong>Последовательность:</strong> 
                ${(data.traits.consistency * 100).toFixed(1)}%
            </div>
        `;
    } else {
        html += '<p>Не удалось проанализировать паттерны</p>';
    }
    
    container.innerHTML = html;
}

function displayInsights(insights) {
    const container = document.getElementById('insightsResult');
    container.innerHTML = `
        <div class="insight-text">
            "${insights}"
        </div>
    `;
}

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 = '<div class="entry-emotions">';
        entry.emotions.forEach(emotion => {
            emotionsHtml += `<span class="emotion-tag">${emotion.label} (${(emotion.score * 100).toFixed(0)}%)</span>`;
        });
        emotionsHtml += '</div>';
    }
    
    entryElement.innerHTML = `
        <div class="entry-date">${date}</div>
        <div class="entry-text">${entry.text}</div>
        ${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 = `<p>${data.message}</p>`;
            return;
        }
        
        if (data.error) {
            progressContainer.innerHTML = `<p class="error">${data.error}</p>`;
            return;
        }
        
        let html = `
            <div class="progress-stats">
                <div class="stat-item">
                    <div class="stat-value">${data.total_entries}</div>
                    <div class="stat-label">Всего записей</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${(data.consistency_score * 100).toFixed(0)}%</div>
                    <div class="stat-label">Регулярность</div>
                </div>
            </div>
        `;
        
        progressContainer.innerHTML = html;
    } catch (error) {
        console.error('Ошибка загрузки прогресса:', error);
        document.getElementById('progressContent').innerHTML = 
            '<p class="error">Ошибка загрузки прогресса</p>';
    }
}

// Вспомогательные функции
function showLoading(containerId, message = 'Загрузка...') {
    const container = document.getElementById(containerId);
    if (container) {
        container.innerHTML = `
            <div class="loading">${message}</div>
        `;
    }
}

function showError(message, containerId = null) {
    if (containerId) {
        const container = document.getElementById(containerId);
        if (container) {
            container.innerHTML = `
                <div class="error">${message}</div>
            `;
        }
    } 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();
});