Serg234 commited on
Commit
838f69f
·
verified ·
1 Parent(s): 513d0d7

Upload 8 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ pic/clases.png filter=lfs diff=lfs merge=lfs -text
ace_diff_gradio.py ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from app_function import *
3
+ from plot_function import calculate_plot, predict_plot
4
+
5
+
6
+ def run_test():
7
+ with gr.Blocks(title="Адденбрукский когнитивный тест (ACE-III)") as demo:
8
+ gr.Markdown("# Адденбрукский когнитивный тест (ACE-III)")
9
+
10
+
11
+ with gr.Row():
12
+ with gr.Column(scale=2):
13
+ gr.Markdown("""
14
+ ## Описание теста ACE-III
15
+
16
+ **Адденбрукский когнитивный тест (ACE-III)** - это скрининговый инструмент
17
+ для диагностики когнитивных нарушений и деменций. Является усовершенствованной
18
+ версией теста ACE-R.
19
+
20
+ ### Основные характеристики:
21
+ - Оценивает 5 когнитивных доменов:
22
+ 1. Внимание и концентрация
23
+ 2. Память
24
+ 3. Речевые функции
25
+ 4. Визуально-пространственные способности
26
+ 5. Ориентация
27
+ - Общее максимальное количество баллов: 100
28
+ - Время проведения: 15-20 минут
29
+ - Чувствительность для выявления деменции: 84-94%
30
+
31
+ ### Интерпретация результатов:
32
+ - 88-100 баллов: норма
33
+ - 82-87 баллов: легкие когнитивные нарушения
34
+ - Менее 82 баллов: вероятна деменция
35
+
36
+ Тест особенно полезен для дифференциальной диагностики между
37
+ болезнью Альцгеймера, лобно-височной деменцией и деменцией с тельцами Леви.
38
+ """)
39
+
40
+ with gr.Column(scale=1):
41
+
42
+ gr.Markdown("[Подробнее о тесте](https://www.sydney.edu.au/brain-mind/our-clinics/dementia-test.html#addenbrookes-cognitive-examination-iii)")
43
+
44
+ # Внимание
45
+ with gr.Tab("Внимание"):
46
+ gr.Markdown("## ВНИМАНИЕ")
47
+
48
+ with gr.Column():
49
+ time_orientation = gr.Slider(0, 5, label='Ориентирование во времени', value=0, step=1)
50
+ space_orientation = gr.Slider(0, 5, label='Ориентирование в пространстве', value=0, step=1)
51
+ three_words = gr.Slider(0, 3, label='Повторение 3-х слов', value=0, step=1)
52
+ calculate = gr.Slider(0, 5, label='Серийный счет (100-7 последовательно)', value=0, step=1)
53
+
54
+ total_att = gr.Number(label="Общий балл за внимание", value=0)
55
+
56
+ for slider in [time_orientation, space_orientation, three_words, calculate]:
57
+ slider.change(
58
+ fn=calculate_total,
59
+ inputs=[time_orientation, space_orientation, three_words, calculate],
60
+ outputs=total_att
61
+ )
62
+
63
+ # Память (исправлена опечатка в названии вкладки)
64
+ with gr.Tab("Память"):
65
+ gr.Markdown("## ПАМЯТЬ")
66
+
67
+ with gr.Column():
68
+ three_word_memory = gr.Slider(0, 3, label='Припоминание 3-х слов', value=0, step=1)
69
+ memory_adress = gr.Slider(0, 7, label='Запоминание адреса', value=0, step=1)
70
+ memory_president = gr.Slider(0, 4, label='Осведомленность (президент, премьер-министр)', value=0, step=1)
71
+ free_recall_adress = gr.Slider(0, 7, label='Свободное припоминание адреса', value=0, step=1)
72
+ choice_adress = gr.Slider(0, 5, label='Выбор из множества (подсказка)', value=0, step=1)
73
+
74
+ total_memory = gr.Number(label="Общий балл за память", value=0) # Исправлена подпись
75
+
76
+ for slider in [three_word_memory, memory_adress, memory_president, free_recall_adress, choice_adress]:
77
+ slider.change(
78
+ fn=calculate_memory,
79
+ inputs=[three_word_memory, memory_adress, memory_president, free_recall_adress, choice_adress],
80
+ outputs=total_memory
81
+ )
82
+
83
+ with gr.Tab("Беглость"):
84
+ gr.Markdown("## БЕГЛОСТЬ")
85
+
86
+ with gr.Column():
87
+ words_minuts = gr.Slider(0, 7, label='Балл за количество слов в минуту', value=0, step=1)
88
+ animal_minuts = gr.Slider(0, 7, label='Балл за число названных животных в минуту', value=0, step=1)
89
+
90
+
91
+ total_fluency = gr.Number(label="Общий балл за беглость", value=0) # Исправлена подпись
92
+
93
+ for slider in [words_minuts, animal_minuts]:
94
+ slider.change(
95
+ fn=calculate_fluency,
96
+ inputs=[words_minuts, animal_minuts],
97
+ outputs= total_fluency
98
+ )
99
+
100
+
101
+ with gr.Tab("Речь"):
102
+ gr.Markdown("## РЕЧЬ")
103
+
104
+ with gr.Column():
105
+ instruction = gr.Slider(0, 3, label='Понимание инструкций', value=0, step=1)
106
+ write_two_sentence = gr.Slider(0, 2, label='Написание двух предложений', value=0, step=1)
107
+ repit_words= gr.Slider(0, 2, label='Повторение', value=0, step=1)
108
+ repit_phrase = gr.Slider(0, 2, label='Повторение пословиц', value=0, step=1)
109
+ naming = gr.Slider(0, 12, label='Название', value=0, step=1)
110
+ understanding = gr.Slider(0, 4, label='Понимание', value=0, step=1)
111
+ reading = gr.Slider(0, 1, label='Чтение', value=0, step=1)
112
+
113
+
114
+ total_speech = gr.Number(label="Общий балл за речь", value=0) # Исправлена подпись
115
+
116
+ for slider in [instruction, write_two_sentence, repit_words, repit_phrase, naming, understanding, reading]:
117
+ slider.change(
118
+ fn=calculate_speech,
119
+ inputs=[instruction, write_two_sentence, repit_words, repit_phrase, naming, understanding, reading],
120
+ outputs= total_speech
121
+ )
122
+
123
+
124
+ with gr.Tab("зрительно-простраснтвенные способности"):
125
+ gr.Markdown("## ПРОСТРАНСТВО")
126
+
127
+ with gr.Column():
128
+ infinity = gr.Slider(0, 1, label='копирование бесконечностей', value=0, step=1)
129
+ cube = gr.Slider(0, 2, label='Копирование куба', value=0, step=1)
130
+ clock= gr.Slider(0, 5, label='Рисование часов', value=0, step=1)
131
+ punkt = gr.Slider(0, 4, label='Подсчет точек', value=0, step=1)
132
+ letters = gr.Slider(0, 4, label='Распознавание букв', value=0, step=1)
133
+
134
+
135
+ total_spatial = gr.Number(label="Общий балл за речь", value=0) # Исправлена подпись
136
+
137
+ for slider in [infinity, cube, clock, punkt, letters]:
138
+ slider.change(
139
+ fn=calculate_spatial,
140
+ inputs=[infinity, cube, clock, punkt, letters],
141
+ outputs= total_spatial
142
+ )
143
+
144
+
145
+
146
+
147
+
148
+ # Общий балл
149
+ with gr.Tab("Всего"):
150
+ gr.Markdown("## ОБЩИЙ БАЛЛ")
151
+
152
+ with gr.Column():
153
+ total_score = gr.Number(label="Общий балл по тесту", value=0)
154
+
155
+ # Обновляем общий балл при изменении баллов за внимание или память
156
+ total_att.change(
157
+ fn=calculate_overall,
158
+ inputs=[total_att, total_memory, total_fluency, total_speech, total_spatial],
159
+ outputs=total_score
160
+ )
161
+
162
+ total_memory.change(
163
+ fn=calculate_overall,
164
+ inputs=[total_att, total_memory, total_fluency, total_speech, total_spatial],
165
+ outputs=total_score
166
+ )
167
+
168
+ total_fluency.change(
169
+ fn=calculate_overall,
170
+ inputs=[total_att, total_memory, total_fluency, total_speech, total_spatial],
171
+ outputs=total_score
172
+ )
173
+
174
+ total_speech.change(
175
+ fn=calculate_overall,
176
+ inputs=[total_att, total_memory, total_fluency, total_speech, total_spatial],
177
+ outputs=total_score
178
+ )
179
+
180
+ total_spatial.change(
181
+ fn=calculate_overall,
182
+ inputs=[total_att, total_memory, total_fluency, total_speech, total_spatial],
183
+ outputs=total_score
184
+ )
185
+
186
+
187
+
188
+ with gr.Tab("Анализ"):
189
+ gr.Markdown("## Визуализация результатов")
190
+
191
+ with gr.Row():
192
+ # Колонка с графиком когнитивных функций
193
+ with gr.Column():
194
+ gr.Markdown("### Когнитивные функции")
195
+ cognitive_plot = gr.Plot()
196
+
197
+ # Обработчики для обновления графика функций
198
+ for component in [total_att, total_memory, total_fluency, total_speech, total_spatial]:
199
+ component.change(
200
+ fn=calculate_plot,
201
+ inputs=[total_att, total_memory, total_fluency, total_speech, total_spatial],
202
+ outputs=cognitive_plot
203
+ )
204
+
205
+ # Колонка с графиком предсказаний
206
+ with gr.Column():
207
+ gr.Markdown("### Прогноз модели")
208
+
209
+ age_slider = gr.Slider(20, 100, value=56, label="Возраст")
210
+ prediction_plot = gr.Plot()
211
+
212
+ predict_btn = gr.Button("Выполнить прогноз")
213
+ predict_btn.click(
214
+ fn=predict_plot,
215
+ inputs=[total_score, total_att, total_memory, total_fluency, total_speech, total_spatial, age_slider],
216
+ outputs=prediction_plot
217
+ )
218
+
219
+ with gr.Tab("Метрики"):
220
+ gr.Markdown("## Метрики классификации")
221
+
222
+ with gr.Row():
223
+ # Структура выборки
224
+ with gr.Column():
225
+ gr.Markdown("### Структура выборки")
226
+ gr.Image("pic/clases.png", label="Структура выборки")
227
+
228
+ # Confusion Matrix (готовая картинка)
229
+ with gr.Column():
230
+ gr.Markdown("### Confusion Matrix")
231
+ gr.Image("pic/confusion_matrix_neuon.png", label="Confusion Matrix")
232
+
233
+
234
+
235
+ # Метрики F1
236
+ with gr.Row():
237
+ with gr.Column():
238
+ gr.Markdown("### Метрики классификации")
239
+ metrics_table = gr.Dataframe(
240
+ headers=["Метрика", "Значение"],
241
+ datatype=["str", "number"],
242
+ row_count=4)
243
+
244
+ gr.Markdown("### F1-мера ")
245
+ # Пример готовых метрик
246
+ predefined_metrics = [
247
+ ["F1-мера (норма)", 0.92],
248
+ ["F1-мера (умеренные нарушения)", 0.90],
249
+ ["F1-мера (деменция)", 0.99],
250
+
251
+ ]
252
+ gr.Dataframe(
253
+ predefined_metrics,
254
+ headers=["Метрика", "Значение"],
255
+ datatype=["str", "number"],
256
+ row_count=4,
257
+ col_count=2,
258
+ interactive=False
259
+ )
260
+
261
+
262
+
263
+ return demo
264
+
265
+ if __name__ == "__main__":
266
+ demo = run_test()
267
+ demo.launch()
app_function.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ def calculate_total(time, space, words, calc):
3
+ return time + space + words + calc
4
+
5
+ def calculate_memory(words, adress, president, free_recall, choice):
6
+ return words + adress + president + free_recall + choice
7
+
8
+
9
+ def calculate_fluency(words, animal):
10
+ return words + animal
11
+
12
+ def calculate_speech(instruction, write, repit_words, repit_phrase, naming, understood, read ):
13
+ return instruction + write + repit_words + repit_phrase+ naming + understood + read
14
+
15
+ def calculate_spatial(infinity, cube, clock, punkt, letters):
16
+ return infinity + cube + clock + punkt + letters
17
+
18
+ def calculate_language(reading, writing, dict_words, dict_phrase, dict_naming, dict_understood, dict_read ):
19
+ return reading + writing + dict_words + dict_phrase+ dict_naming + dict_understood + dict_read
20
+
21
+ def calculate_att_score(total_att):
22
+ return total_att
23
+
24
+ def calculate_overall(att_score, memory_score, total_flue, total_speech, total_spatial):
25
+ return att_score + memory_score + total_flue + total_speech + total_spatial
mymodel.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4f09354d04d65005934753ce0c0b17d101a46ff6798973781679838bf7f1eadd
3
+ size 34250
pic/clases.png ADDED

