File size: 56,544 Bytes
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d473f9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c194eb0
 
e54393e
bfeb49a
 
c194eb0
e54393e
bfeb49a
 
c194eb0
e54393e
bfeb49a
 
c194eb0
e54393e
bfeb49a
 
c194eb0
 
 
e16ab65
 
c194eb0
 
e16ab65
 
c194eb0
 
e16ab65
 
c194eb0
 
e16ab65
 
c194eb0
 
 
4cb6ee4
c194eb0
 
 
 
 
 
4cb6ee4
 
 
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42fc619
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcc0c48
c194eb0
 
 
 
 
 
 
d473f9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c194eb0
d473f9b
 
 
c194eb0
 
e54393e
bfeb49a
 
c194eb0
e54393e
bfeb49a
 
c194eb0
e54393e
bfeb49a
 
c194eb0
e54393e
bfeb49a
 
c194eb0
 
 
e16ab65
 
c194eb0
 
e16ab65
 
c194eb0
 
e16ab65
 
c194eb0
 
e16ab65
 
c194eb0
 
 
 
48dc477
 
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42fc619
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dcc0c48
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbff237
d473f9b
c194eb0
 
c774bfb
d473f9b
c194eb0
 
 
 
 
4cb6ee4
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
4cb6ee4
 
 
 
 
 
 
c194eb0
 
 
 
4cb6ee4
 
 
 
 
 
c194eb0
 
 
 
4cb6ee4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c774bfb
 
 
 
 
 
 
4cb6ee4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c194eb0
 
 
 
4cb6ee4
 
 
 
 
 
c194eb0
 
 
 
c774bfb
 
 
 
 
 
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cb6ee4
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2485f4
c194eb0
c2485f4
c194eb0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
HF_TOKEN = os.getenv("HF_TOKEN")

import numpy as np
import pandas as pd
import sklearn
import sklearn.metrics
from math import sqrt
from scipy import stats as st
from matplotlib import pyplot as plt

from sklearn.linear_model import LogisticRegression

import shap
import gradio as gr
import random
import re
import textwrap
from datasets import load_dataset


#Read data training data.

g2_x1 = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g2_12m_data_train.csv", use_auth_token = HF_TOKEN)
g2_x1 = pd.DataFrame(g2_x1['train'])
g2_x1 = g2_x1.iloc[:, 1:]

g2_x2 = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g2_24m_data_train.csv", use_auth_token = HF_TOKEN)
g2_x2 = pd.DataFrame(g2_x2['train'])
g2_x2 = g2_x2.iloc[:, 1:]

g2_x3 = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g2_36m_data_train.csv", use_auth_token = HF_TOKEN)
g2_x3 = pd.DataFrame(g2_x3['train'])
g2_x3 = g2_x3.iloc[:, 1:]

g2_x4 = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g2_60m_data_train.csv", use_auth_token = HF_TOKEN)
g2_x4 = pd.DataFrame(g2_x4['train'])
g2_x4 = g2_x4.iloc[:, 1:]

#Read validation data.

g2_x1_valid = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g2_12m_data_valid.csv", use_auth_token = HF_TOKEN)
g2_x1_valid = pd.DataFrame(g2_x1_valid['train'])
g2_x1_valid = g2_x1_valid.iloc[:, 1:]

g2_x2_valid = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g2_24m_data_valid.csv", use_auth_token = HF_TOKEN)
g2_x2_valid = pd.DataFrame(g2_x2_valid['train'])
g2_x2_valid = g2_x2_valid.iloc[:, 1:]

g2_x3_valid = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g2_36m_data_valid.csv", use_auth_token = HF_TOKEN)
g2_x3_valid = pd.DataFrame(g2_x3_valid['train'])
g2_x3_valid = g2_x3_valid.iloc[:, 1:]

g2_x4_valid = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g2_60m_data_valid.csv", use_auth_token = HF_TOKEN)
g2_x4_valid = pd.DataFrame(g2_x4_valid['train'])
g2_x4_valid = g2_x4_valid.iloc[:, 1:]


#Define feature names (g2).
g2_f1_names = list(g2_x1.columns)
g2_f1_names = [f1.replace('__', ' - ') for f1 in g2_f1_names]
g2_f1_names = [f1.replace('_', ' ') for f1 in g2_f1_names]

g2_f2_names = list(g2_x2.columns)
g2_f2_names = [f2.replace('__', ' - ') for f2 in g2_f2_names]
g2_f2_names = [f2.replace('_', ' ') for f2 in g2_f2_names]

g2_f3_names = list(g2_x3.columns)
g2_f3_names = [f3.replace('__', ' - ') for f3 in g2_f3_names]
g2_f3_names = [f3.replace('_', ' ') for f3 in g2_f3_names]

g2_f4_names = list(g2_x4.columns)
g2_f4_names = [f4.replace('__', ' - ') for f4 in g2_f4_names]
g2_f4_names = [f4.replace('_', ' ') for f4 in g2_f4_names]


#Prepare data for the outcome 1 (g2).
g2_y1 = g2_x1.pop('OUTCOME')
g2_y1_valid = g2_x1_valid.pop('OUTCOME')

#Prepare data for the outcome 2 (g2).
g2_y2 = g2_x2.pop('OUTCOME')
g2_y2_valid = g2_x2_valid.pop('OUTCOME')

#Prepare data for the outcome 3 (g2).
g2_y3 = g2_x3.pop('OUTCOME')
g2_y3_valid = g2_x3_valid.pop('OUTCOME')

#Prepare data for the outcome 4 (g2).
g2_y4 = g2_x4.pop('OUTCOME')
g2_y4_valid = g2_x4_valid.pop('OUTCOME')


#Assign hyperparameters (g2).
g2_y1_params =  {'criterion': 'gini', 'max_features': 'log2', 'max_depth': 4, 'n_estimators': 900, 'min_samples_leaf': 3, 'min_samples_split': 3, 'random_state': 31}
g2_y2_params =  {'objective': 'binary', 'boosting_type': 'gbdt', 'lambda_l1': 6.121600211393574e-07, 'lambda_l2': 0.0028998418721597743, 'num_leaves': 2, 'feature_fraction': 0.6798107660641116, 'bagging_fraction': 0.42950125330169564, 'bagging_freq': 7, 'min_child_samples': 87, 'metric': 'binary_logloss', 'verbosity': -1, 'random_state': 31}
g2_y3_params =  {'objective': 'binary', 'boosting_type': 'gbdt', 'lambda_l1': 6.806711570427862e-07, 'lambda_l2': 0.003064768550805565, 'num_leaves': 2, 'feature_fraction': 0.6780931825384188, 'bagging_fraction': 0.5046150209604292, 'bagging_freq': 3, 'min_child_samples': 69, 'metric': 'binary_logloss', 'verbosity': -1, 'random_state': 31}
g2_y4_params =  {'criterion': 'gini', 'max_features': 'log2', 'max_depth': 5, 'n_estimators': 800, 'min_samples_leaf': 3, 'min_samples_split': 2, 'random_state': 31}

