Aist1 commited on
Commit
b8b23c0
·
verified ·
1 Parent(s): 8128df5

Update static/script.js

Browse files
Files changed (1) hide show
  1. static/script.js +312 -10
static/script.js CHANGED
@@ -1,20 +1,196 @@
1
- // Добавьте эту функцию в script.js
2
- async function loadJournalEntries() {
 
 
 
 
 
 
 
 
3
  try {
4
- const response = await fetch('/journal_entries');
 
 
 
 
 
 
 
 
 
 
5
  const data = await response.json();
6
 
7
- if (data.entries) {
8
- data.entries.forEach(entry => {
9
- addJournalEntry(entry);
10
- });
11
  }
 
 
12
  } catch (error) {
13
- console.error('Ошибка загрузки записей:', error);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  }
15
  }
16
 
17
- // Обновите функцию addJournalEntry для обработки уже существующих записей
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  function addJournalEntry(entry) {
19
  const container = document.getElementById('journalEntries');
20
  const entryElement = document.createElement('div');
@@ -40,8 +216,134 @@ function addJournalEntry(entry) {
40
  container.insertBefore(entryElement, container.firstChild);
41
  }
42
 
43
- // Обновите обработчик DOMContentLoaded
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  document.addEventListener('DOMContentLoaded', function() {
 
45
  loadJournalEntries();
46
  loadProgress();
47
  });
 
1
+ // Основные функции для работы с приложением
2
+ async function analyzeEmotions() {
3
+ const text = document.getElementById('textInput').value;
4
+ if (!text.trim()) {
5
+ showError('Пожалуйста, введите текст для анализа');
6
+ return;
7
+ }
8
+
9
+ showLoading('analysisResult', 'Анализируем эмоции...');
10
+
11
  try {
12
+ const response = await fetch('/analyze', {
13
+ method: 'POST',
14
+ headers: {
15
+ 'Content-Type': 'application/json',
16
+ },
17
+ body: JSON.stringify({
18
+ text: text,
19
+ type: 'emotion'
20
+ })
21
+ });
22
+
23
  const data = await response.json();
24
 
25
+ if (data.error) {
26
+ showError(data.error, 'analysisResult');
27
+ return;
 
28
  }
29
+
30
+ displayEmotionAnalysis(data);
31
  } catch (error) {
32
+ showError('Ошибка при анализе: ' + error.message, 'analysisResult');
33
+ }
34
+ }
35
+
36
+ async function analyzePersonality() {
37
+ const text = document.getElementById('textInput').value;
38
+ if (!text.trim()) {
39
+ showError('Пожалуйста, введите текст для анализа');
40
+ return;
41
+ }
42
+
43
+ showLoading('analysisResult', 'Анализируем паттерны мышления...');
44
+
45
+ try {
46
+ const response = await fetch('/analyze', {
47
+ method: 'POST',
48
+ headers: {
49
+ 'Content-Type': 'application/json',
50
+ },
51
+ body: JSON.stringify({
52
+ text: text,
53
+ type: 'personality'
54
+ })
55
+ });
56
+
57
+ const data = await response.json();
58
+
59
+ if (data.error) {
60
+ showError(data.error, 'analysisResult');
61
+ return;
62
+ }
63
+
64
+ displayPersonalityAnalysis(data);
65
+ } catch (error) {
66
+ showError('Ошибка при анализе: ' + error.message, 'analysisResult');
67
  }
68
  }
69
 
70
+ async function saveToJournal() {
71
+ const text = document.getElementById('textInput').value;
72
+ if (!text.trim()) {
73
+ showError('Пожалуйста, введите запись для дневника');
74
+ return;
75
+ }
76
+
77
+ try {
78
+ const response = await fetch('/journal', {
79
+ method: 'POST',
80
+ headers: {
81
+ 'Content-Type': 'application/json',
82
+ },
83
+ body: JSON.stringify({
84
+ entry: text
85
+ })
86
+ });
87
+
88
+ const data = await response.json();
89
+
90
+ if (data.error) {
91
+ showError(data.error);
92
+ return;
93
+ }
94
+
95
+ // Очищаем поле ввода
96
+ document.getElementById('textInput').value = '';
97
+
98
+ // Добавляем запись в дневник
99
+ addJournalEntry(data.entry);
100
+
101
+ showSuccess('Запись успешно сохранена в дневник!');
102
+ } catch (error) {
103
+ showError('Ошибка при сохранении: ' + error.message);
104
+ }
105
+ }
106
+
107
+ async function getInsights() {
108
+ showLoading('insightsResult', 'Генерируем инсайты...');
109
+
110
+ try {
111
+ const response = await fetch('/insights');
112
+ const data = await response.json();
113
+
114
+ if (data.error) {
115
+ showError(data.error, 'insightsResult');
116
+ return;
117
+ }
118
+
119
+ displayInsights(data.insights);
120
+ } catch (error) {
121
+ showError('Ошибка при получении инсайтов: ' + error.message, 'insightsResult');
122
+ }
123
+ }
124
+
125
+ // Функции отображения результатов
126
+ function displayEmotionAnalysis(data) {
127
+ const container = document.getElementById('analysisResult');
128
+ let html = '<h3>Эмоциональный анализ:</h3>';
129
+
130
+ if (data.dominant_emotion) {
131
+ html += `<div class="dominant-emotion">
132
+ <strong>Преобладающая эмоция:</strong> ${data.dominant_emotion.label}
133
+ (${(data.dominant_emotion.score * 100).toFixed(1)}%)
134
+ </div>`;
135
+ }
136
+
137
+ html += '<h4>Все обнаруженные эмоции:</h4>';
138
+ if (data.emotions && data.emotions.length > 0) {
139
+ data.emotions.forEach(emotion => {
140
+ const percentage = (emotion.score * 100).toFixed(1);
141
+ html += `
142
+ <div class="emotion-item">
143
+ <span>${emotion.label}</span>
144
+ <span class="emotion-score">${percentage}%</span>
145
+ </div>
146
+ `;
147
+ });
148
+ } else {
149
+ html += '<p>Не удалось определить эмоции</p>';
150
+ }
151
+
152
+ container.innerHTML = html;
153
+ }
154
+
155
+ function displayPersonalityAnalysis(data) {
156
+ const container = document.getElementById('analysisResult');
157
+ let html = '<h3>Анализ паттернов:</h3>';
158
+
159
+ if (data.traits) {
160
+ html += `
161
+ <div class="trait-item">
162
+ <strong>Эмоциональная стабильность:</strong>
163
+ ${(data.traits.emotional_stability * 100).toFixed(1)}%
164
+ </div>
165
+ <div class="trait-item">
166
+ <strong>Позитивность:</strong>
167
+ ${(data.traits.positivity * 100).toFixed(1)}%
168
+ </div>
169
+ <div class="trait-item">
170
+ <strong>Сложность мышления:</strong>
171
+ ${(data.traits.complexity * 100).toFixed(1)}%
172
+ </div>
173
+ <div class="trait-item">
174
+ <strong>Последовательность:</strong>
175
+ ${(data.traits.consistency * 100).toFixed(1)}%
176
+ </div>
177
+ `;
178
+ } else {
179
+ html += '<p>Не удалось проанализировать паттерны</p>';
180
+ }
181
+
182
+ container.innerHTML = html;
183
+ }
184
+
185
+ function displayInsights(insights) {
186
+ const container = document.getElementById('insightsResult');
187
+ container.innerHTML = `
188
+ <div class="insight-text">
189
+ "${insights}"
190
+ </div>
191
+ `;
192
+ }
193
+
194
  function addJournalEntry(entry) {
195
  const container = document.getElementById('journalEntries');
196
  const entryElement = document.createElement('div');
 
216
  container.insertBefore(entryElement, container.firstChild);
217
  }
218
 
219
+ // Загрузка записей дневника при старте
220
+ async function loadJournalEntries() {
221
+ try {
222
+ const response = await fetch('/journal_entries');
223
+ const data = await response.json();
224
+
225
+ if (data.entries && data.entries.length > 0) {
226
+ data.entries.forEach(entry => {
227
+ addJournalEntry(entry);
228
+ });
229
+ }
230
+ } catch (error) {
231
+ console.error('Ошибка загрузки записей:', error);
232
+ }
233
+ }
234
+
235
+ async function loadProgress() {
236
+ try {
237
+ const response = await fetch('/progress');
238
+ const data = await response.json();
239
+
240
+ const progressContainer = document.getElementById('progressContent');
241
+
242
+ if (data.message) {
243
+ progressContainer.innerHTML = `<p>${data.message}</p>`;
244
+ return;
245
+ }
246
+
247
+ if (data.error) {
248
+ progressContainer.innerHTML = `<p class="error">${data.error}</p>`;
249
+ return;
250
+ }
251
+
252
+ let html = `
253
+ <div class="progress-stats">
254
+ <div class="stat-item">
255
+ <div class="stat-value">${data.total_entries}</div>
256
+ <div class="stat-label">Всего записей</div>
257
+ </div>
258
+ <div class="stat-item">
259
+ <div class="stat-value">${(data.consistency_score * 100).toFixed(0)}%</div>
260
+ <div class="stat-label">Регулярность</div>
261
+ </div>
262
+ </div>
263
+ `;
264
+
265
+ progressContainer.innerHTML = html;
266
+ } catch (error) {
267
+ console.error('Ошибка загрузки прогресса:', error);
268
+ document.getElementById('progressContent').innerHTML =
269
+ '<p class="error">Ошибка загрузки прогресса</p>';
270
+ }
271
+ }
272
+
273
+ // Вспомогательные функции
274
+ function showLoading(containerId, message = 'Загрузка...') {
275
+ const container = document.getElementById(containerId);
276
+ if (container) {
277
+ container.innerHTML = `
278
+ <div class="loading">${message}</div>
279
+ `;
280
+ }
281
+ }
282
+
283
+ function showError(message, containerId = null) {
284
+ if (containerId) {
285
+ const container = document.getElementById(containerId);
286
+ if (container) {
287
+ container.innerHTML = `
288
+ <div class="error">${message}</div>
289
+ `;
290
+ }
291
+ } else {
292
+ // Показываем временное уведомление
293
+ const notification = document.createElement('div');
294
+ notification.className = 'error';
295
+ notification.style.cssText = `
296
+ position: fixed;
297
+ top: 20px;
298
+ right: 20px;
299
+ background: #fed7d7;
300
+ color: #c53030;
301
+ padding: 15px 20px;
302
+ border-radius: 8px;
303
+ z-index: 1000;
304
+ box-shadow: 0 4px 12px rgba(0,0,0,0.3);
305
+ border-left: 4px solid #c53030;
306
+ `;
307
+ notification.textContent = message;
308
+
309
+ document.body.appendChild(notification);
310
+
311
+ setTimeout(() => {
312
+ if (document.body.contains(notification)) {
313
+ document.body.removeChild(notification);
314
+ }
315
+ }, 5000);
316
+ }
317
+ }
318
+
319
+ function showSuccess(message) {
320
+ const notification = document.createElement('div');
321
+ notification.style.cssText = `
322
+ position: fixed;
323
+ top: 20px;
324
+ right: 20px;
325
+ background: #48bb78;
326
+ color: white;
327
+ padding: 15px 20px;
328
+ border-radius: 8px;
329
+ z-index: 1000;
330
+ box-shadow: 0 4px 12px rgba(0,0,0,0.3);
331
+ border-left: 4px solid #38a169;
332
+ `;
333
+ notification.textContent = message;
334
+
335
+ document.body.appendChild(notification);
336
+
337
+ setTimeout(() => {
338
+ if (document.body.contains(notification)) {
339
+ document.body.removeChild(notification);
340
+ }
341
+ }, 3000);
342
+ }
343
+
344
+ // Инициализация при загрузке страницы
345
  document.addEventListener('DOMContentLoaded', function() {
346
+ console.log('Приложение загружено');
347
  loadJournalEntries();
348
  loadProgress();
349
  });