Git LFS Details

  • SHA256: d33a4e3c5fdeaba18f5f4bf482ac87eb466dda572aa8c2e3a4332ee38ef98a12
  • Pointer size: 131 Bytes
  • Size of remote file: 115 kB
pic/confusion_matrix_neuon.png ADDED
plot_function.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import seaborn as sns
2
+ import matplotlib.pyplot as plt
3
+ import numpy as np
4
+ from predict_function import predict
5
+
6
+ def calculate_plot(total_att, total_memory, total_fluency, total_speech, total_spatial):
7
+
8
+
9
+ labels = ['Внимание', 'Память', 'Беглость', 'Речь', 'Пространство']
10
+ data = np.array([total_att, total_memory, total_fluency, total_speech, total_spatial], dtype=np.float32)
11
+ max_value = np.array([18, 26, 14, 26, 16 ], dtype=np.float32)
12
+ relative_data = np.divide(data, max_value )* 100
13
+ plt.close('all')
14
+ fig=plt.figure(figsize=(6, 5))
15
+ ax=sns.barplot(y=labels, x=relative_data, palette="Blues_d", hue=labels, legend=False)
16
+ # Добавляем подписи осей
17
+ ax.set_xlabel('Процент сохранных функций', fontsize=12, labelpad=10)
18
+ ax.set_ylabel('Когнитивные функции', fontsize=12, labelpad=10)
19
+
20
+
21
+ plt.xticks(fontsize=10)
22
+ plt.yticks(fontsize=10)
23
+ plt.title('Оценка когнитивных функций', fontsize=14, pad=20)
24
+
25
+
26
+ ax.grid(True, linestyle='--', alpha=0.3)
27
+
28
+
29
+
30
+ plt.title(f"Когнитивный профиль. Общий балл:{np.sum(data)}")
31
+
32
+
33
+ plt.tight_layout()
34
+
35
+ return fig
36
+
37
+ def predict_plot(total, total_att, total_memory, total_fluency, total_speech, total_spatial, age):
38
+
39
+ data=[total, total_att, total_memory, total_fluency, total_speech, total_spatial, age]
40
+
41
+ dict_data = predict(data)
42
+ # 3. Создание графика
43
+ plt.close('all') # Закрываем предыдущие графики
44
+ fig, ax=plt.subplots(figsize=(6,4)) # Увеличил размер для читаемости
45
+
46
+
47
+ # Сортируем по значениям для лучшего отображения
48
+ sorted_items = sorted(dict_data.items(), key=lambda x: x[1])
49
+ labels = [item[0] for item in sorted_items]
50
+ values = [item[1] for item in sorted_items]
51
+
52
+ # 5. Построение графика
53
+ bars = ax.barh(labels, values, color='skyblue')
54
+
55
+ # 6. Выделение максимального значения
56
+ max_idx = np.argmax(values)
57
+ bars[max_idx].set_color('green')
58
+
59
+ # 7. Добавление значений на график
60
+ for bar in bars:
61
+ width = bar.get_width()
62
+ ax.text(width + 0.01, bar.get_y() + bar.get_height()/2,
63
+ f'{width:.2f}',
64
+ va='center', ha='left', fontsize=9)
65
+
66
+ # 8. Настройка оформления
67
+ ax.set_title(f'Нарушения соответствуют: {labels[max_idx]}',
68
+ fontsize=12, pad=10)
69
+ ax.set_xlabel('Вероятность', fontsize=10)
70
+ ax.set_ylabel('Тип нарушений', fontsize=10)
71
+ ax.set_xlim(0, 1.1 if max(values) <= 1 else None) # Автоподбор границ
72
+
73
+ plt.tight_layout()
74
+ return fig
75
+
predict_function.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from onnxruntime import InferenceSession
3
+
4
+ '''
5
+ входные данные data=[batch, 7]
6
+ shape=(1, 7) 7 входных параметров
7
+ '''
8
+
9
+ def softmax(x):
10
+ e_x = np.exp(x - np.max(x))
11
+ return e_x / e_x.sum(axis=0)
12
+
13
+ def predict(data):
14
+
15
+ model = InferenceSession("mymodel.onnx")
16
+
17
+ label=['норма', 'умеренные когнитивные', 'демнция']
18
+
19
+ input_data=np.array(data, dtype=np.float32).reshape(1,-1)
20
+ outputs = model.run(
21
+ output_names=["output"],
22
+ input_feed={"input": input_data},
23
+ )
24
+
25
+ dict_predict=dict(zip(label, softmax(outputs[0][0])))
26
+ return dict_predict
27
+
28
+
requirements.txt ADDED
Binary file (2.51 kB). View file