File size: 49,565 Bytes
5778478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e81c62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a118ca2
 
 
 
 
 
 
 
 
 
 
 
17062f6
a118ca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5778478
a118ca2
 
 
 
 
 
 
 
 
 
5778478
a118ca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5778478
3e81c62
a118ca2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5778478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a118ca2
5778478
a118ca2
 
 
 
 
 
 
 
5778478
a118ca2
 
 
5778478
a118ca2
 
 
 
 
 
5778478
3e81c62
5778478
 
a118ca2
 
5778478
a118ca2
 
 
5778478
 
 
 
 
 
 
a118ca2
 
 
 
5778478
 
 
 
 
 
 
a118ca2
 
 
 
5778478
 
 
a118ca2
 
5778478
 
 
 
 
 
 
 
 
 
 
 
3e81c62
 
 
 
 
 
 
 
 
5778478
3e81c62
5778478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e81c62
5778478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a118ca2
5778478
 
3e81c62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5778478
3e81c62
5778478
 
 
 
 
3e81c62
5778478
 
a118ca2
604595a
a118ca2
5778478
a118ca2
 
 
5778478
a118ca2
 
 
3e81c62
a118ca2
 
 
 
5778478
a118ca2
 
 
 
5778478
a118ca2
 
 
 
5778478
a118ca2
 
5778478
a118ca2
 
5778478
a118ca2
5778478
 
 
 
 
 
a118ca2
5778478
 
a118ca2
 
5778478
 
 
a118ca2
 
5778478
 
a118ca2
 
5778478
 
 
 
a118ca2
5778478
a118ca2
 
 
 
5778478
a118ca2
 
5778478
 
 
 
 
 
 
 
 
 
 
 
a118ca2
5778478
 
a118ca2
5778478
 
 
a118ca2
5778478
6f4a782
 
 
 
 
 
5778478
3e81c62
 
 
 
 
a118ca2
5778478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
# import streamlit as st
# import tempfile
# import os
# import nibabel as nib
# import numpy as np
# import plotly.graph_objects as go
# from scipy.ndimage import zoom
# import time
# import random
# import threading

# # Set the page layout to wide
# st.set_page_config(layout="wide")

# st.logo("resources/biomedia.png")

# st.markdown(
#     """
#     <style>
#     /* Change the font size of the sidebar */
#     .sidebar .sidebar-content {
#         font-size: 2px;  
#     }
#     /* Change the line spacing of the sidebar */
#     .sidebar .sidebar-content p {
#         line-height: 0.2;  /* Adjust the line height as needed */
#     }
#     </style>
#     """,
#     unsafe_allow_html=True
# )

# st.title('MRI Scan Visualization :brain:')

# st.write("""
#          The **MRI Visualization** page offers an interactive platform for users to explore 3D MRI scans in detail. It is designed to enhance the understanding of anatomical structures and any associated segmentation data. This feature is particularly useful for clinicians, researchers, and students who wish to examine specific regions of interest within the brain.
# """)

# with st.expander("### **Features:**"):
#     st.write("""
#     - **Upload MRI Scans:**
#         - Users can upload their own 3D MRI scans in NIfTI format (`.nii` or `.nii.gz`).
#         - An optional checkbox allows users to upload a corresponding segmentation mask if available.
    
#     - **Interactive Slice Navigation:**
#         - Provides axial, coronal, and sagittal views of the MRI scan.
#         - Users can scroll through slices in each plane using sliders or arrow keys.
#         - Real-time updates as users navigate through different slices.

#     - **Segmentation Overlay:**
#         - When a segmentation mask is provided, it overlays onto the MRI images.
#         - Segmented regions are highlighted with transparent colors to maintain visibility of underlying anatomy.

#     - **Segmentation Labels:**
#         - A legend or sidebar displays the labels corresponding to different segmented regions.
#         - Hovering over a segmented area in the image highlights the corresponding label in the legend.
#         - Provides detailed information about each structure, such as name and assigned label value.

#     - **Visualization Controls:**
#         - Zoom and pan functionalities for detailed examination of specific areas.
#     """)

# with st.expander("## **Instructions:**"):
#     st.write("""
#     1. **Upload Your MRI Scan:**
#         - Use the file uploader to select your MRI scan file.
#         - Supported formats: NIfTI (`.nii`, `.nii.gz`).

#     2. **Upload Segmentation Mask (Optional):**
#         - If you have a segmentation mask, check the **"Include Segmentation Mask"** checkbox.
#         - Upload your segmentation mask file in NIfTI format.

#     3. **View MRI Slices:**
#         - After uploading, the application will display the MRI scan in three views: axial, coronal, and sagittal.
#         - Use the sliders beneath each image to navigate through the slices.
#         - The slice number and anatomical location are displayed for reference.

#     4. **Interact with the Images:**
#         - Zoom in and out using the scroll wheel or zoom controls.
#         - Pan across the image by clicking and dragging.
#     """)

# uploaded_file = st.file_uploader("Upload MRI file", type=["gz", "nii", "nii.gz"])

# segments = st.checkbox("Show Segmentation")
# segmentation_file = None

# if segments:
#     segmentation_file = st.file_uploader("Upload segmentation file", type=["gz", "nii", "nii.gz"])

# # Define segmentation colors
# segmentation_colors = {
#     0: '#000000',  # Background (black)
#     2: '#759479',  # Left cerebral white matter (purple)
#     3: '#f7d587',  # Left cerebral cortex (orange)
#     4: '#bb7761',  # Left lateral ventricle (brown)
#     5: '#53bad5',  # Left inferior lateral ventricle (cyan)
#     7: '#e95c47',  # Left cerebellum white matter (red)
#     8: '#ec7c5e',  # Left cerebellum cortex (light salmon)
#     10: '#6cf185', # Left thalamus (green)
#     11: '#ce6253', # Left caudate (brown)
#     12: '#d6f600', # Left putamen (yellow)
#     13: '#513e00', # Left pallidum (saddle brown)
#     14: '#fffad9', # 3rd ventricle (white)
#     15: '#e8dc00', # 4th ventricle (yellow)
#     16: '#c8c8ee', # Brain-stem (lavender)
#     17: '#fafacd', # Left hippocampus (lemon chiffon)
#     18: '#fad500', # Left amygdala (yellow)
#     24: '#009ad3', # CSF (cyan)
#     26: '#e95c47', # Left accumbens area (red)
#     28: '#bc9be1', # Left ventral DC (lavender)
#     41: '#afd7d3', # Right cerebral white matter (light cyan)
#     42: '#8ebed1', # Right cerebral cortex (light blue)
#     43: '#53bad5', # Right lateral ventricle (cyan)
#     44: '#a9d5f5', # Right inferior lateral ventricle (cyan)
#     46: '#00af5c', # Right cerebellum white matter (light green)
#     47: '#4ac87c', # Right cerebellum cortex (pale green)
#     49: '#00bfff', # Right thalamus (cyan)
#     50: '#009400', # Right caudate (green)
#     51: '#d2e772', # Right putamen (green yellow)
#     52: '#513e00', # Right pallidum (saddle brown)
#     53: '#d0ffff', # Right hippocampus (light cyan)
#     54: '#90fdfb', # Right amygdala (cyan)
#     58: '#6de3e6', # Right accumbens area (cyan)
#     60: '#cc3400', # Right ventral DC (red)
# }