#Training models (g2).

from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(**g2_y1_params)
g2_y1_model = rf
g2_y1_model = g2_y1_model.fit(g2_x1, g2_y1)
g2_y1_explainer = shap.Explainer(g2_y1_model.predict, g2_x1)
g2_y1_calib_probs = g2_y1_model.predict_proba(g2_x1_valid)
g2_y1_calib_model = LogisticRegression()
g2_y1_calib_model = g2_y1_calib_model.fit(g2_y1_calib_probs, g2_y1_valid)

from lightgbm import LGBMClassifier
lgb = LGBMClassifier(**g2_y2_params)
g2_y2_model = lgb
g2_y2_model = g2_y2_model.fit(g2_x2, g2_y2)
g2_y2_explainer = shap.Explainer(g2_y2_model.predict, g2_x2)
g2_y2_calib_probs = g2_y2_model.predict_proba(g2_x2_valid)
g2_y2_calib_model = LogisticRegression()
g2_y2_calib_model = g2_y2_calib_model.fit(g2_y2_calib_probs, g2_y2_valid)

from lightgbm import LGBMClassifier
lgb = LGBMClassifier(**g2_y3_params)
g2_y3_model = lgb
g2_y3_model = g2_y3_model.fit(g2_x3, g2_y3)
g2_y3_explainer = shap.Explainer(g2_y3_model.predict, g2_x3)
g2_y3_calib_probs = g2_y3_model.predict_proba(g2_x3_valid)
g2_y3_calib_model = LogisticRegression()
g2_y3_calib_model = g2_y3_calib_model.fit(g2_y3_calib_probs, g2_y3_valid)

from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(**g2_y4_params)
g2_y4_model = rf
g2_y4_model = g2_y4_model.fit(g2_x4, g2_y4)
g2_y4_explainer = shap.Explainer(g2_y4_model.predict, g2_x4)
g2_y4_calib_probs = g2_y4_model.predict_proba(g2_x4_valid)
g2_y4_calib_model = LogisticRegression()
g2_y4_calib_model = g2_y4_calib_model.fit(g2_y4_calib_probs, g2_y4_valid)

#Define output functions (g2).

g2_output_y1 = (
    """          
        <br/>
        <center>The probability of 12-month survival:</center>
        <br/>
        <center><h1>{:.2f}%</h1></center>
"""
)

g2_output_y2 = (
    """          
        <br/>        
        <center>The probability of 24-month survival:</center>
        <br/>        
        <center><h1>{:.2f}%</h1></center>
"""
)

g2_output_y3 = (
    """          
        <br/>        
        <center>The probability of 36-month survival:</center>
        <br/>        
        <center><h1>{:.2f}%</h1></center>
"""
)

g2_output_y4 = (
    """          
        <br/>        
        <center>The probability of 60-month survival:</center>
        <br/>        
        <center><h1>{:.2f}%</h1></center>
"""
)

#Define predict for y1 (g2).
def g2_y1_predict(*args):
    g2_df1 = pd.DataFrame([args], columns=g2_x1.columns)
    pos_pred = g2_y1_model.predict_proba(g2_df1)
    pos_pred = g2_y1_calib_model.predict_proba(pos_pred)
    prob = pos_pred[0][1]
    prob = 1-prob
    output = g2_output_y1.format(prob * 100)
    return output

#Define predict for y2 (g2).
def g2_y2_predict(*args):
    g2_df2 = pd.DataFrame([args], columns=g2_x2.columns)
    pos_pred = g2_y2_model.predict_proba(g2_df2)
    pos_pred = g2_y2_calib_model.predict_proba(pos_pred)        
    prob = pos_pred[0][1]
    prob = 1-prob
    output = g2_output_y2.format(prob * 100)
    return output

#Define predict for y3 (g2).
def g2_y3_predict(*args):
    g2_df3 = pd.DataFrame([args], columns=g2_x3.columns)
    pos_pred = g2_y3_model.predict_proba(g2_df3)
    pos_pred = g2_y3_calib_model.predict_proba(pos_pred)            
    prob = pos_pred[0][1]
    prob = 1-prob    
    output = g2_output_y3.format(prob * 100)
    return output

#Define predict for y4 (g2).
def g2_y4_predict(*args):
    g2_df4 = pd.DataFrame([args], columns=g2_x4.columns)
    pos_pred = g2_y4_model.predict_proba(g2_df4)
    pos_pred = g2_y4_calib_model.predict_proba(pos_pred)            
    prob = pos_pred[0][1]
    prob = 1-prob
    output = g2_output_y4.format(prob * 100)
    return output

#Read data training data.

g3_x1 = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g3_12m_data_train.csv", use_auth_token = HF_TOKEN)
g3_x1 = pd.DataFrame(g3_x1['train'])
g3_x1 = g3_x1.iloc[:, 1:]

g3_x2 = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g3_24m_data_train.csv", use_auth_token = HF_TOKEN)
g3_x2 = pd.DataFrame(g3_x2['train'])
g3_x2 = g3_x2.iloc[:, 1:]

g3_x3 = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g3_36m_data_train.csv", use_auth_token = HF_TOKEN)
g3_x3 = pd.DataFrame(g3_x3['train'])
g3_x3 = g3_x3.iloc[:, 1:]

g3_x4 = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g3_60m_data_train.csv", use_auth_token = HF_TOKEN)
g3_x4 = pd.DataFrame(g3_x4['train'])
g3_x4 = g3_x4.iloc[:, 1:]

#Read validation data.

g3_x1_valid = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g3_12m_data_valid.csv", use_auth_token = HF_TOKEN)
g3_x1_valid = pd.DataFrame(g3_x1_valid['train'])
g3_x1_valid = g3_x1_valid.iloc[:, 1:]