# def create_plotly_colorscale(segmentation_colors):
#     max_value = max(segmentation_colors.keys())
#     colorscale = []
#     for i in range(max_value + 1):
#         color = segmentation_colors.get(i, '#000000')
#         colorscale.append([i / max_value, color])
#     return colorscale

# # Create the Plotly-compatible colorscale
# segmentation_colorscale = create_plotly_colorscale(segmentation_colors)

# def get_label_name(value):
#     label_names = {
#         2: 'Left cerebral white matter',
#         3: 'Left cerebral cortex',
#         4: 'Left lateral ventricle',
#         5: 'Left inferior lateral ventricle',
#         7: 'Left cerebellum white matter',
#         8: 'Left cerebellum cortex',
#         10: 'Left thalamus',
#         11: 'Left caudate',
#         12: 'Left putamen',
#         13: 'Left pallidum',
#         14: '3rd ventricle',
#         15: '4th ventricle',
#         16: 'Brain-stem',
#         17: 'Left hippocampus',
#         18: 'Left amygdala',
#         24: 'CSF',
#         26: 'Left accumbens area',
#         28: 'Left ventral DC',
#         41: 'Right cerebral white matter',
#         42: 'Right cerebral cortex',
#         43: 'Right lateral ventricle',
#         44: 'Right inferior lateral ventricle',
#         46: 'Right cerebellum white matter',
#         47: 'Right cerebellum cortex',
#         49: 'Right thalamus',
#         50: 'Right caudate',
#         51: 'Right putamen',
#         52: 'Right pallidum',
#         53: 'Right hippocampus',
#         54: 'Right amygdala',
#         58: 'Right accumbens area',
#         60: 'Right ventral DC',
#     }
#     return label_names.get(value, f'Unknown ({value})')

# def add_segmentation_legend_sidebar():
#     st.sidebar.title("Segmentation Labels")
#     for value, color in segmentation_colors.items():
#         if value != 0:  # Skip background
#             st.sidebar.markdown(f"<span style='color:{color};'>⬤</span> {get_label_name(value)}", unsafe_allow_html=True)


# def plot_mri_slice(data, seg_data, view, pixel_spacing, slice_thickness):
#     if view == 'Axial':
#         data = np.flip(data, axis=0)
#         seg_data = np.flip(seg_data, axis=0)
#         aspect_ratio = slice_thickness / pixel_spacing[0]
#         height = 800
#         num_slices = data.shape[1]
#     elif view == 'Coronal':
#         aspect_ratio = slice_thickness / pixel_spacing[0]
#         height = 400
#         num_slices = data.shape[0]
#     elif view == 'Sagittal':
#         aspect_ratio = pixel_spacing[1] / pixel_spacing[0]
#         height = 400
#         num_slices = data.shape[2]

#     fig = go.Figure()

#     frames = []
#     for i in range(num_slices):
#         if view == 'Axial':
#             img = data[:, i, :]
#             seg_img = seg_data[:, i, :]
#         elif view == 'Coronal':
#             img = data[i, :, :]
#             seg_img = seg_data[i, :, :]
#         elif view == 'Sagittal':
#             img = np.rot90(data[:, :, i])
#             img = np.flip(img, axis=0)
#             seg_img = np.rot90(seg_data[:, :, i])
#             seg_img = np.flip(seg_img, axis=0)

#         # Create hover text matrix
#         hover_text = np.full(seg_img.shape, '', dtype='object')
#         for y in range(seg_img.shape[0]):
#             for x in range(seg_img.shape[1]):
#                 label_value = int(seg_img[y, x])
#                 if label_value != 0:  # Skip background
#                     hover_text[y, x] = get_label_name(label_value)

#         frame = go.Frame(
#             data=[
#                 go.Heatmap(z=img, colorscale='gray', showscale=False),
#                 go.Heatmap(
#                     z=seg_img,
#                     colorscale=segmentation_colorscale,
#                     showscale=False,
#                     opacity=0.5,
#                     hoverinfo='text',
#                     text=hover_text,
#                     hoverongaps=False
#                 )
#             ],
#             name=f'slice{i}',
#             layout=go.Layout()
#         )
#         frames.append(frame)

#     fig.frames = frames

#     # Add the middle slice as the initial visible layer
#     middle_slice = num_slices // 2
#     middle_hover_text = np.full(frames[middle_slice].data[1].z.shape, '', dtype='object')
#     for y in range(frames[middle_slice].data[1].z.shape[0]):
#         for x in range(frames[middle_slice].data[1].z.shape[1]):
#             label_value = int(frames[middle_slice].data[1].z[y, x])
#             if label_value != 0:
#                 middle_hover_text[y, x] = get_label_name(label_value)

#     fig.add_trace(go.Heatmap(z=frames[middle_slice].data[0].z, colorscale='gray', showscale=False))
#     fig.add_trace(go.Heatmap(
#         z=frames[middle_slice].data[1].z,
#         colorscale=segmentation_colorscale,
#         showscale=False,
#         opacity=0.5,
#         hoverinfo='text',
#         text=middle_hover_text,
#         hoverongaps=False
#     ))

#     fig.update_layout(
#         title=f'{view} View',
#         xaxis=dict(title='X-axis', scaleanchor='y', scaleratio=aspect_ratio),
#         yaxis=dict(title='Y-axis'),
#         height=height,
#         margin=dict(l=0, r=0, t=30, b=0),
#         xaxis_visible=False,
#         yaxis_visible=False,
#         updatemenus=[{
#             'buttons': [
#                 {
#                     'args': [None, {'frame': {'duration': 100, 'redraw': True}, 'fromcurrent': True, 'mode': 'immediate',
#                               'transition': {'duration': 0}}],
#                     'label': '▶',
#                     'method': 'animate'
#                 },
#                 {
#                     'args': [[None], {'frame': {'duration': 0, 'redraw': True}, 'mode': 'immediate',
#                               'transition': {'duration': 0}}],
#                     'label': '◼',
#                     'method': 'animate'
#                 }
#             ],
#             'direction': 'left',
#             'pad': {'r': 10, 't': 87},
#             'showactive': False,
#             'type': 'buttons',
#             'x': 0.1,
#             'xanchor': 'right',
#             'y': 0,
#             'yanchor': 'top'
#         }],
#         sliders=[{
#             'active': middle_slice,
#             'yanchor': 'top',
#             'xanchor': 'left',
#             'currentvalue': {
#                 'font': {'size': 16},
#                 'prefix': 'Slice: ',
#                 'visible': True,
#                 'xanchor': 'right'
#             },
#             'transition': {'duration': 100, 'easing': 'cubic-in-out'},
#             'pad': {'b': 10, 't': 50},
#             'len': 0.9,
#             'x': 0.1,
#             'y': 0,
#             'steps': [{'args': [[f'slice{i}'],
#                                 {'frame': {'duration': 100, 'easing': 'cubic-in-out', 'redraw': True},
#                                  'transition': {'duration': 0}}],
#                        'label': str(i),
#                        'method': 'animate'} for i in range(num_slices)]
#         }]
#     )

#     return fig

# def get_random_fun_fact():
#     fun_facts = [
#         "Regular physical exercise can reduce the risk of developing dementia by up to 50%.",
#         "Eating a Mediterranean diet rich in fruits, vegetables, and omega-3 fatty acids may help prevent dementia.",
#         "Learning a new language or playing a musical instrument can help reduce the risk of developing dementia.",
#         "Socializing and maintaining strong social connections may lower the risk of cognitive decline.",
#         "Some studies suggest that drinking coffee in moderation may help protect against dementia.",
#         "Engaging in mentally stimulating activities like puzzles or reading can help maintain cognitive function.",
#         "Getting enough quality sleep is crucial for brain health and may help prevent dementia.",
#         "Controlling high blood pressure and cholesterol levels can reduce the risk of developing vascular dementia.",
#         "Non-smokers have a lower risk of developing dementia compared to smokers.",
#         "Early detection and treatment of hearing loss may help reduce the risk of cognitive decline."
#     ]
#     return random.choice(fun_facts)

# def prepare_figures(data, seg_data, pixel_spacing, slice_thickness, result):
#     axial_fig = plot_mri_slice(data, seg_data, 'Axial', pixel_spacing, slice_thickness)
#     coronal_fig = plot_mri_slice(data, seg_data, 'Coronal', pixel_spacing, slice_thickness)
#     sagittal_fig = plot_mri_slice(data, seg_data, 'Sagittal', pixel_spacing, slice_thickness)
#     result.extend([axial_fig, coronal_fig, sagittal_fig])

# if uploaded_file:
#     temp_dir = tempfile.mkdtemp()
#     path = os.path.join(temp_dir, uploaded_file.name)
#     with open(path, "wb") as f:
#         f.write(uploaded_file.getvalue())
    
#     img = nib.load(path)
#     data = img.get_fdata()
#     header = img.header

#     pixel_spacing = header['pixdim'][1:3]
#     slice_thickness = header['pixdim'][3]

#     seg_data = np.zeros_like(data)
#     if segments and segmentation_file:
#         seg_path = os.path.join(temp_dir, segmentation_file.name)
#         with open(seg_path, "wb") as f:
#             f.write(segmentation_file.getvalue())
        
#         seg_img = nib.load(seg_path)
#         seg_data = seg_img.get_fdata()

#         # Resample segmentation data to match MRI data dimensions
#         zoom_factors = np.array(data.shape) / np.array(seg_data.shape)
#         seg_data = zoom(seg_data, zoom_factors, order=0)  # Using nearest-neighbor interpolation

#     # Create a placeholder for the loading screen
#     loading_placeholder = st.empty()

#     # Prepare figures in a separate thread
#     result = []
#     thread = threading.Thread(target=prepare_figures, args=(data, seg_data, pixel_spacing, slice_thickness, result))
#     thread.start()

#     # Display loading screen with fun facts
#     start_time = time.time()
#     while thread.is_alive():
#         with loading_placeholder.container():
#             st.markdown("## Loading MRI Visualization")
#             fun_fact = get_random_fun_fact()
#             st.markdown(f"**Fun Fact:** {fun_fact}")
#             progress = min(100, int((time.time() - start_time) / 0.5))  # Assume max 50 seconds loading time
#             st.progress(progress)
#         time.sleep(2)  # Update fun fact every 2 seconds

#     thread.join()  # Ensure the thread has completed

#     # Clear the loading screen
#     loading_placeholder.empty()

#     # Unpack the prepared figures
#     axial_fig, coronal_fig, sagittal_fig = result

#     # Display all figures at once
#     col1, col2 = st.columns([2, 1], gap="small")

#     with col1:
#         axial_chart = st.plotly_chart(axial_fig, use_container_width=True)

#     with col2:
#         coronal_chart = st.plotly_chart(coronal_fig, use_container_width=True)
#         sagittal_chart = st.plotly_chart(sagittal_fig, use_container_width=True)

#     # Add segmentation legend to the sidebar
#     add_segmentation_legend_sidebar()

# # if uploaded_file:
# #     temp_dir = tempfile.mkdtemp()
# #     path = os.path.join(temp_dir, uploaded_file.name)
# #     with open(path, "wb") as f:
# #         f.write(uploaded_file.getvalue())
    
# #     img = nib.load(path)
# #     data = img.get_fdata()
# #     header = img.header

# #     pixel_spacing = header['pixdim'][1:3]
# #     slice_thickness = header['pixdim'][3]

# #     seg_data = np.zeros_like(data)
# #     if segments and segmentation_file:
# #         seg_path = os.path.join(temp_dir, segmentation_file.name)
# #         with open(seg_path, "wb") as f:
# #             f.write(segmentation_file.getvalue())
        
# #         seg_img = nib.load(seg_path)
# #         seg_data = seg_img.get_fdata()

# #         # Resample segmentation data to match MRI data dimensions
# #         zoom_factors = np.array(data.shape) / np.array(seg_data.shape)
# #         seg_data = zoom(seg_data, zoom_factors, order=0)  # Using nearest-neighbor interpolation