g3_x2_valid = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g3_24m_data_valid.csv", use_auth_token = HF_TOKEN)
g3_x2_valid = pd.DataFrame(g3_x2_valid['train'])
g3_x2_valid = g3_x2_valid.iloc[:, 1:]

g3_x3_valid = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g3_36m_data_valid.csv", use_auth_token = HF_TOKEN)
g3_x3_valid = pd.DataFrame(g3_x3_valid['train'])
g3_x3_valid = g3_x3_valid.iloc[:, 1:]

g3_x4_valid = load_dataset("mertkarabacak/G2G3-Glioma", data_files="g3_60m_data_valid.csv", use_auth_token = HF_TOKEN)
g3_x4_valid = pd.DataFrame(g3_x4_valid['train'])
g3_x4_valid = g3_x4_valid.iloc[:, 1:]

#Define feature names (g3).
g3_f1_names = list(g3_x1.columns)
g3_f1_names = [f1.replace('__', ' - ') for f1 in g3_f1_names]
g3_f1_names = [f1.replace('_', ' ') for f1 in g3_f1_names]

g3_f2_names = list(g3_x2.columns)
g3_f2_names = [f2.replace('__', ' - ') for f2 in g3_f2_names]
g3_f2_names = [f2.replace('_', ' ') for f2 in g3_f2_names]

g3_f3_names = list(g3_x3.columns)
g3_f3_names = [f3.replace('__', ' - ') for f3 in g3_f3_names]
g3_f3_names = [f3.replace('_', ' ') for f3 in g3_f3_names]

g3_f4_names = list(g3_x4.columns)
g3_f4_names = [f4.replace('__', ' - ') for f4 in g3_f4_names]
g3_f4_names = [f4.replace('_', ' ') for f4 in g3_f4_names]


#Prepare data for the outcome 1 (g3).
g3_y1 = g3_x1.pop('OUTCOME')
g3_y1_valid = g3_x1_valid.pop('OUTCOME')

#Prepare data for the outcome 2 (g3).
g3_y2 = g3_x2.pop('OUTCOME')
g3_y2_valid = g3_x2_valid.pop('OUTCOME')

#Prepare data for the outcome 3 (g3).
g3_y3 = g3_x3.pop('OUTCOME')
g3_y3_valid = g3_x3_valid.pop('OUTCOME')

#Prepare data for the outcome 4 (g3).
g3_y4 = g3_x4.pop('OUTCOME')
g3_y4_valid = g3_x4_valid.pop('OUTCOME')


#Assign hyperparameters (g3).
g3_y1_params =  {'objective': 'binary', 'boosting_type': 'gbdt', 'lambda_l1': 0.0002964237261979634, 'lambda_l2': 0.0003914277818587476, 'num_leaves': 13, 'feature_fraction': 0.4598669689672836, 'bagging_fraction': 0.5293813102688141, 'bagging_freq': 3, 'min_child_samples': 93, 'metric': 'binary_logloss', 'verbosity': -1, 'random_state': 31}
g3_y2_params =  {'criterion': 'entropy', 'max_depth': 53, 'n_estimators': 800, 'min_samples_leaf': 4, 'min_samples_split': 8, 'random_state': 31}
g3_y3_params =  {'criterion': 'entropy', 'max_depth': 44, 'n_estimators': 1000, 'min_samples_leaf': 2, 'min_samples_split': 7, 'random_state': 31}
g3_y4_params =  {'objective': 'binary', 'boosting_type': 'gbdt', 'lambda_l1': 1.9669754108753293e-06, 'lambda_l2': 0.0012741287968581684, 'num_leaves': 17, 'feature_fraction': 0.40138611969162713, 'bagging_fraction': 0.49839300388462815, 'bagging_freq': 4, 'min_child_samples': 91, 'metric': 'binary_logloss', 'verbosity': -1, 'random_state': 31}

#Training models (g3).

from lightgbm import LGBMClassifier
lgb = LGBMClassifier(**g3_y1_params)
g3_y1_model = lgb
g3_y1_model = g3_y1_model.fit(g3_x1, g3_y1)
g3_y1_explainer = shap.Explainer(g3_y1_model.predict, g3_x1)
g3_y1_calib_probs = g3_y1_model.predict_proba(g3_x1_valid)
g3_y1_calib_model = LogisticRegression()
g3_y1_calib_model = g3_y1_calib_model.fit(g3_y1_calib_probs, g3_y1_valid)

from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(**g3_y2_params)
g3_y2_model = rf
g3_y2_model = g3_y2_model.fit(g3_x2, g3_y2)
g3_y2_explainer = shap.Explainer(g3_y2_model.predict, g3_x2)
g3_y2_calib_probs = g3_y2_model.predict_proba(g3_x2_valid)
g3_y2_calib_model = LogisticRegression()
g3_y2_calib_model = g3_y2_calib_model.fit(g3_y2_calib_probs, g3_y2_valid)

from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(**g3_y3_params)
g3_y3_model = rf
g3_y3_model = g3_y3_model.fit(g3_x3, g3_y3)
g3_y3_explainer = shap.Explainer(g3_y3_model.predict, g3_x3)
g3_y3_calib_probs = g3_y3_model.predict_proba(g3_x3_valid)
g3_y3_calib_model = LogisticRegression()
g3_y3_calib_model = g3_y3_calib_model.fit(g3_y3_calib_probs, g3_y3_valid)

from lightgbm import LGBMClassifier
lgb = LGBMClassifier(**g3_y4_params)
g3_y4_model = lgb
g3_y4_model = g3_y4_model.fit(g3_x4, g3_y4)
g3_y4_explainer = shap.Explainer(g3_y4_model.predict, g3_x4)
g3_y4_calib_probs = g3_y4_model.predict_proba(g3_x4_valid)
g3_y4_calib_model = LogisticRegression()
g3_y4_calib_model = g3_y4_calib_model.fit(g3_y4_calib_probs, g3_y4_valid)

#Define output functions (g3).

g3_output_y1 = (
    """          
        <br/>
        <center>The probability of 12-month survival:</center>
        <br/>
        <center><h1>{:.2f}%</h1></center>
"""
)

g3_output_y2 = (
    """          
        <br/>        
        <center>The probability of 24-month survival:</center>
        <br/>        
        <center><h1>{:.2f}%</h1></center>
"""
)