# #     # Create a placeholder for the loading screen
# #     loading_placeholder = st.empty()

# #     # Display loading screen
# #     with loading_placeholder.container():
# #         st.markdown("## Loading MRI Visualization")

# #     # Prepare the figures
# #     axial_fig = plot_mri_slice(data, seg_data, 'Axial', pixel_spacing, slice_thickness)
# #     coronal_fig = plot_mri_slice(data, seg_data, 'Coronal', pixel_spacing, slice_thickness)
# #     sagittal_fig = plot_mri_slice(data, seg_data, 'Sagittal', pixel_spacing, slice_thickness)

# #     # Clear the loading screen
# #     loading_placeholder.empty()

# #     # Display all figures at once
# #     col1, col2 = st.columns([2, 1], gap="small")

# #     with col1:
# #         axial_chart = st.plotly_chart(axial_fig, use_container_width=True)

# #     with col2:
# #         coronal_chart = st.plotly_chart(coronal_fig, use_container_width=True)
# #         sagittal_chart = st.plotly_chart(sagittal_fig, use_container_width=True)

# #     # Add segmentation legend to the sidebar
# #     add_segmentation_legend_sidebar()

# import streamlit as st
# import tempfile
# import os
# import nibabel as nib
# import numpy as np
# import plotly.graph_objects as go
# from scipy.ndimage import zoom
# import time

# # Set the page layout to wide
# st.set_page_config(layout="wide")

# # Optional: logo (uncomment if you have the resource)
# st.image("resources/biomedia.png", width=200)

# st.markdown(
#     """
#     <style>
#     /* Change the font size of the sidebar */
#     .sidebar .sidebar-content {
#         font-size: 2px;  
#     }
#     /* Change the line spacing of the sidebar */
#     .sidebar .sidebar-content p {
#         line-height: 0.2;  /* Adjust the line height as needed */
#     }
#     </style>
#     """,
#     unsafe_allow_html=True
# )

# st.title('MRI Scan Visualization :brain:')

# st.write("""
#          The **MRI Visualization** page offers an interactive platform for users to explore 3D MRI scans in detail. It is designed to enhance the understanding of anatomical structures and any associated segmentation data.
# """)

# with st.expander("### **Features:**"):
#     st.write("""
#     - **Upload MRI Scans:**
#         - Users can upload their own 3D MRI scans in NIfTI format (`.nii` or `.nii.gz`).
#         - An optional checkbox allows users to upload a corresponding segmentation mask if available.
    
#     - **Interactive Slice Navigation:**
#         - Provides axial, coronal, and sagittal views of the MRI scan.
#         - Users can scroll through slices in each plane using the interactive slider.

#     - **Segmentation Overlay:**
#         - When a segmentation mask is provided, it overlays onto the MRI images.
#         - Segmented regions are highlighted with transparent colors to maintain visibility of underlying anatomy.
#     """)

# with st.expander("## **Instructions:**"):
#     st.write("""
#     1. **Upload Your MRI Scan:**
#         - Use the file uploader to select your MRI scan file.
#         - Supported formats: NIfTI (`.nii`, `.nii.gz`).

#     2. **Upload Segmentation Mask (Optional):**
#         - If you have a segmentation mask, check the **"Include Segmentation Mask"** checkbox.
#         - Upload your segmentation mask file in NIfTI format.

#     3. **View MRI Slices:**
#         - After uploading, the application will display the MRI scan in three views: axial, coronal, and sagittal.
#         - Use the slider beneath each visualization to navigate through the slices.
#     """)

# uploaded_file = st.file_uploader("Upload MRI file", type=["gz", "nii", "nii.gz"])

# segments = st.checkbox("Show Segmentation")
# segmentation_file = None

# if segments:
#     segmentation_file = st.file_uploader("Upload segmentation file", type=["gz", "nii", "nii.gz"])

# # Define segmentation colors
# segmentation_colors = {
#     0: '#000000',  # Background (black)
#     2: '#759479',  # Left cerebral white matter (purple)
#     3: '#f7d587',  # Left cerebral cortex (orange)
#     4: '#bb7761',  # Left lateral ventricle (brown)
#     5: '#53bad5',  # Left inferior lateral ventricle (cyan)
#     7: '#e95c47',  # Left cerebellum white matter (red)
#     8: '#ec7c5e',  # Left cerebellum cortex (light salmon)
#     10: '#6cf185', # Left thalamus (green)
#     11: '#ce6253', # Left caudate (brown)
#     12: '#d6f600', # Left putamen (yellow)
#     13: '#513e00', # Left pallidum (saddle brown)
#     14: '#fffad9', # 3rd ventricle (white)
#     15: '#e8dc00', # 4th ventricle (yellow)
#     16: '#c8c8ee', # Brain-stem (lavender)
#     17: '#fafacd', # Left hippocampus (lemon chiffon)
#     18: '#fad500', # Left amygdala (yellow)
#     24: '#009ad3', # CSF (cyan)
#     26: '#e95c47', # Left accumbens area (red)
#     28: '#bc9be1', # Left ventral DC (lavender)
#     41: '#afd7d3', # Right cerebral white matter (light cyan)
#     42: '#8ebed1', # Right cerebral cortex (light blue)
#     43: '#53bad5', # Right lateral ventricle (cyan)
#     44: '#a9d5f5', # Right inferior lateral ventricle (cyan)
#     46: '#00af5c', # Right cerebellum white matter (light green)
#     47: '#4ac87c', # Right cerebellum cortex (pale green)
#     49: '#00bfff', # Right thalamus (cyan)
#     50: '#009400', # Right caudate (green)
#     51: '#d2e772', # Right putamen (green yellow)
#     52: '#513e00', # Right pallidum (saddle brown)
#     53: '#d0ffff', # Right hippocampus (light cyan)
#     54: '#90fdfb', # Right amygdala (cyan)
#     58: '#6de3e6', # Right accumbens area (cyan)
#     60: '#cc3400', # Right ventral DC (red)
# }

# # Label names for legend
# label_names = {
#     2: 'Left cerebral white matter',
#     3: 'Left cerebral cortex',
#     4: 'Left lateral ventricle',
#     5: 'Left inferior lateral ventricle',
#     7: 'Left cerebellum white matter',
#     8: 'Left cerebellum cortex',
#     10: 'Left thalamus',
#     11: 'Left caudate',
#     12: 'Left putamen',
#     13: 'Left pallidum',
#     14: '3rd ventricle',
#     15: '4th ventricle',
#     16: 'Brain-stem',
#     17: 'Left hippocampus',
#     18: 'Left amygdala',
#     24: 'CSF',
#     26: 'Left accumbens area',
#     28: 'Left ventral DC',
#     41: 'Right cerebral white matter',
#     42: 'Right cerebral cortex',
#     43: 'Right lateral ventricle',
#     44: 'Right inferior lateral ventricle',
#     46: 'Right cerebellum white matter',
#     47: 'Right cerebellum cortex',
#     49: 'Right thalamus',
#     50: 'Right caudate',
#     51: 'Right putamen',
#     52: 'Right pallidum',
#     53: 'Right hippocampus',
#     54: 'Right amygdala',
#     58: 'Right accumbens area',
#     60: 'Right ventral DC',
# }

# @st.cache_data
# def create_plotly_colorscale(segmentation_colors):
#     """Create a Plotly-compatible colorscale for segmentation"""
#     max_value = max(segmentation_colors.keys())
#     colorscale = []
#     for i in range(max_value + 1):
#         color = segmentation_colors.get(i, '#000000')
#         colorscale.append([i / max_value, color])
#     return colorscale

# def get_label_name(value):
#     """Get the label name for a segmentation value"""
#     return label_names.get(value, f'Unknown ({value})')

# def add_segmentation_legend_sidebar():
#     """Add segmentation legend to sidebar"""
#     st.sidebar.title("Segmentation Labels")
#     for value, color in segmentation_colors.items():
#         if value != 0:  # Skip background
#             st.sidebar.markdown(f"<span style='color:{color};'>⬤</span> {get_label_name(value)}", unsafe_allow_html=True)

# def plot_mri_slice(data, seg_data, view, pixel_spacing, slice_thickness):
#     """
#     Plot MRI slice with segmentation overlay - optimized version
#     """
#     # Create an empty frames list to store all slices
#     frames = []
    
#     # Set appropriate dimensions and orientation based on view
#     if view == 'Axial':
#         data = np.flip(data, axis=0)
#         seg_data = np.flip(seg_data, axis=0) if seg_data is not None else None
#         aspect_ratio = slice_thickness / pixel_spacing[0]
#         height = 800
#         num_slices = data.shape[1]
        
#         # Function to extract slice for this view
#         def extract_slice(i):
#             img = data[:, i, :]
#             seg_img = None if seg_data is None else seg_data[:, i, :]
#             return img, seg_img
            
#     elif view == 'Coronal':
#         aspect_ratio = slice_thickness / pixel_spacing[0]
#         height = 400
#         num_slices = data.shape[0]
        
#         # Function to extract slice for this view
#         def extract_slice(i):
#             img = data[i, :, :]
#             seg_img = None if seg_data is None else seg_data[i, :, :]
#             return img, seg_img
            
#     elif view == 'Sagittal':
#         aspect_ratio = pixel_spacing[1] / pixel_spacing[0]
#         height = 400
#         num_slices = data.shape[2]
        
#         # Function to extract slice for this view
#         def extract_slice(i):
#             img = np.rot90(data[:, :, i])
#             img = np.flip(img, axis=0)
#             seg_img = None
#             if seg_data is not None:
#                 seg_img = np.rot90(seg_data[:, :, i])
#                 seg_img = np.flip(seg_img, axis=0)
#             return img, seg_img
    
#     # Initialize figure
#     fig = go.Figure()
    
#     # Get colorscale for segmentation
#     segmentation_colorscale = create_plotly_colorscale(segmentation_colors)
    
#     # Create frames for each slice - this is the key optimization
#     # We only create a limited number of frames for performance but keep smooth animation
#     # For very large volumes, we sample every nth slice
#     skip_factor = max(1, num_slices // 100)  # Don't create more than ~100 frames
    
#     for i in range(0, num_slices, skip_factor):
#         img, seg_img = extract_slice(i)
        
#         frame_data = [go.Heatmap(z=img, colorscale='gray', showscale=False)]
        
#         if seg_img is not None:
#             # Only create hover text for visible segmentation values (non-zero)
#             hover_text = np.full(seg_img.shape, '', dtype='object')
#             for unique_val in np.unique(seg_img):
#                 if unique_val > 0 and unique_val in label_names:
#                     mask = seg_img == unique_val
#                     hover_text[mask] = get_label_name(unique_val)
            
#             frame_data.append(go.Heatmap(
#                 z=seg_img,
#                 colorscale=segmentation_colorscale,
#                 showscale=False,
#                 opacity=0.5,
#                 hoverinfo='text',
#                 text=hover_text,
#                 hoverongaps=False
#             ))
        
#         frames.append(go.Frame(data=frame_data, name=f'slice{i}'))
    
#     # Add the initial (middle) slice to the figure
#     middle_idx = num_slices // 2
#     middle_img, middle_seg = extract_slice(middle_idx)
    
#     fig.add_trace(go.Heatmap(z=middle_img, colorscale='gray', showscale=False))
    
#     if middle_seg is not None:
#         # Create hover text for middle slice
#         middle_hover = np.full(middle_seg.shape, '', dtype='object')
#         for unique_val in np.unique(middle_seg):
#             if unique_val > 0 and unique_val in label_names:
#                 mask = middle_seg == unique_val
#                 middle_hover[mask] = get_label_name(unique_val)
        
#         fig.add_trace(go.Heatmap(
#             z=middle_seg,
#             colorscale=segmentation_colorscale,
#             showscale=False,
#             opacity=0.5,
#             hoverinfo='text',
#             text=middle_hover,
#             hoverongaps=False
#         ))
    
#     # Add frames to the figure
#     fig.frames = frames
    
#     # Configure layout with slider
#     sliders = [{
#         'active': num_slices // (2 * skip_factor),  # Set to middle slice
#         'currentvalue': {'prefix': 'Slice: ', 'visible': True},
#         'pad': {'t': 50},
#         'len': 0.9,
#         'x': 0.1,
#         'y': 0,
#         'steps': [
#             {
#                 'args': [
#                     [f'slice{i}'],
#                     {'frame': {'duration': 0, 'redraw': True}}
#                 ],
#                 'label': str(i),
#                 'method': 'animate'
#             }
#             for i in range(0, num_slices, skip_factor)
#         ]
#     }]
    