g3_output_y3 = (
    """          
        <br/>        
        <center>The probability of 36-month survival:</center>
        <br/>        
        <center><h1>{:.2f}%</h1></center>
"""
)

g3_output_y4 = (
    """          
        <br/>        
        <center>The probability of 60-month survival:</center>
        <br/>        
        <center><h1>{:.2f}%</h1></center>
"""
)

#Define predict for y1 (g3).
def g3_y1_predict(*args):
    g3_df1 = pd.DataFrame([args], columns=g3_x1.columns)
    pos_pred = g3_y1_model.predict_proba(g3_df1)
    pos_pred = g3_y1_calib_model.predict_proba(pos_pred)
    prob = pos_pred[0][1]
    prob = 1-prob
    output = g3_output_y1.format(prob * 100)
    return output

#Define predict for y2 (g3).
def g3_y2_predict(*args):
    g3_df2 = pd.DataFrame([args], columns=g3_x2.columns)
    pos_pred = g3_y2_model.predict_proba(g3_df2)
    pos_pred = g3_y2_calib_model.predict_proba(pos_pred)        
    prob = pos_pred[0][1]
    prob = 1-prob
    output = g3_output_y2.format(prob * 100)
    return output

#Define predict for y3 (g3).
def g3_y3_predict(*args):
    g3_df3 = pd.DataFrame([args], columns=g3_x3.columns)
    pos_pred = g3_y3_model.predict_proba(g3_df3)
    pos_pred = g3_y3_calib_model.predict_proba(pos_pred)            
    prob = pos_pred[0][1]
    prob = 1-prob    
    output = g3_output_y3.format(prob * 100)
    return output

#Define predict for y4 (g3).
def g3_y4_predict(*args):
    g3_df4 = pd.DataFrame([args], columns=g3_x4.columns)
    pos_pred = g3_y4_model.predict_proba(g3_df4)
    pos_pred = g3_y4_calib_model.predict_proba(pos_pred)            
    prob = pos_pred[0][1]
    prob = 1-prob
    output = g3_output_y4.format(prob * 100)
    return output

#Define function for wrapping feature labels.
def wrap_labels(ax, width, break_long_words=False):
    labels = []
    for label in ax.get_yticklabels():
        text = label.get_text()
        labels.append(textwrap.fill(text, width=width, break_long_words=break_long_words))
    ax.set_yticklabels(labels, rotation=0)
    

#Define interpret for y1 (g2).
def g2_y1_interpret(*args):
    g2_df1 = pd.DataFrame([args], columns=g2_x1.columns)
    g2_shap_values1 = g2_y1_explainer(g2_df1).values
    g2_shap_values1 = np.abs(g2_shap_values1)
    shap.bar_plot(g2_shap_values1[0], max_display = 10, show = False, feature_names = g2_f1_names)
    fig = plt.gcf()
    ax = plt.gca()
    wrap_labels(ax, 20)
    ax.figure
    plt.tight_layout()
    fig.set_figheight(7)
    fig.set_figwidth(9)
    plt.xlabel("SHAP value (impact on model output)", fontsize =12, fontweight = 'heavy', labelpad = 8)
    plt.tick_params(axis="y",direction="out", labelsize = 12)
    plt.tick_params(axis="x",direction="out", labelsize = 12)
    return fig

#Define interpret for y2 (g2).
def g2_y2_interpret(*args):
    g2_df2 = pd.DataFrame([args], columns=g2_x2.columns)
    g2_shap_values2 = g2_y2_explainer(g2_df2).values
    g2_shap_values2 = np.abs(g2_shap_values2)
    shap.bar_plot(g2_shap_values2[0], max_display = 10, show = False, feature_names = g2_f2_names)
    fig = plt.gcf()
    ax = plt.gca()
    wrap_labels(ax, 20)
    ax.figure
    plt.tight_layout()
    fig.set_figheight(7)
    fig.set_figwidth(9)
    plt.xlabel("SHAP value (impact on model output)", fontsize =12, fontweight = 'heavy', labelpad = 8)
    plt.tick_params(axis="y",direction="out", labelsize = 12)
    plt.tick_params(axis="x",direction="out", labelsize = 12)
    return fig

#Define interpret for y3 (g2).
def g2_y3_interpret(*args):
    g2_df3 = pd.DataFrame([args], columns=g2_x3.columns)
    g2_shap_values3 = g2_y3_explainer(g2_df3).values
    g2_shap_values3 = np.abs(g2_shap_values3)
    shap.bar_plot(g2_shap_values3[0], max_display = 10, show = False, feature_names = g2_f3_names)
    fig = plt.gcf()
    ax = plt.gca()
    wrap_labels(ax, 20)
    ax.figure
    plt.tight_layout()
    fig.set_figheight(7)
    fig.set_figwidth(9)
    plt.xlabel("SHAP value (impact on model output)", fontsize =12, fontweight = 'heavy', labelpad = 8)
    plt.tick_params(axis="y",direction="out", labelsize = 12)
    plt.tick_params(axis="x",direction="out", labelsize = 12)
    return fig

#Define interpret for y4 (g2).
def g2_y4_interpret(*args):
    g2_df4 = pd.DataFrame([args], columns=g2_x4.columns)
    g2_shap_values4 = g2_y4_explainer(g2_df4).values
    g2_shap_values4 = np.abs(g2_shap_values4)
    shap.bar_plot(g2_shap_values4[0], max_display = 10, show = False, feature_names = g2_f4_names)
    fig = plt.gcf()
    ax = plt.gca()
    wrap_labels(ax, 20)
    ax.figure
    plt.tight_layout()
    fig.set_figheight(7)
    fig.set_figwidth(9)
    plt.xlabel("SHAP value (impact on model output)", fontsize =12, fontweight = 'heavy', labelpad = 8)
    plt.tick_params(axis="y",direction="out", labelsize = 12)
    plt.tick_params(axis="x",direction="out", labelsize = 12)
    return fig

#Define interpret for y1 (g3).
def g3_y1_interpret(*args):
    g3_df1 = pd.DataFrame([args], columns=g3_x1.columns)
    g3_shap_values1 = g3_y1_explainer(g3_df1).values
    g3_shap_values1 = np.abs(g3_shap_values1)
    shap.bar_plot(g3_shap_values1[0], max_display = 10, show = False, feature_names = g3_f1_names)
    fig = plt.gcf()
    ax = plt.gca()
    wrap_labels(ax, 20)
    ax.figure
    plt.tight_layout()
    fig.set_figheight(7)
    fig.set_figwidth(9)
    plt.xlabel("SHAP value (impact on model output)", fontsize =12, fontweight = 'heavy', labelpad = 8)
    plt.tick_params(axis="y",direction="out", labelsize = 12)
    plt.tick_params(axis="x",direction="out", labelsize = 12)
    return fig