#     fig.update_layout(
#         title=f'{view} View',
#         height=height,
#         xaxis=dict(scaleanchor='y', scaleratio=aspect_ratio),
#         margin=dict(l=0, r=0, t=30, b=0),
#         xaxis_visible=False,
#         yaxis_visible=False,
#         sliders=sliders,
#         updatemenus=[{
#             'buttons': [
#                 {
#                     'args': [None, {'frame': {'duration': 500, 'redraw': True}}],
#                     'label': '▶',
#                     'method': 'animate'
#                 },
#                 {
#                     'args': [[None], {'frame': {'duration': 0, 'redraw': True}}],
#                     'label': '◼',
#                     'method': 'animate'
#                 }
#             ],
#             'type': 'buttons',
#             'direction': 'left',
#             'showactive': False,
#             'x': 0.1,
#             'y': 0,
#             'pad': {'r': 10, 't': 60}
#         }]
#     )
    
#     return fig

# # Main execution
# if uploaded_file:
#     # Create progress indicator
#     progress_bar = st.progress(0)
#     status_text = st.empty()
    
#     # Step 1: Load MRI file
#     status_text.text("Loading MRI file...")
#     temp_dir = tempfile.mkdtemp()
#     mri_path = os.path.join(temp_dir, uploaded_file.name)
#     with open(mri_path, "wb") as f:
#         f.write(uploaded_file.getvalue())
    
#     # Load MRI image
#     progress_bar.progress(25)
#     img = nib.load(mri_path)
#     data = img.get_fdata()
#     header = img.header
    
#     # Get pixel spacing for aspect ratio
#     pixel_spacing = header['pixdim'][1:3]
#     slice_thickness = header['pixdim'][3]
    
#     # Step 2: Load segmentation if provided
#     progress_bar.progress(40)
#     seg_data = None
#     if segments and segmentation_file:
#         status_text.text("Loading segmentation file...")
#         seg_path = os.path.join(temp_dir, segmentation_file.name)
#         with open(seg_path, "wb") as f:
#             f.write(segmentation_file.getvalue())
        
#         # Load segmentation
#         seg_img = nib.load(seg_path)
#         seg_data = seg_img.get_fdata()
        
#         # Resample segmentation if dimensions don't match
#         if seg_data.shape != data.shape:
#             status_text.text("Resampling segmentation to match MRI dimensions...")
#             zoom_factors = np.array(data.shape) / np.array(seg_data.shape)
#             seg_data = zoom(seg_data, zoom_factors, order=0)  # Use nearest-neighbor interpolation
    
#     # Step 3: Create visualizations
#     progress_bar.progress(60)
#     status_text.text("Creating visualizations...")
    
#     # Create columns for layout
#     col1, col2 = st.columns([2, 1], gap="small")
    
#     # Create axial view (top-down)
#     with col1:
#         progress_bar.progress(70)
#         status_text.text("Rendering axial view...")
#         axial_fig = plot_mri_slice(data, seg_data, 'Axial', pixel_spacing, slice_thickness)
#         axial_chart = st.plotly_chart(axial_fig, use_container_width=True)
    
#     with col2:
#         # Create coronal view (front-back)
#         progress_bar.progress(85)
#         status_text.text("Rendering coronal view...")
#         coronal_fig = plot_mri_slice(data, seg_data, 'Coronal', pixel_spacing, slice_thickness)
#         coronal_chart = st.plotly_chart(coronal_fig, use_container_width=True)
        
#     #     # Create sagittal view (side)
#     #     progress_bar.progress(95)
#     #     status_text.text("Rendering sagittal view...")
#     #     sagittal_fig = plot_mri_slice(data, seg_data, 'Sagittal', pixel_spacing, slice_thickness)
#     #     sagittal_chart = st.plotly_chart(sagittal_fig, use_container_width=True)
    
#     # Add segmentation legend to sidebar if using segmentation
#     if segments and segmentation_file and seg_data is not None:
#         add_segmentation_legend_sidebar()
    
#     # Cleanup
#     progress_bar.progress(100)
#     status_text.text("Visualization complete!")
#     time.sleep(1)
#     status_text.empty()
#     progress_bar.empty()
    
#     # Clean up temporary files
#     try:
#         os.remove(mri_path)
#         if segments and segmentation_file:
#             os.remove(seg_path)
#         os.rmdir(temp_dir)
#     except:
#         pass  # Ignore cleanup errors
# else:
#     st.info("Please upload an MRI file to begin visualization.")


import streamlit as st
import tempfile
import os
import nibabel as nib
import numpy as np
import plotly.graph_objects as go
from scipy.ndimage import zoom
import time

# Set the page layout to wide
st.set_page_config(layout="wide")

st.logo("resources/biomedia.png")

st.markdown(
    """
    <style>
    /* Change the font size of the sidebar */
    .sidebar .sidebar-content {
        font-size: 2px;  
    }
    /* Change the line spacing of the sidebar */
    .sidebar .sidebar-content p {
        line-height: 0.2;  /* Adjust the line height as needed */
    }
    </style>
    """,
    unsafe_allow_html=True
)

st.title('MRI Scan Visualization :brain:')

st.write("""
         The **MRI Visualization** page offers an interactive platform for users to explore 3D MRI scans in detail. It is designed to enhance the understanding of anatomical structures and any associated segmentation data.
""")

with st.expander("### **Features:**"):
    st.write("""
    - **Upload MRI Scans:**
        - Users can upload their own 3D MRI scans in NIfTI format (`.nii` or `.nii.gz`).
        - An optional checkbox allows users to upload a corresponding segmentation mask if available.
    
    - **Interactive Slice Navigation:**
        - Provides axial, coronal, and sagittal views of the MRI scan.
        - Users can scroll through slices in each plane using the interactive slider.

    - **Segmentation Overlay:**
        - When a segmentation mask is provided, it overlays onto the MRI images.
        - Segmented regions are highlighted with transparent colors to maintain visibility of underlying anatomy.
    """)

with st.expander("## **Instructions:**"):
    st.write("""
    1. **Upload Your MRI Scan:**
        - Use the file uploader to select your MRI scan file.
        - Supported formats: NIfTI (`.nii`, `.nii.gz`).

    2. **Upload Segmentation Mask (Optional):**
        - If you have a segmentation mask, check the **"Include Segmentation Mask"** checkbox.
        - Upload your segmentation mask file in NIfTI format.

    3. **View MRI Slices:**
        - After uploading, the application will display the MRI scan in three views: axial, coronal, and sagittal.
        - Use the slider beneath each visualization to navigate through the slices.
        - Note: For performance reasons, only the middle slice and 10 slices before and after are rendered.
    """)

uploaded_file = st.file_uploader("Upload MRI file", type=["gz", "nii", "nii.gz"])

segments = st.checkbox("Show Segmentation")
segmentation_file = None

if segments:
    segmentation_file = st.file_uploader("Upload segmentation file", type=["gz", "nii", "nii.gz"])

# Define segmentation colors
segmentation_colors = {
    0: '#000000',  # Background (black)
    2: '#759479',  # Left cerebral white matter (purple)
    3: '#f7d587',  # Left cerebral cortex (orange)
    4: '#bb7761',  # Left lateral ventricle (brown)
    5: '#53bad5',  # Left inferior lateral ventricle (cyan)
    7: '#e95c47',  # Left cerebellum white matter (red)
    8: '#ec7c5e',  # Left cerebellum cortex (light salmon)
    10: '#6cf185', # Left thalamus (green)
    11: '#ce6253', # Left caudate (brown)
    12: '#d6f600', # Left putamen (yellow)
    13: '#513e00', # Left pallidum (saddle brown)
    14: '#fffad9', # 3rd ventricle (white)
    15: '#e8dc00', # 4th ventricle (yellow)
    16: '#c8c8ee', # Brain-stem (lavender)
    17: '#fafacd', # Left hippocampus (lemon chiffon)
    18: '#fad500', # Left amygdala (yellow)
    24: '#009ad3', # CSF (cyan)
    26: '#e95c47', # Left accumbens area (red)
    28: '#bc9be1', # Left ventral DC (lavender)
    41: '#afd7d3', # Right cerebral white matter (light cyan)
    42: '#8ebed1', # Right cerebral cortex (light blue)
    43: '#53bad5', # Right lateral ventricle (cyan)
    44: '#a9d5f5', # Right inferior lateral ventricle (cyan)
    46: '#00af5c', # Right cerebellum white matter (light green)
    47: '#4ac87c', # Right cerebellum cortex (pale green)
    49: '#00bfff', # Right thalamus (cyan)
    50: '#009400', # Right caudate (green)
    51: '#d2e772', # Right putamen (green yellow)
    52: '#513e00', # Right pallidum (saddle brown)
    53: '#d0ffff', # Right hippocampus (light cyan)
    54: '#90fdfb', # Right amygdala (cyan)
    58: '#6de3e6', # Right accumbens area (cyan)
    60: '#cc3400', # Right ventral DC (red)
}

# Label names for legend
label_names = {
    2: 'Left cerebral white matter',
    3: 'Left cerebral cortex',
    4: 'Left lateral ventricle',
    5: 'Left inferior lateral ventricle',
    7: 'Left cerebellum white matter',
    8: 'Left cerebellum cortex',
    10: 'Left thalamus',
    11: 'Left caudate',
    12: 'Left putamen',
    13: 'Left pallidum',
    14: '3rd ventricle',
    15: '4th ventricle',
    16: 'Brain-stem',
    17: 'Left hippocampus',
    18: 'Left amygdala',
    24: 'CSF',
    26: 'Left accumbens area',
    28: 'Left ventral DC',
    41: 'Right cerebral white matter',
    42: 'Right cerebral cortex',
    43: 'Right lateral ventricle',
    44: 'Right inferior lateral ventricle',
    46: 'Right cerebellum white matter',
    47: 'Right cerebellum cortex',
    49: 'Right thalamus',
    50: 'Right caudate',
    51: 'Right putamen',
    52: 'Right pallidum',
    53: 'Right hippocampus',
    54: 'Right amygdala',
    58: 'Right accumbens area',
    60: 'Right ventral DC',
}

@st.cache_data
def create_plotly_colorscale(segmentation_colors):
    """Create a Plotly-compatible colorscale for segmentation"""
    max_value = max(segmentation_colors.keys())
    colorscale = []
    for i in range(max_value + 1):
        color = segmentation_colors.get(i, '#000000')
        colorscale.append([i / max_value, color])
    return colorscale

def get_label_name(value):
    """Get the label name for a segmentation value"""
    return label_names.get(value, f'Unknown ({value})')

def add_segmentation_legend_sidebar():
    """Add segmentation legend to sidebar"""
    st.sidebar.title("Segmentation Labels")
    for value, color in segmentation_colors.items():
        if value != 0:  # Skip background
            st.sidebar.markdown(f"<span style='color:{color};'>⬤</span> {get_label_name(value)}", unsafe_allow_html=True)