#Define interpret for y2 (g3).
def g3_y2_interpret(*args):
    g3_df2 = pd.DataFrame([args], columns=g3_x2.columns)
    g3_shap_values2 = g3_y2_explainer(g3_df2).values
    g3_shap_values2 = np.abs(g3_shap_values2)
    shap.bar_plot(g3_shap_values2[0], max_display = 10, show = False, feature_names = g3_f2_names)
    fig = plt.gcf()
    ax = plt.gca()
    wrap_labels(ax, 20)
    ax.figure
    plt.tight_layout()
    fig.set_figheight(7)
    fig.set_figwidth(9)
    plt.xlabel("SHAP value (impact on model output)", fontsize =12, fontweight = 'heavy', labelpad = 8)
    plt.tick_params(axis="y",direction="out", labelsize = 12)
    plt.tick_params(axis="x",direction="out", labelsize = 12)
    return fig

#Define interpret for y3 (g3).
def g3_y3_interpret(*args):
    g3_df3 = pd.DataFrame([args], columns=g3_x3.columns)
    g3_shap_values3 = g3_y3_explainer(g3_df3).values
    g3_shap_values3 = np.abs(g3_shap_values3)
    shap.bar_plot(g3_shap_values3[0], max_display = 10, show = False, feature_names = g3_f3_names)
    fig = plt.gcf()
    ax = plt.gca()
    wrap_labels(ax, 20)
    ax.figure
    plt.tight_layout()
    fig.set_figheight(7)
    fig.set_figwidth(9)
    plt.xlabel("SHAP value (impact on model output)", fontsize =12, fontweight = 'heavy', labelpad = 8)
    plt.tick_params(axis="y",direction="out", labelsize = 12)
    plt.tick_params(axis="x",direction="out", labelsize = 12)
    return fig

#Define interpret for y4 (g3).
def g3_y4_interpret(*args):
    g3_df4 = pd.DataFrame([args], columns=g3_x4.columns)
    g3_shap_values4 = g3_y4_explainer(g3_df4).values
    g3_shap_values4 = np.abs(g3_shap_values4)
    shap.bar_plot(g3_shap_values4[0], max_display = 10, show = False, feature_names = g3_f4_names)
    fig = plt.gcf()
    ax = plt.gca()
    wrap_labels(ax, 20)
    ax.figure
    plt.tight_layout()
    fig.set_figheight(7)
    fig.set_figwidth(9)
    plt.xlabel("SHAP value (impact on model output)", fontsize =12, fontweight = 'heavy', labelpad = 8)
    plt.tick_params(axis="y",direction="out", labelsize = 12)
    plt.tick_params(axis="x",direction="out", labelsize = 12)
    return fig

with gr.Blocks(title = "NCDB-G2G3 Glioma") as demo:
        
    gr.Markdown(
        """
    <br/>
    <center><h2>NOT FOR CLINICAL USE</h2><center>    
    <br/>    
    <center><h1>Grade II and III Glioma Survival Outcomes</h1></center>
    <center><h2>Prediction Tool</h2></center>
    <br/>
    <center><h3>This web application should not be used to guide any clinical decisions.</h3><center>
        """
    )

    gr.Markdown(
        """
        <center><h3>Model Performances for Grade II Gliomas</h3></center>
          <div style="text-align:center;">
          <table style="width:100%;">
          <tr>
            <th>Outcome</th>
            <th>Algorithm</th>
            <th>Sensitivity</th>
            <th>Specificity</th>
            <th>Accuracy</th>
            <th>AUPRC</th>
            <th>AUROC</th>
            <th>Brier Score</th>
          </tr>
          <tr>
            <td>12-Month Mortality</td>
            <td>Random Forest</td>
            <td>0.838 (0.822 - 0.854)</td>
            <td>0.814 (0.797 - 0.831)</td>
            <td>0.816 (0.799 - 0.833)</td>
            <td>0.383 (0.361 - 0.405)</td>
            <td>0.888 (0.856 - 0.912)</td>
            <td>0.054 (0.044 - 0.064)</td>             
          </tr>
          <tr>
            <td>24-Month Mortality</td>
            <td>LightGBM</td>
            <td>0.712 (0.692 - 0.732)</td>
            <td>0.839 (0.822 - 0.856)</td>
            <td>0.823 (0.806 - 0.840)</td>
            <td>0.523 (0.500 - 0.546)</td>
            <td>0.859 (0.804 - 0.867)</td>
            <td>0.054 (0.044 - 0.064)</td>             
          </tr>
          <tr>
            <td>36-Month Mortality</td>
            <td>LightGBM</td>
            <td>0.653 (0.631 - 0.675)</td>
            <td>0.836 (0.819 - 0.853)</td>
            <td>0.803 (0.785 - 0.821)</td>
            <td>0.564 (0.541 - 0.587)</td>
            <td>0.813 (0.777 - 0.835)</td>
            <td>0.111 (0.096 - 0.126)</td>             
          </tr>                        
          <tr>
            <td>60-Month Mortality</td>
            <td>Random Forest</td>
            <td>0.838 (0.822 - 0.854)</td>
            <td>0.814 (0.797 - 0.831)</td>
            <td>0.816 (0.799 - 0.833)</td>
            <td>0.383 (0.361 - 0.405)</td>
            <td>0.888 (0.856 - 0.912)</td>
            <td>0.054 (0.044 - 0.064)</td>             
          </tr>        
        </table>
        </div>
        """
    )

    gr.Markdown(
        """
    <br/>
        """
    )
    
    
    gr.Markdown(
        """
        <center><h3>Model Performances for Grade III Gliomas</h3></center>
          <div style="text-align:center;">
          <table style="width:100%;">
          <tr>
            <th>Outcome</th>
            <th>Algorithm</th>
            <th>Sensitivity</th>
            <th>Specificity</th>
            <th>Accuracy</th>
            <th>AUPRC</th>
            <th>AUROC</th>
            <th>Brier Score</th>
          </tr>
          <tr>
            <td>12-Month Mortality</td>
            <td>LightGBM</td>
            <td>0.768 (0.750 - 0.786)</td>
            <td>0.811 (0.795 - 0.827)</td>
            <td>0.800 (0.783 - 0.817)</td>
            <td>0.725 (0.706 - 0.744)</td>
            <td>0.876 (0.857 - 0.889)</td>
            <td>0.119 (0.106 - 0.132)</td>             
          </tr>
          <tr>
            <td>24-Month Mortality</td>
            <td>Random Forest</td>
            <td>0.722 (0.703 - 0.741)</td>
            <td>0.810 (0.794 - 0.826)</td>
            <td>0.796 (0.779 - 0.813)</td>
            <td>0.775 (0.758 - 0.792)</td>
            <td>0.855 (0.839 - 0.870)</td>
            <td>0.153 (0.138 - 0.168)</td>             
          </tr>
          <tr>
            <td>36-Month Mortality</td>
            <td>Random Forest</td>
            <td>0.763 (0.745 - 0.781)</td>
            <td>0.827 (0.811 - 0.843)</td>
            <td>0.874 (0.860 - 0.888)</td>
            <td>0.794 (0.777 - 0.811)</td>
            <td>0.878 (0.857 - 0.885)</td>
            <td>0.146 (0.131 - 0.161)</td>             
          </tr>                        
          <tr>
            <td>60-Month Mortality</td>
            <td>LightGBM</td>
            <td>0.816 (0.798 - 0.834)</td>
            <td>0.748 (0.728 - 0.768)</td>
            <td>0.930 (0.918 - 0.942)</td>
            <td>0.795 (0.776 - 0.814)</td>
            <td>0.860 (0.834 - 0.870)</td>
            <td>0.142 (0.126 - 0.158)</td>             
          </tr>        
        </table>
        </div>
        """
    )
    
    gr.Markdown(
        """
    <br/>
        """
    )    
    
    with gr.Tab('Grade II'):
        
            with gr.Row():

                with gr.Column():

                    Age = gr.Slider(label="Age", minimum = 18, maximum = 99, step = 1, value = 55)

                    Sex = gr.Dropdown(label = "Sex", choices = ['Male', 'Female'], type = 'index', value = 'Male')

                    Race = gr.Dropdown(label = "Race", choices = ['White', 'Black', 'Asian Indian or Pakistani', 'Chinese', 'Filipino', 'American Indian, Aleutian, or Eskimo', 'Vietnamese', 'Korean', 'Other or Unknown'], type = 'index', value = 'White')

                    Hispanic_Ethnicity = gr.Dropdown(label = "Hispanic Ethnicity", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'No')

                    Primary_Payor = gr.Dropdown(label = "Primary Payor", choices = ['Private insurance', 'Medicare', 'Medicaid', 'Other government', 'Not insured', 'Unknown'], type = 'index', value = 'Private insurance')

                    Facility_Type = gr.Dropdown(label = "Facility Type", choices = ['Academic/Research Program', 'Comprehensive Community Cancer Program', 'Integrated Network Cancer Program', 'Community Cancer Program', 'Other or Unknown'], type = 'index', value = 'Academic/Research Program')

                    Facility_Location = gr.Dropdown(label = "Facility Location", choices = ['South Atlantic', 'East North Central', 'Middle Atlantic', 'East North Central', 'Middle Atlantic', 'Pacific', 'West South Central', 'West North Central', 'East South Central', 'New England', 'Mountain', 'Unknown or Other'], type = 'index', value = 'South Atlantic')

                    CharlsonDeyo_Score = gr.Dropdown(label = "Charlson-Deyo Score", choices = ['0', '1', '2', 'Greater than 3'], type = 'index', value = '0')
                    Karnofsky_Performance_Scale = gr.Dropdown(label = "Karnofsky Performance Scale", choices = ['KPS 0-20', 'KPS 21-40', 'KPS 41-60', 'KPS 61-80', 'KPS 81-100', 'Unknown'], type = 'index', value = 'KPS 81-100')

                    Laterality = gr.Dropdown(label = "Laterality", choices = ['Right', 'Left', 'Bilateral', 'Midline', 'Unknown'], type = 'index', value = 'Right')

                    Tumor_Localization = gr.Dropdown(label = "Tumor Localization", choices = ['Frontal lobe', 'Temporal lobe', 'Parietal lobe', 'Occipital lobe', 'Overlapping', 'Intraventricular', 'Cerebellum', 'Brain stem', 'Unknown'], type = 'index', value = 'Frontal lobe')

                    Focality = gr.Dropdown(label = "Focality", choices = ['Unifocal', 'Multifocal', 'Unknown'], type = 'index', value = 'Unifocal')

                    Diagnostic_Biopsy = gr.Dropdown(label = "Diagnostic Biopsy", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'No')

                    Tumor_Size = gr.Dropdown(label = "Tumor Size", choices = ['< 2 cm', '2 - 3.9 cm', '4 - 5.9 cm', '6 - 7.9 cm', '8 - 9.9 cm', '10 - 11.9 cm', '12 - 13.9 cm', '14 - 15.9 cm', '16 - 17.9 cm', '18 - 19.9 cm', '> 20 cm', 'Unknown'], type = 'index', value = '< 2 cm')

                    Histology = gr.Dropdown(label = "Histology", choices = ['Pilomyxoid astrocytoma', 'Diffuse astrocytoma', 'Pleomorphic astrocytoma', 'Oligodendroglioma', 'Oligoastrocytoma'], type = 'index', value = 'Diffuse astrocytoma')

                    CoDeletion_1p19q = gr.Dropdown(label = "1p19q Co-Deletion", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'No')

                    MGMT_Methylation = gr.Dropdown(label = "MGMT Methylation", choices = ['Unmethylated', 'Methylated', 'Unknown'], type = 'index', value = 'Unmethylated')

                    Ki67_Labeling_Index = gr.Dropdown(label = 'Ki-67 Labeling Index', choices = ['0-20%', '21-40%', '41-60%', '61-80%', '81-100%', 'Normal (no percentage available)', 'Slightly elevated (no percentage available)', 'Elevated (no percentage available)', 'Unknown'], type = 'index', value = '0-20%')

                    Extent_of_Resection = gr.Dropdown(label = "Extent of Resection", choices = ['No resective surgery was performed', 'Gross total resection', 'Subtotal resection', 'Unknown'], type = 'index', value = 'Gross total resection')

                    Radiation_Treatment = gr.Dropdown(label = "Radiation Treatment", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'Yes')

                    Chemotherapy = gr.Dropdown(label = "Chemotherapy", choices = ['No', 'Yes (single-agent chemotherapy)', 'Yes (multi-agent chemotherapy)', 'Yes (details unknown)', 'Unknown'], type = 'index', value = 'No')

                    Immunotherapy = gr.Dropdown(label = "Immunotherapy", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'No')

                with gr.Column():

                    with gr.Box():

                        gr.Markdown(
                            """
                            <center> <h2>12-Month Survival</h2> </center>
                            <br/>
                            <center> This model uses the Random Forest algorithm.</center>
                            <br/>
                            """
                            )

                        with gr.Row():
                            y1_predict_btn = gr.Button(value="Predict")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        label1 = gr.Markdown()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        with gr.Row():
                            y1_interpret_btn = gr.Button(value="Explain")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        plot1 = gr.Plot()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                    with gr.Box():
                        gr.Markdown(
                            """
                            <center> <h2>24-Month Survival</h2> </center>
                            <br/>
                            <center> This model uses the LightGBM algorithm.</center>
                            <br/>
                            """
                            )

                        with gr.Row():
                            y2_predict_btn = gr.Button(value="Predict")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        label2 = gr.Markdown()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        with gr.Row():
                            y2_interpret_btn = gr.Button(value="Explain")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        plot2 = gr.Plot()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                    with gr.Box():

                        gr.Markdown(
                            """
                            <center> <h2>36-Month Survival</h2> </center>
                            <br/>
                            <center> This model uses the LightGBM algorithm.</center>
                            <br/>
                            """
                            )

                        with gr.Row():
                            y3_predict_btn = gr.Button(value="Predict")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        label3 = gr.Markdown()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        with gr.Row():
                            y3_interpret_btn = gr.Button(value="Explain")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        plot3 = gr.Plot()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )  

                    with gr.Box():

                        gr.Markdown(
                            """
                            <center> <h2>60-Month Survival</h2> </center>
                            <br/>
                            <center> This model uses the Random Forest algorithm.</center>
                            <br/>
                            """
                            )

                        with gr.Row():
                            y4_predict_btn = gr.Button(value="Predict")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        label4 = gr.Markdown()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        with gr.Row():
                            y4_interpret_btn = gr.Button(value="Explain")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        plot4 = gr.Plot()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )  


                        y1_predict_btn.click(
                            g2_y1_predict,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [label1]
                        )

                        y2_predict_btn.click(
                            g2_y2_predict,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [label2]
                        )

                        y3_predict_btn.click(
                            g2_y3_predict,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [label3]
                        )

                        y4_predict_btn.click(
                            g2_y4_predict,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [label4]
                        )

                        y1_interpret_btn.click(
                            g2_y1_interpret,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [plot1],
                        )

                        y2_interpret_btn.click(
                            g2_y2_interpret,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [plot2],
                        )

                        y3_interpret_btn.click(
                            g2_y3_interpret,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                          outputs = [plot3],
                        )

                        y4_interpret_btn.click(
                            g2_y4_interpret,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                  outputs = [plot4],
                )

    with gr.Tab('Grade III'):
        
            with gr.Row():

                with gr.Column():

                    Age = gr.Slider(label="Age", minimum = 18, maximum = 99, step = 1, value = 55)

                    Sex = gr.Dropdown(label = "Sex", choices = ['Male', 'Female'], type = 'index', value = 'Male')

                    Race = gr.Dropdown(label = "Ethnicity", choices = ['White', 'Black', 'Asian Indian or Pakistani', 'Chinese', 'Filipino', 'American Indian, Aleutian, or Eskimo', 'Vietnamese', 'Korean', 'Other or Unknown'], type = 'index', value = 'White')

                    Hispanic_Ethnicity = gr.Dropdown(label = "Spanish/Hispanic Origin", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'No')

                    Primary_Payor = gr.Dropdown(label = "Primary Payor", choices = ['Private insurance', 'Medicare', 'Medicaid', 'Other government', 'Not insured', 'Unknown'], type = 'index', value = 'Private insurance')

                    Facility_Type = gr.Dropdown(label = "Facility Type", choices = ['Academic/Research Program', 'Comprehensive Community Cancer Program', 'Integrated Network Cancer Program', 'Community Cancer Program', 'Other or Unknown'], type = 'index', value = 'Academic/Research Program')

                    Facility_Location = gr.Dropdown(label = "Facility Location", choices = ['South Atlantic', 'East North Central', 'Middle Atlantic', 'East North Central', 'Middle Atlantic', 'Pacific', 'West South Central', 'West North Central', 'East South Central', 'New England', 'Mountain', 'Unknown or Other'], type = 'index', value = 'South Atlantic')

                    CharlsonDeyo_Score = gr.Dropdown(label = "Charlson-Deyo Score", choices = ['0', '1', '2', 'Greater than 3'], type = 'index', value = '0')
                    Karnofsky_Performance_Scale = gr.Dropdown(label = "Karnofsky Performance Scale", choices = ['KPS 0-20', 'KPS 21-40', 'KPS 41-60', 'KPS 61-80', 'KPS 81-100', 'Unknown'], type = 'index', value = 'KPS 81-100')

                    Laterality = gr.Dropdown(label = "Laterality", choices = ['Right', 'Left', 'Bilateral', 'Midline', 'Unknown'], type = 'index', value = 'Right')

                    Tumor_Localization = gr.Dropdown(label = "Tumor Localization", choices = ['Frontal lobe', 'Temporal lobe', 'Parietal lobe', 'Occipital lobe', 'Overlapping', 'Intraventricular', 'Cerebellum', 'Brain stem', 'Unknown'], type = 'index', value = 'Frontal lobe')

                    Focality = gr.Dropdown(label = "Focality", choices = ['Unifocal', 'Multifocal', 'Unknown'], type = 'index', value = 'Unifocal')

                    Diagnostic_Biopsy = gr.Dropdown(label = "Diagnostic Biopsy", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'No')

                    Tumor_Size = gr.Dropdown(label = "Tumor Size", choices = ['< 2 cm', '2 - 3.9 cm', '4 - 5.9 cm', '6 - 7.9 cm', '8 - 9.9 cm', '10 - 11.9 cm', '12 - 13.9 cm', '14 - 15.9 cm', '16 - 17.9 cm', '18 - 19.9 cm', '> 20 cm', 'Unknown'], type = 'index', value = '< 2 cm')

                    Histology = gr.Dropdown(label = "Histology", choices = ['Anaplastic astrocytoma', 'Anaplastic oligodendroglioma', 'Anaplastic oligoastrocytoma'], type = 'index', value = 'Anaplastic astrocytoma')

                    CoDeletion_1p19q = gr.Dropdown(label = "1p19q Co-Deletion", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'No')

                    MGMT_Methylation = gr.Dropdown(label = "MGMT Methylation", choices = ['Unmethylated', 'Methylated', 'Unknown'], type = 'index', value = 'Unmethylated')

                    Ki67_Labeling_Index = gr.Dropdown(label = 'Ki-67 Labeling Index', choices = ['0-20%', '21-40%', '41-60%', '61-80%', '81-100%', 'Normal (no percentage available)', 'Slightly elevated (no percentage available)', 'Elevated (no percentage available)', 'Unknown'], type = 'index', value = '0-20%')

                    Extent_of_Resection = gr.Dropdown(label = "Extent of Resection", choices = ['No resective surgery was performed', 'Gross total resection', 'Subtotal resection', 'Unknown'], type = 'index', value = 'Gross total resection')

                    Radiation_Treatment = gr.Dropdown(label = "Radiation Treatment", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'Yes')

                    Chemotherapy = gr.Dropdown(label = "Chemotherapy", choices = ['No', 'Yes (single-agent chemotherapy)', 'Yes (multi-agent chemotherapy)', 'Yes (details unknown)', 'Unknown'], type = 'index', value = 'No')

                    Immunotherapy = gr.Dropdown(label = "Immunotherapy", choices = ['No', 'Yes', 'Unknown'], type = 'index', value = 'No')

                with gr.Column():

                    with gr.Box():

                        gr.Markdown(
                            """
                            <center> <h2>12-Month Survival</h2> </center>
                            <br/>
                            <center> This model uses the LightGBM algorithm.</center>
                            <br/>
                            """
                            )

                        with gr.Row():
                            y1_predict_btn = gr.Button(value="Predict")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        label1 = gr.Markdown()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        with gr.Row():
                            y1_interpret_btn = gr.Button(value="Explain")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        plot1 = gr.Plot()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                    with gr.Box():
                        gr.Markdown(
                            """
                            <center> <h2>24-Month Survival</h2> </center>
                            <br/>
                            <center> This model uses the Random Forest algorithm.</center>
                            <br/>
                            """
                            )

                        with gr.Row():
                            y2_predict_btn = gr.Button(value="Predict")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        label2 = gr.Markdown()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        with gr.Row():
                            y2_interpret_btn = gr.Button(value="Explain")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        plot2 = gr.Plot()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                    with gr.Box():

                        gr.Markdown(
                            """
                            <center> <h2>36-Month Survival</h2> </center>
                            <br/>
                            <center> This model uses the Random Forest algorithm.</center>
                            <br/>
                            """
                            )

                        with gr.Row():
                            y3_predict_btn = gr.Button(value="Predict")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        label3 = gr.Markdown()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        with gr.Row():
                            y3_interpret_btn = gr.Button(value="Explain")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        plot3 = gr.Plot()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )  

                    with gr.Box():

                        gr.Markdown(
                            """
                            <center> <h2>60-Month Survival</h2> </center>
                            <br/>
                            <center> This model uses the LightGBM algorithm.</center>
                            <br/>
                            """
                            )

                        with gr.Row():
                            y4_predict_btn = gr.Button(value="Predict")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        label4 = gr.Markdown()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        with gr.Row():
                            y4_interpret_btn = gr.Button(value="Explain")

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )

                        plot4 = gr.Plot()

                        gr.Markdown(
                            """
                            <br/>
                            """
                            )  


                        y1_predict_btn.click(
                            g3_y1_predict,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [label1]
                        )

                        y2_predict_btn.click(
                            g3_y2_predict,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [label2]
                        )

                        y3_predict_btn.click(
                            g3_y3_predict,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [label3]
                        )

                        y4_predict_btn.click(
                            g3_y4_predict,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [label4]
                        )

                        y1_interpret_btn.click(
                            g3_y1_interpret,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [plot1],
                        )

                        y2_interpret_btn.click(
                            g3_y2_interpret,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                            outputs = [plot2],
                        )

                        y3_interpret_btn.click(
                            g3_y3_interpret,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                          outputs = [plot3],
                        )

                        y4_interpret_btn.click(
                            g3_y4_interpret,
                            inputs = [Facility_Type,Facility_Location,Age,Sex,Race,Hispanic_Ethnicity,Primary_Payor,CharlsonDeyo_Score,Histology,Tumor_Localization,Laterality,Diagnostic_Biopsy,Ki67_Labeling_Index,Karnofsky_Performance_Scale,MGMT_Methylation,Focality,Tumor_Size,Chemotherapy,Immunotherapy,CoDeletion_1p19q,Extent_of_Resection,Radiation_Treatment],
                  outputs = [plot4],
                )                        
                               
    gr.Markdown(
                """    
                <center><h2>Disclaimer</h2>
                <center> 
                The data utilized for this tool is sourced from the Commission on Cancer (CoC) of the American College of Surgeons and the American Cancer Society. These institutions, however, have not verified the information and are not responsible for the statistical validity of the data analysis or the conclusions drawn by the authors. This predictive tool, available on this webpage, is designed to provide general health information only and is not a substitute for professional medical advice, diagnosis, or treatment. It is strongly recommended that users consult with their own healthcare provider for any health-related concerns or issues. The authors make no warranties or representations, express or implied, regarding the accuracy, timeliness, relevance, or utility of the information contained in this tool. The health information in the prediction tool is subject to change and can be affected by various confounders, therefore it may be outdated, incomplete, or incorrect. No doctor-patient relationship is created by using this prediction tool and the authors have not validated its content. The authors do not record any specific user information or initiate contact with users. Before making any healthcare decisions or taking or refraining from any action based on the information in this prediction tool, it is advisable to seek professional advice from a healthcare provider. By using the prediction tool, users acknowledge and agree that neither the authors nor any other party will be liable for any decisions made, actions taken or not taken as a result of the information provided herein.
                <br/>
                <h4>By using this tool, you accept all of the above terms.<h4/>
                </center>
                """
    )                
                
demo.launch()