def plot_mri_slice(data, seg_data, view, pixel_spacing, slice_thickness):
    """
    Plot MRI slice with segmentation overlay - optimized to only render middle slice and 10 slices before and after
    """
    # Set appropriate dimensions and orientation based on view
    if view == 'Axial':
        data = np.flip(data, axis=0)
        seg_data = np.flip(seg_data, axis=0) if seg_data is not None else None
        aspect_ratio = slice_thickness / pixel_spacing[0]
        height = 800
        num_slices = data.shape[1]
        
        # Function to extract slice for this view
        def extract_slice(i):
            img = data[:, i, :]
            seg_img = None if seg_data is None else seg_data[:, i, :]
            return img, seg_img
            
    elif view == 'Coronal':
        aspect_ratio = slice_thickness / pixel_spacing[0]
        height = 400
        num_slices = data.shape[0]
        
        # Function to extract slice for this view
        def extract_slice(i):
            img = data[i, :, :]
            seg_img = None if seg_data is None else seg_data[i, :, :]
            return img, seg_img
            
    elif view == 'Sagittal':
        aspect_ratio = pixel_spacing[1] / pixel_spacing[0]
        height = 400
        num_slices = data.shape[2]
        
        # Function to extract slice for this view
        def extract_slice(i):
            img = np.rot90(data[:, :, i])
            img = np.flip(img, axis=0)
            seg_img = None
            if seg_data is not None:
                seg_img = np.rot90(seg_data[:, :, i])
                seg_img = np.flip(seg_img, axis=0)
            return img, seg_img
    
    # Initialize figure
    fig = go.Figure()
    
    # Get colorscale for segmentation
    segmentation_colorscale = create_plotly_colorscale(segmentation_colors)
    
    # Calculate middle slice and range
    middle_idx = num_slices // 2
    slice_range = 10  # Number of slices before and after middle to render
    start_idx = max(0, middle_idx - slice_range)
    end_idx = min(num_slices, middle_idx + slice_range + 1)
    
    # Create frames only for the middle slice and neighboring slices
    frames = []
    slice_labels = []
    
    for i in range(start_idx, end_idx):
        img, seg_img = extract_slice(i)
        
        frame_data = [go.Heatmap(z=img, colorscale='gray', showscale=False)]
        
        if seg_img is not None:
            # Only create hover text for visible segmentation values (non-zero)
            hover_text = np.full(seg_img.shape, '', dtype='object')
            for unique_val in np.unique(seg_img):
                if unique_val > 0 and unique_val in label_names:
                    mask = seg_img == unique_val
                    hover_text[mask] = get_label_name(unique_val)
            
            frame_data.append(go.Heatmap(
                z=seg_img,
                colorscale=segmentation_colorscale,
                showscale=False,
                opacity=0.5,
                hoverinfo='text',
                text=hover_text,
                hoverongaps=False
            ))
        
        frames.append(go.Frame(data=frame_data, name=f'slice{i}'))
        slice_labels.append(str(i))
    
    # Add the initial (middle) slice to the figure
    middle_img, middle_seg = extract_slice(middle_idx)
    
    fig.add_trace(go.Heatmap(z=middle_img, colorscale='gray', showscale=False))
    
    if middle_seg is not None:
        # Create hover text for middle slice
        middle_hover = np.full(middle_seg.shape, '', dtype='object')
        for unique_val in np.unique(middle_seg):
            if unique_val > 0 and unique_val in label_names:
                mask = middle_seg == unique_val
                middle_hover[mask] = get_label_name(unique_val)
        
        fig.add_trace(go.Heatmap(
            z=middle_seg,
            colorscale=segmentation_colorscale,
            showscale=False,
            opacity=0.5,
            hoverinfo='text',
            text=middle_hover,
            hoverongaps=False
        ))
    
    # Add frames to the figure
    fig.frames = frames
    
    # Configure layout with slider
    slider_steps = [
        {
            'args': [
                [f'slice{i}'],
                {'frame': {'duration': 0, 'redraw': True}}
            ],
            'label': str(i),
            'method': 'animate'
        }
        for i in range(start_idx, end_idx)
    ]
    
    # Calculate middle position for slider
    slider_midpoint = (middle_idx - start_idx) / (end_idx - start_idx - 1) if end_idx > start_idx + 1 else 0.5
    
    sliders = [{
        'active': middle_idx - start_idx,  # Set to middle slice
        'currentvalue': {'prefix': 'Slice: ', 'visible': True},
        'pad': {'t': 50},
        'len': 0.9,
        'x': 0.1,
        'y': 0,
        'steps': slider_steps
    }]
    
    fig.update_layout(
        title=f'{view} View',
        height=height,
        xaxis=dict(scaleanchor='y', scaleratio=aspect_ratio),
        margin=dict(l=0, r=0, t=30, b=0),
        xaxis_visible=False,
        yaxis_visible=False,
        sliders=sliders,
        updatemenus=[{
            'buttons': [
                {
                    'args': [None, {'frame': {'duration': 200, 'redraw': True}}],
                    'label': '▶',
                    'method': 'animate'
                },
                {
                    'args': [[None], {'frame': {'duration': 0, 'redraw': True}}],
                    'label': '◼',
                    'method': 'animate'
                }
            ],
            'type': 'buttons',
            'direction': 'left',
            'showactive': False,
            'x': 0.1,
            'y': 0,
            'pad': {'r': 10, 't': 60}
        }]
    )
    
    return fig

# Main execution
if uploaded_file:
    # Create progress indicator
    progress_bar = st.progress(0)
    status_text = st.empty()
    
    # Step 1: Load MRI file
    status_text.text("Loading MRI file...")
    temp_dir = tempfile.mkdtemp()
    mri_path = os.path.join(temp_dir, uploaded_file.name)
    with open(mri_path, "wb") as f:
        f.write(uploaded_file.getvalue())
    
    # Load MRI image
    progress_bar.progress(25)
    img = nib.load(mri_path)
    data = img.get_fdata()
    header = img.header
    
    # Get pixel spacing for aspect ratio
    pixel_spacing = header['pixdim'][1:3]
    slice_thickness = header['pixdim'][3]
    
    # Step 2: Load segmentation if provided
    progress_bar.progress(40)
    seg_data = None
    if segments and segmentation_file:
        status_text.text("Loading segmentation file...")
        seg_path = os.path.join(temp_dir, segmentation_file.name)
        with open(seg_path, "wb") as f:
            f.write(segmentation_file.getvalue())
        
        # Load segmentation
        seg_img = nib.load(seg_path)
        seg_data = seg_img.get_fdata()
        
        # Resample segmentation if dimensions don't match
        if seg_data.shape != data.shape:
            status_text.text("Resampling segmentation to match MRI dimensions...")
            zoom_factors = np.array(data.shape) / np.array(seg_data.shape)
            seg_data = zoom(seg_data, zoom_factors, order=0)  # Use nearest-neighbor interpolation
    
    # Step 3: Create visualizations
    progress_bar.progress(60)
    status_text.text("Creating visualizations...")
    
    # Create columns for layout
    col1, col2 = st.columns([2, 1], gap="small")
    
    # Create axial view (top-down)
    with col1:
        progress_bar.progress(70)
        status_text.text("Rendering axial view...")
        axial_fig = plot_mri_slice(data, seg_data, 'Axial', pixel_spacing, slice_thickness)
        axial_chart = st.plotly_chart(axial_fig, use_container_width=True)
    
    with col2:
        # Create coronal view (front-back)
        progress_bar.progress(85)
        status_text.text("Rendering coronal view...")
        coronal_fig = plot_mri_slice(data, seg_data, 'Coronal', pixel_spacing, slice_thickness)
        coronal_chart = st.plotly_chart(coronal_fig, use_container_width=True)
        
        # Create sagittal view (side)
        progress_bar.progress(95)
        status_text.text("Rendering sagittal view...")
        sagittal_fig = plot_mri_slice(data, seg_data, 'Sagittal', pixel_spacing, slice_thickness)
        sagittal_chart = st.plotly_chart(sagittal_fig, use_container_width=True)
    
    # Add segmentation legend to sidebar if using segmentation
    if segments and segmentation_file and seg_data is not None:
        add_segmentation_legend_sidebar()
    
    # Cleanup
    progress_bar.progress(100)
    status_text.text("Visualization complete!")
    time.sleep(1)
    status_text.empty()
    progress_bar.empty()
    
    # Clean up temporary files
    try:
        os.remove(mri_path)
        if segments and segmentation_file:
            os.remove(seg_path)
        os.rmdir(temp_dir)
    except:
        pass  # Ignore cleanup errors
else:
    st.info("Please upload an MRI file to begin visualization.")