File size: 67,449 Bytes
59a9ccf
7fa8b10
5bb223e
99e133c
 
5bb223e
 
 
 
5f136c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99e133c
 
 
 
 
 
 
 
 
 
5f136c5
96198c4
99e133c
 
 
a372d2a
dadf5f2
8dd2959
 
 
 
 
 
 
 
 
 
 
72b6bdd
 
19e8804
96198c4
 
99e133c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59a9ccf
b122ddc
 
 
 
 
 
 
 
 
 
7714bff
25d992f
8ff8fc7
 
 
 
 
 
 
 
 
 
b122ddc
 
250c90d
b122ddc
 
 
 
 
 
 
250c90d
 
 
 
b122ddc
 
 
34b069c
 
bb8021c
34b069c
 
 
 
 
 
 
bb8021c
 
34b069c
 
250c90d
 
34b069c
250c90d
 
34b069c
 
250c90d
 
1b950bb
1b8d3ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ff8fc7
1b8d3ac
8ff8fc7
1b8d3ac
8ff8fc7
 
 
 
 
1b8d3ac
 
 
8ff8fc7
 
 
 
 
 
1b8d3ac
384e099
 
8ff8fc7
1b8d3ac
 
 
8ff8fc7
1b8d3ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b950bb
34b069c
1b8d3ac
 
 
 
 
 
 
 
33bb1d2
1b8d3ac
 
 
 
 
 
 
33bb1d2
1b8d3ac
 
 
 
 
 
 
33bb1d2
1b8d3ac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33bb1d2
1b8d3ac
 
 
 
 
34b069c
250c90d
 
 
 
34b069c
250c90d
 
1b8d3ac
250c90d
1b950bb
 
33bb1d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b950bb
 
 
 
 
 
 
 
 
 
 
59a9ccf
72b6bdd
59a9ccf
 
8a6c540
 
99e133c
 
 
 
 
59a9ccf
72b6bdd
 
 
 
 
 
59a9ccf
 
72b6bdd
59a9ccf
 
 
 
 
 
 
 
 
 
 
7d02436
59a9ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6c540
 
59a9ccf
 
 
 
8a6c540
 
 
 
 
 
 
 
 
59a9ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6c540
 
 
 
 
59a9ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb5d1fc
59a9ccf
 
 
 
 
dadf5f2
 
 
59a9ccf
 
2446683
 
 
 
 
59a9ccf
 
2446683
59a9ccf
 
2446683
59a9ccf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6c540
bcfc971
 
 
 
 
 
a71505c
8a6c540
a71505c
 
 
8a6c540
a71505c
 
 
 
8a6c540
a71505c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6c540
a71505c
bcfc971
 
8a6c540
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcfc971
 
 
 
 
 
 
8a6c540
bcfc971
 
 
 
 
 
dadf5f2
 
 
 
 
 
 
 
 
 
 
59a9ccf
535c8ca
 
 
 
59a9ccf
 
535c8ca
 
 
 
 
 
 
 
 
 
 
 
 
 
e31033d
dadf5f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6c540
dadf5f2
 
 
 
59a9ccf
dadf5f2
 
 
 
 
 
 
 
 
59a9ccf
e31033d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dadf5f2
e31033d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a6c540
25d992f
6f38a8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1dab7bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25d992f
 
fc6decc
 
 
 
 
 
3a56ec4
1dab7bb
25d992f
384e099
 
 
 
 
 
25d992f
384e099
 
 
 
 
 
25d992f
384e099
 
 
 
 
1dab7bb
fc6decc
 
 
 
 
 
 
 
 
 
1dab7bb
 
384e099
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93008f1
3a56ec4
384e099
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a56ec4
384e099
 
3a56ec4
384e099
 
 
 
 
3a56ec4
384e099
 
3a56ec4
384e099
 
 
 
 
 
3a56ec4
384e099
 
 
 
fc6decc
384e099
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a56ec4
25d992f
384e099
25d992f
3a56ec4
25d992f
 
 
1dab7bb
25d992f
 
 
 
96198c4
 
25d992f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96198c4
25d992f
 
 
 
 
 
 
 
384e099
96198c4
 
384e099
96198c4
 
72b6bdd
25d992f
72b6bdd
25d992f
 
 
96198c4
72b6bdd
 
25d992f
72b6bdd
25d992f
72b6bdd
25d992f
 
 
96198c4
25d992f
 
384e099
96198c4
384e099
 
 
 
 
96198c4
 
 
 
 
 
 
 
 
 
 
 
 
6f38a8f
25d992f
8ff8fc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a57ea9b
 
e31033d
a57ea9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1d5993
1b950bb
 
a57ea9b
 
 
 
 
 
 
 
 
 
 
 
 
bb8021c
 
a57ea9b
bb8021c
a57ea9b
 
 
 
 
 
 
 
 
 
 
 
bb8021c
 
b122ddc
 
 
 
 
 
 
3a56ec4
 
b122ddc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b950bb
c1d5993
a57ea9b
380523e
3a56ec4
 
380523e
 
a57ea9b
380523e
3a56ec4
 
 
380523e
c1d5993
 
3a56ec4
c1d5993
380523e
 
 
 
 
 
 
 
 
 
 
 
c1d5993
 
380523e
 
 
 
 
 
 
 
 
 
 
 
c1d5993
a57ea9b
380523e
 
3a56ec4
380523e
3a56ec4
380523e
c1d5993
 
 
380523e
a57ea9b
380523e
 
 
 
c1d5993
 
 
 
 
 
3a56ec4
c1d5993
3a56ec4
380523e
3a56ec4
 
380523e
c1d5993
380523e
 
 
 
 
 
 
3a56ec4
380523e
 
 
 
 
 
 
 
 
 
 
 
 
3a56ec4
380523e
 
 
 
 
 
 
 
 
c1d5993
380523e
 
 
 
 
 
c1d5993
 
380523e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bcfc971
3a56ec4
36ba1c1
3a56ec4
36ba1c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a56ec4
36ba1c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cebc63d
3a56ec4
36ba1c1
3a56ec4
380523e
3a56ec4
 
380523e
c1d5993
3a56ec4
380523e
3a56ec4
380523e
3a56ec4
380523e
 
3a56ec4
380523e
3a56ec4
380523e
5eaa79d
380523e
c1d5993
 
380523e
 
 
 
 
 
 
 
 
 
 
c1d5993
3a56ec4
380523e
3a56ec4
380523e
3a56ec4
380523e
3a56ec4
 
380523e
 
c1d5993
5eaa79d
3a56ec4
5eaa79d
 
 
 
380523e
 
 
 
1b950bb
c1d5993
1b950bb
 
a57ea9b
c1d5993
3a56ec4
1b950bb
3a56ec4
 
380523e
3a56ec4
 
 
 
 
c1d5993
 
a57ea9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b950bb
 
 
 
a57ea9b
e989c1c
 
 
 
 
 
 
a57ea9b
e989c1c
 
 
 
 
 
 
a57ea9b
1b950bb
 
 
 
bcfc971
e989c1c
a57ea9b
1b950bb
 
 
 
bcfc971
 
1b950bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e989c1c
25d992f
 
 
 
 
 
 
 
 
 
 
 
 
 
91ce7fe
25d992f
 
 
 
 
 
 
 
 
 
 
 
 
 
a57ea9b
25d992f
 
 
 
 
 
 
1b950bb
 
 
 
 
c1d5993
 
a57ea9b
5f136c5
 
 
 
 
 
 
 
a57ea9b
93008f1
 
 
 
 
 
 
 
 
 
 
 
 
 
1dab7bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b950bb
c1d5993
384e099
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
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
import os,sys
import traceback  # ์ƒ๋‹จ์— ์ถ”๊ฐ€
# install required packages
os.system('pip install plotly')  # plotly ์„ค์น˜
os.system('pip install matplotlib')  # matplotlib ์„ค์น˜
os.system('pip install dgl==1.0.2+cu116 -f https://data.dgl.ai/wheels/cu116/repo.html')
os.environ["DGLBACKEND"] = "pytorch"
print('Modules installed')

# ๊ธฐ๋ณธ args ์„ค์ •
if not os.path.exists('./tmp'):
    os.makedirs('./tmp')

if not os.path.exists('./tmp/args.json'):
    default_args = {
        'checkpoint': None,
        'dump_trb': False,
        'dump_args': True,
        'save_best_plddt': True,
        'T': 25,
        'strand_bias': 0.0,
        'loop_bias': 0.0,
        'helix_bias': 0.0,
        'd_t1d': 24,
        'potentials': None,
        'potential_scale': None,
        'aa_composition': None
    }
    with open('./tmp/args.json', 'w') as f:
        json.dump(default_args, f)

# ์ฒดํฌํฌ์ธํŠธ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ
if not os.path.exists('./SEQDIFF_230205_dssp_hotspots_25mask_EQtasks_mod30.pt'):
    print('Downloading model weights 1')
    os.system('wget http://files.ipd.uw.edu/pub/sequence_diffusion/checkpoints/SEQDIFF_230205_dssp_hotspots_25mask_EQtasks_mod30.pt')
    print('Successfully Downloaded')

if not os.path.exists('./SEQDIFF_221219_equalTASKS_nostrSELFCOND_mod30.pt'):
    print('Downloading model weights 2')
    os.system('wget http://files.ipd.uw.edu/pub/sequence_diffusion/checkpoints/SEQDIFF_221219_equalTASKS_nostrSELFCOND_mod30.pt')
    print('Successfully Downloaded')


from openai import OpenAI
import gradio as gr
import json  # json ๋ชจ๋“ˆ ์ถ”๊ฐ€
from datasets import load_dataset
import plotly.graph_objects as go
import numpy as np
import py3Dmol
from io import StringIO
import json
import secrets
import copy
import matplotlib.pyplot as plt
from utils.sampler import HuggingFace_sampler
from utils.parsers_inference import parse_pdb
from model.util import writepdb
from utils.inpainting_util import *
import os

from Bio import SeqIO, Align
from Bio.Seq import Seq

# args ๋กœ๋“œ
with open('./tmp/args.json', 'r') as f:
    args = json.load(f)

plt.rcParams.update({'font.size': 13})

# manually set checkpoint to load
args['checkpoint'] = None
args['dump_trb'] = False
args['dump_args'] = True
args['save_best_plddt'] = True
args['T'] = 25
args['strand_bias'] = 0.0
args['loop_bias'] = 0.0
args['helix_bias'] = 0.0

# Hugging Face ํ† ํฐ ์„ค์ •
ACCESS_TOKEN = os.getenv("HF_TOKEN")
if not ACCESS_TOKEN:
    raise ValueError("HF_TOKEN not found in environment variables")

# OpenAI ํด๋ผ์ด์–ธํŠธ ์„ค์ • (Hugging Face ์—”๋“œํฌ์ธํŠธ ์‚ฌ์šฉ)
client = OpenAI(
    base_url="https://api-inference.huggingface.co/v1/",
    api_key=ACCESS_TOKEN,
)


# ๋ฐ์ดํ„ฐ์…‹ ๋กœ๋“œ ๋ฐ ๊ตฌ์กฐ ํ™•์ธ
try:
    ds = load_dataset("lamm-mit/protein_secondary_structure_from_PDB",
                     token=ACCESS_TOKEN)
    print("Dataset structure:", ds)
    print("First entry example:", next(iter(ds['train'])))
except Exception as e:
    print(f"Dataset loading error: {str(e)}")
    raise
    
def respond(
    message,
    history,
    system_message,
    max_tokens,
    temperature,
    top_p,
):
    messages = [{"role": "system", "content": system_message}]

    for msg in history:
        messages.append({"role": "user", "content": msg[0]})
        if msg[1]:
            messages.append({"role": "assistant", "content": msg[1]})

    messages.append({"role": "user", "content": message})

    try:
        response = ""
        for chunk in client.chat.completions.create(
            model="CohereForAI/c4ai-command-r-plus-08-2024",
            max_tokens=max_tokens,
            stream=True,
            temperature=temperature,
            top_p=top_p,
            messages=messages,
        ):
            if hasattr(chunk.choices[0].delta, 'content'):
                token = chunk.choices[0].delta.content
                if token is not None:
                    response += token
                    yield [{"role": "user", "content": message},
                          {"role": "assistant", "content": response}]
        
        return [{"role": "user", "content": message},
                {"role": "assistant", "content": response}]
    except Exception as e:
        print(f"Error in respond: {str(e)}")
        return [{"role": "user", "content": message},
                {"role": "assistant", "content": f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"}]

def analyze_prompt(message):
    """LLM์„ ์‚ฌ์šฉํ•˜์—ฌ ํ”„๋กฌํ”„ํŠธ ๋ถ„์„"""
    try:
        analysis_prompt = f"""
        ๋‹ค์Œ ์š”์ฒญ์„ ๋ถ„์„ํ•˜์—ฌ ๋‹จ๋ฐฑ์งˆ ์„ค๊ณ„์— ํ•„์š”ํ•œ ์ฃผ์š” ํŠน์„ฑ์„ ์ถ”์ถœํ•˜์„ธ์š”:
        ์š”์ฒญ: {message}
        
        ๋‹ค์Œ ํ•ญ๋ชฉ๋“ค์„ ๋ถ„์„ํ•ด์ฃผ์„ธ์š”:
        1. ์ฃผ์š” ๊ธฐ๋Šฅ (์˜ˆ: ์น˜๋ฃŒ, ๊ฒฐํ•ฉ, ์ด‰๋งค ๋“ฑ)
        2. ๋ชฉํ‘œ ํ™˜๊ฒฝ (์˜ˆ: ์„ธํฌ๋ง‰, ์ˆ˜์šฉ์„ฑ, ๋“ฑ)
        3. ํ•„์š”ํ•œ ๊ตฌ์กฐ์  ํŠน์ง•
        4. ํฌ๊ธฐ ๋ฐ ๋ณต์žก๋„ ์š”๊ตฌ์‚ฌํ•ญ
        """
        
        response = client.chat.completions.create(
            model="CohereForAI/c4ai-command-r-plus-08-2024",
            messages=[{"role": "user", "content": analysis_prompt}],
            temperature=0.7
        )
        
        return response.choices[0].message.content
    except Exception as e:
        print(f"ํ”„๋กฌํ”„ํŠธ ๋ถ„์„ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
        return None

def search_protein_data(analysis, dataset):
    """๋ถ„์„ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๋ฐ์ดํ„ฐ์…‹์—์„œ ์œ ์‚ฌํ•œ ๊ตฌ์กฐ ๊ฒ€์ƒ‰"""
    try:
        # ํ‚ค์›Œ๋“œ ์ถ”์ถœ
        keywords = extract_keywords(analysis)
        print("Extracted keywords:", keywords)
        
        # ๋ฐ์ดํ„ฐ์…‹ ๊ตฌ์กฐ ํ™•์ธ
        if not dataset or 'train' not in dataset:
            print("Invalid dataset structure")
            return []
            
        # ์œ ์‚ฌ๋„ ์ ์ˆ˜ ๊ณ„์‚ฐ
        scored_entries = []
        for entry in dataset['train']:
            try:
                score = calculate_similarity(keywords, entry)
                scored_entries.append((score, entry))
            except Exception as e:
                print(f"Error processing entry: {str(e)}")
                continue
        
        # ๊ฒฐ๊ณผ ์ •๋ ฌ ๋ฐ ๋ฐ˜ํ™˜ (key ํ•จ์ˆ˜ ์‚ฌ์šฉ)
        return sorted(scored_entries, key=lambda x: x[0], reverse=True)[:3]
        
    except Exception as e:
        print(f"๋ฐ์ดํ„ฐ ๊ฒ€์ƒ‰ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
        return []
        
def extract_parameters(analysis, similar_structures):
    """๋ถ„์„ ๊ฒฐ๊ณผ์™€ ์œ ์‚ฌ ๊ตฌ์กฐ๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ์ƒ์„ฑ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฒฐ์ •"""
    try:
        # ๊ธฐ๋ณธ ํŒŒ๋ผ๋ฏธํ„ฐ ํ…œํ”Œ๋ฆฟ
        params = {
            'sequence_length': 100,
            'helix_bias': 0.02,
            'strand_bias': 0.02,
            'loop_bias': 0.1,
            'hydrophobic_target_score': 0
        }
        
        # ๋ถ„์„ ๊ฒฐ๊ณผ์—์„œ ๊ตฌ์กฐ์  ์š”๊ตฌ์‚ฌํ•ญ ํŒŒ์•…
        if "๋ง‰ ํˆฌ๊ณผ" in analysis or "์†Œ์ˆ˜์„ฑ" in analysis:
            params['hydrophobic_target_score'] = -2
            params['helix_bias'] = 0.03
        elif "์ˆ˜์šฉ์„ฑ" in analysis or "๊ฐ€์šฉ์„ฑ" in analysis:
            params['hydrophobic_target_score'] = 2
            params['loop_bias'] = 0.15
            
        # ์œ ์‚ฌ ๊ตฌ์กฐ๋“ค์˜ ํŠน์„ฑ ๋ฐ˜์˜
        if similar_structures:
            avg_length = sum(len(s[1]['sequence']) for s in similar_structures) / len(similar_structures)
            params['sequence_length'] = int(avg_length)
            
            # ๊ตฌ์กฐ์  ํŠน์„ฑ ๋ถ„์„ ๋ฐ ๋ฐ˜์˜
            for _, structure in similar_structures:
                if 'secondary_structure' in structure:
                    helix_ratio = structure['secondary_structure'].count('H') / len(structure['secondary_structure'])
                    sheet_ratio = structure['secondary_structure'].count('E') / len(structure['secondary_structure'])
                    params['helix_bias'] = max(0.01, min(0.05, helix_ratio))
                    params['strand_bias'] = max(0.01, min(0.05, sheet_ratio))
        
        return params
    except Exception as e:
        print(f"ํŒŒ๋ผ๋ฏธํ„ฐ ์ถ”์ถœ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
        return None

def process_chat(message, history):
    try:
        if any(keyword in message.lower() for keyword in ['protein', 'generate', '๋‹จ๋ฐฑ์งˆ', '์ƒ์„ฑ', '์น˜๋ฃŒ']):
            # 1. LLM์„ ์‚ฌ์šฉํ•œ ํ”„๋กฌํ”„ํŠธ ๋ถ„์„
            analysis = analyze_prompt(message)
            if not analysis:
                return history + [
                    {"role": "user", "content": message},
                    {"role": "assistant", "content": "์š”์ฒญ ๋ถ„์„์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."}
                ]
            
            # 2. ์œ ์‚ฌ ๊ตฌ์กฐ ๊ฒ€์ƒ‰
            similar_structures = search_protein_data(analysis, ds)
            if not similar_structures:
                return history + [
                    {"role": "user", "content": message},
                    {"role": "assistant", "content": "์ ํ•ฉํ•œ ์ฐธ์กฐ ๊ตฌ์กฐ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."}
                ]
            
            # 3. ์ƒ์„ฑ ํŒŒ๋ผ๋ฏธํ„ฐ ๊ฒฐ์ •
            params = extract_parameters(analysis, similar_structures)
            if not params:
                return history + [
                    {"role": "user", "content": message},
                    {"role": "assistant", "content": "ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ •์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."}
                ]
            
            # 4. ๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ
            try:
                protein_result = protein_diffusion_model(
                    sequence=None,
                    seq_len=params['sequence_length'],
                    helix_bias=params['helix_bias'],
                    strand_bias=params['strand_bias'],
                    loop_bias=params['loop_bias'],
                    secondary_structure=None,
                    aa_bias=None,
                    aa_bias_potential=None,
                    num_steps="25",
                    noise="normal",
                    hydrophobic_target_score=str(params['hydrophobic_target_score']),
                    hydrophobic_potential="2",
                    contigs=None,
                    pssm=None,
                    seq_mask=None,
                    str_mask=None,
                    rewrite_pdb=None
                )
                
                output_seq, output_pdb, structure_view, plddt_plot = next(protein_result)
                
                # 5. ๊ฒฐ๊ณผ ์„ค๋ช… ์ƒ์„ฑ
                explanation = f"""
                ์š”์ฒญํ•˜์‹  ๊ธฐ๋Šฅ์— ๋งž๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ–ˆ์Šต๋‹ˆ๋‹ค:
                
                ๋ถ„์„๋œ ์š”๊ตฌ์‚ฌํ•ญ:
                {analysis}
                
                ์„ค๊ณ„๋œ ๊ตฌ์กฐ์  ํŠน์ง•:
                - ๊ธธ์ด: {params['sequence_length']} ์•„๋ฏธ๋…ธ์‚ฐ
                - ์•ŒํŒŒ ํ—ฌ๋ฆญ์Šค ๋น„์œจ: {params['helix_bias']*100:.1f}%
                - ๋ฒ ํƒ€ ์‹œํŠธ ๋น„์œจ: {params['strand_bias']*100:.1f}%
                - ๋ฃจํ”„ ๊ตฌ์กฐ ๋น„์œจ: {params['loop_bias']*100:.1f}%
                - ์†Œ์ˆ˜์„ฑ ์ ์ˆ˜: {params['hydrophobic_target_score']}
                
                ์ฐธ์กฐ๋œ ์œ ์‚ฌ ๊ตฌ์กฐ: {len(similar_structures)}๊ฐœ
                
                ์ƒ์„ฑ๋œ ๋‹จ๋ฐฑ์งˆ์˜ 3D ๊ตฌ์กฐ์™€ ์‹œํ€€์Šค๋ฅผ ํ™•์ธํ•˜์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
                """
                
                # 6. ๊ฒฐ๊ณผ ์ €์žฅ
                global current_protein_result
                current_protein_result = {
                    'sequence': output_seq,
                    'pdb': output_pdb,
                    'structure_view': structure_view,
                    'plddt_plot': plddt_plot,
                    'params': params
                }
                
                return history + [
                    {"role": "user", "content": message},
                    {"role": "assistant", "content": explanation}
                ]
            
            except Exception as e:
                return history + [
                    {"role": "user", "content": message},
                    {"role": "assistant", "content": f"๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"}
                ]
        else:
            return history + [
                {"role": "user", "content": message},
                {"role": "assistant", "content": "๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ ๊ด€๋ จ ํ‚ค์›Œ๋“œ๋ฅผ ํฌํ•จํ•ด์ฃผ์„ธ์š”."}
            ]
    except Exception as e:
        return history + [
            {"role": "user", "content": message},
            {"role": "assistant", "content": f"์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"}
        ]


def generate_protein(params):
    # ๊ธฐ์กด protein_diffusion_model ํ•จ์ˆ˜ ํ˜ธ์ถœ
    result = protein_diffusion_model(
        sequence=None,
        seq_len=params['sequence_length'],
        helix_bias=params['helix_bias'],
        strand_bias=params['strand_bias'],
        loop_bias=params['loop_bias'],
        secondary_structure=None,
        aa_bias=None,
        aa_bias_potential=None,
        num_steps="25",
        noise="normal",
        hydrophobic_target_score=str(params['hydrophobic_target_score']),
        hydrophobic_potential="2",
        contigs=None,
        pssm=None,
        seq_mask=None,
        str_mask=None,
        rewrite_pdb=None
    )
    return result

def generate_explanation(result, params):
    explanation = f"""
    ์ƒ์„ฑ๋œ ๋‹จ๋ฐฑ์งˆ ๋ถ„์„:
    - ๊ธธ์ด: {params['sequence_length']} ์•„๋ฏธ๋…ธ์‚ฐ
    - ๊ตฌ์กฐ์  ํŠน์ง•:
        * ์•ŒํŒŒ ๋‚˜์„  ๋น„์œจ: {params['helix_bias']*100}%
        * ๋ฒ ํƒ€ ์‹œํŠธ ๋น„์œจ: {params['strand_bias']*100}%
        * ๋ฃจํ”„ ๊ตฌ์กฐ ๋น„์œจ: {params['loop_bias']*100}%
    - ํŠน์ˆ˜ ๊ธฐ๋Šฅ: {result.get('special_features', '์—†์Œ')}
    """
    return explanation

# ์ฒดํฌํฌ์ธํŠธ ํŒŒ์ผ ๊ฒฝ๋กœ๋ฅผ ์ ˆ๋Œ€ ๊ฒฝ๋กœ๋กœ ์ˆ˜์ •
def protein_diffusion_model(sequence, seq_len, helix_bias, strand_bias, loop_bias, 
                    secondary_structure, aa_bias, aa_bias_potential, 
                    num_steps, noise, hydrophobic_target_score, hydrophobic_potential,
                    contigs, pssm, seq_mask, str_mask, rewrite_pdb):

    
    dssp_checkpoint = './SEQDIFF_230205_dssp_hotspots_25mask_EQtasks_mod30.pt'
    og_checkpoint = './SEQDIFF_221219_equalTASKS_nostrSELFCOND_mod30.pt'

    
    # ์ฒดํฌํฌ์ธํŠธ ํŒŒ์ผ ์กด์žฌ ํ™•์ธ
    if not os.path.exists(dssp_checkpoint):
        raise FileNotFoundError(f"DSSP checkpoint file not found at: {dssp_checkpoint}")
    if not os.path.exists(og_checkpoint):
        raise FileNotFoundError(f"OG checkpoint file not found at: {og_checkpoint}")
    
    model_args = copy.deepcopy(args)


    # make sampler
    S = HuggingFace_sampler(args=model_args)

    # get random prefix 
    S.out_prefix = './tmp/'+secrets.token_hex(nbytes=10).upper()

    # set args
    S.args['checkpoint'] = None
    S.args['dump_trb'] = False
    S.args['dump_args'] = True
    S.args['save_best_plddt'] = True
    S.args['T'] = 25
    S.args['strand_bias'] = 0.0
    S.args['loop_bias'] = 0.0
    S.args['helix_bias'] = 0.0
    S.args['potentials'] = None
    S.args['potential_scale'] = None
    S.args['aa_composition'] = None


    # get sequence if entered and make sure all chars are valid
    alt_aa_dict = {'B':['D','N'],'J':['I','L'],'U':['C'],'Z':['E','Q'],'O':['K']}
    if sequence not in ['',None]:
        L = len(sequence)
        aa_seq = []
        for aa in sequence.upper():
            if aa in alt_aa_dict.keys():
                aa_seq.append(np.random.choice(alt_aa_dict[aa]))
            else:
                aa_seq.append(aa)

        S.args['sequence'] = aa_seq
    elif contigs not in ['',None]:
        S.args['contigs'] = [contigs]
    else:
        S.args['contigs'] = [f'{seq_len}']
        L = int(seq_len)
    
    print('DEBUG: ',rewrite_pdb)
    if rewrite_pdb not in ['',None]:
        S.args['pdb'] = rewrite_pdb.name

    if seq_mask not in ['',None]:
        S.args['inpaint_seq'] = [seq_mask]
    if str_mask not in ['',None]:
        S.args['inpaint_str'] = [str_mask]

    if secondary_structure in ['',None]:
        secondary_structure = None
    else:
        secondary_structure = ''.join(['E' if x == 'S' else x for x in secondary_structure])
        if L < len(secondary_structure):
            secondary_structure = secondary_structure[:len(sequence)]
        elif L == len(secondary_structure):
            pass
        else:
            dseq = L - len(secondary_structure)
            secondary_structure += secondary_structure[-1]*dseq
    

    # potentials
    potential_list = []
    potential_bias_list = []

    if aa_bias not in ['',None]:
        potential_list.append('aa_bias')
        S.args['aa_composition'] = aa_bias
        if aa_bias_potential in ['',None]:
            aa_bias_potential = 3
        potential_bias_list.append(str(aa_bias_potential))
    '''
    if target_charge not in ['',None]:
        potential_list.append('charge')
        if charge_potential in ['',None]:
            charge_potential = 1
        potential_bias_list.append(str(charge_potential))
        S.args['target_charge'] = float(target_charge)
        if target_ph in ['',None]:
            target_ph = 7.4
        S.args['target_pH'] = float(target_ph)
    '''
    
    if hydrophobic_target_score not in ['',None]:
        potential_list.append('hydrophobic')
        S.args['hydrophobic_score'] = float(hydrophobic_target_score)
        if hydrophobic_potential in ['',None]:
            hydrophobic_potential = 3
        potential_bias_list.append(str(hydrophobic_potential))
    
    if pssm not in ['',None]:
        potential_list.append('PSSM')
        potential_bias_list.append('5')
        S.args['PSSM'] = pssm.name
        

    if len(potential_list) > 0:
        S.args['potentials'] = ','.join(potential_list)
        S.args['potential_scale'] = ','.join(potential_bias_list)


    # normalise secondary_structure bias from range 0-0.3
    S.args['secondary_structure'] = secondary_structure
    S.args['helix_bias'] = helix_bias
    S.args['strand_bias'] = strand_bias
    S.args['loop_bias'] = loop_bias
    
    # set T
    if num_steps in ['',None]:
        S.args['T'] = 20
    else:
        S.args['T'] = int(num_steps)

    # noise
    if 'normal' in noise:
        S.args['sample_distribution'] = noise
        S.args['sample_distribution_gmm_means'] = [0]
        S.args['sample_distribution_gmm_variances'] = [1]
    elif 'gmm2' in noise:
        S.args['sample_distribution'] = noise
        S.args['sample_distribution_gmm_means'] = [-1,1]
        S.args['sample_distribution_gmm_variances'] = [1,1]
    elif 'gmm3' in noise:
        S.args['sample_distribution'] = noise
        S.args['sample_distribution_gmm_means'] = [-1,0,1]
        S.args['sample_distribution_gmm_variances'] = [1,1,1]



    if secondary_structure not in ['',None] or helix_bias+strand_bias+loop_bias > 0:
        S.args['checkpoint'] = dssp_checkpoint
        S.args['d_t1d'] = 29
        print('using dssp checkpoint')
    else:
        S.args['checkpoint'] = og_checkpoint
        S.args['d_t1d'] = 24
        print('using og checkpoint')
    

    for k,v in S.args.items():
        print(f"{k} --> {v}")
    
    # init S
    S.model_init()
    S.diffuser_init()
    S.setup()

    # sampling loop
    plddt_data = []
    for j in range(S.max_t):
        print(f'on step {j}')
        output_seq, output_pdb, plddt = S.take_step_get_outputs(j)
        plddt_data.append(plddt)
        yield output_seq, output_pdb, display_pdb(output_pdb), get_plddt_plot(plddt_data, S.max_t)
    
    output_seq, output_pdb, plddt = S.get_outputs()
 
    return output_seq, output_pdb, display_pdb(output_pdb), get_plddt_plot(plddt_data, S.max_t)

def get_plddt_plot(plddt_data, max_t):
    fig, ax = plt.subplots(figsize=(15,6))
    x = list(range(1, len(plddt_data) + 1))
    ax.plot(x, plddt_data, color='#661dbf', linewidth=3, marker='o')
    ax.set_xticks(range(1, max_t + 1))
    ax.set_yticks([i/10 for i in range(11)])  # 0๋ถ€ํ„ฐ 1๊นŒ์ง€
    ax.set_ylim([0, 1])
    ax.set_ylabel('model confidence (plddt)')
    ax.set_xlabel('diffusion steps (t)')
    plt.close()  # ๋ฉ”๋ชจ๋ฆฌ ๊ด€๋ฆฌ๋ฅผ ์œ„ํ•ด ๋‹ซ๊ธฐ
    return fig


def display_pdb(path_to_pdb):
    '''
        #function to display pdb in py3dmol
    '''
    pdb = open(path_to_pdb, "r").read()
    
    view = py3Dmol.view(width=500, height=500)
    view.addModel(pdb, "pdb")
    view.setStyle({'model': -1}, {"cartoon": {'colorscheme':{'prop':'b','gradient':'roygb','min':0,'max':1}}})#'linear', 'min': 0, 'max': 1, 'colors': ["#ff9ef0","#a903fc",]}}}) 
    view.zoomTo()
    output = view._make_html().replace("'", '"')
    print(view._make_html())
    x = f"""<!DOCTYPE html><html></center> {output} </center></html>"""  # do not use ' in this input
    
    return f"""<iframe height="500px" width="100%"  name="result" allow="midi; geolocation; microphone; camera;
                            display-capture; encrypted-media;" sandbox="allow-modals allow-forms
                            allow-scripts allow-same-origin allow-popups
                            allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
                            allowpaymentrequest="" frameborder="0" srcdoc='{x}'></iframe>"""

'''
    return f"""<iframe  style="width: 100%; height:700px" name="result" allow="midi; geolocation; microphone; camera; 
                            display-capture; encrypted-media;" sandbox="allow-modals allow-forms 
                            allow-scripts allow-same-origin allow-popups 
                            allow-top-navigation-by-user-activation allow-downloads" allowfullscreen="" 
                            allowpaymentrequest="" frameborder="0" srcdoc='{x}'></iframe>"""
'''

def get_motif_preview(pdb_id, contigs):
    try:
        input_pdb = fetch_pdb(pdb_id=pdb_id.lower() if pdb_id else None)
        if input_pdb is None:
            return gr.HTML("PDB ID๋ฅผ ์ž…๋ ฅํ•ด์ฃผ์„ธ์š”"), None
        
        parse = parse_pdb(input_pdb)
        output_name = input_pdb

        pdb = open(output_name, "r").read()
        view = py3Dmol.view(width=500, height=500)
        view.addModel(pdb, "pdb")

        if contigs in ['',0]:
            contigs = ['0']
        else:
            contigs = [contigs]

        print('DEBUG: ',contigs)
        
        pdb_map = get_mappings(ContigMap(parse,contigs))
        print('DEBUG: ',pdb_map)
        print('DEBUG: ',pdb_map['con_ref_idx0'])
        roi = [x[1]-1 for x in pdb_map['con_ref_pdb_idx']]

        colormap = {0:'#D3D3D3', 1:'#F74CFF'}
        colors = {i+1: colormap[1] if i in roi else colormap[0] for i in range(parse['xyz'].shape[0])}
        view.setStyle({"cartoon": {"colorscheme": {"prop": "resi", "map": colors}}})
        view.zoomTo()
        output = view._make_html().replace("'", '"')
        print(view._make_html())
        x = f"""<!DOCTYPE html><html></center> {output} </center></html>"""  # do not use ' in this input
        
        return f"""<iframe height="500px" width="100%"  name="result" allow="midi; geolocation; microphone; camera;
                                display-capture; encrypted-media;" sandbox="allow-modals allow-forms
                                allow-scripts allow-same-origin allow-popups
                                allow-top-navigation-by-user-activation allow-downloads" allowfullscreen=""
                                allowpaymentrequest="" frameborder="0" srcdoc='{x}'></iframe>""", output_name

    except Exception as e:
        return gr.HTML(f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"), None

def fetch_pdb(pdb_id=None):
    if pdb_id is None or pdb_id == "":
        return None
    else:
        os.system(f"wget -qnc https://files.rcsb.org/view/{pdb_id}.pdb")
        return f"{pdb_id}.pdb"

# MSA AND PSSM GUIDANCE
def save_pssm(file_upload):
    filename = file_upload.name
    orig_name = file_upload.orig_name
    if filename.split('.')[-1] in ['fasta', 'a3m']:
        return msa_to_pssm(file_upload)
    return filename

def msa_to_pssm(msa_file):
    # Define the lookup table for converting amino acids to indices
    aa_to_index = {'A': 0, 'R': 1, 'N': 2, 'D': 3, 'C': 4, 'Q': 5, 'E': 6, 'G': 7, 'H': 8, 'I': 9, 'L': 10,
                'K': 11, 'M': 12, 'F': 13, 'P': 14, 'S': 15, 'T': 16, 'W': 17, 'Y': 18, 'V': 19, 'X': 20, '-': 21}
    # Open the FASTA file and read the sequences
    records = list(SeqIO.parse(msa_file.name, "fasta"))

    assert len(records) >= 1, "MSA must contain more than one protein sequecne."

    first_seq = str(records[0].seq)
    aligned_seqs = [first_seq]
    # print(aligned_seqs)
    # Perform sequence alignment using the Needleman-Wunsch algorithm
    aligner = Align.PairwiseAligner()
    aligner.open_gap_score = -0.7
    aligner.extend_gap_score = -0.3
    for record in records[1:]:
        alignment = aligner.align(first_seq, str(record.seq))[0]
        alignment = alignment.format().split("\n")
        al1 = alignment[0]
        al2 = alignment[2]
        al1_fin = ""
        al2_fin = ""
        percent_gap = al2.count('-')/ len(al2)
        if percent_gap > 0.4:
            continue
        for i in range(len(al1)):
            if al1[i] != '-':
                al1_fin += al1[i]
                al2_fin += al2[i]
        aligned_seqs.append(str(al2_fin))
    # Get the length of the aligned sequences
    aligned_seq_length = len(first_seq)
    # Initialize the position scoring matrix
    matrix = np.zeros((22, aligned_seq_length))
    # Iterate through the aligned sequences and count the amino acids at each position
    for seq in aligned_seqs:
        #print(seq)
        for i in range(aligned_seq_length):
            if i == len(seq):
                break
            amino_acid = seq[i]
            if amino_acid.upper() not in aa_to_index.keys():
                continue
            else:
                aa_index = aa_to_index[amino_acid.upper()]
            matrix[aa_index, i] += 1
    # Normalize the counts to get the frequency of each amino acid at each position
    matrix /= len(aligned_seqs)
    print(len(aligned_seqs))
    matrix[20:,]=0

    outdir = ".".join(msa_file.name.split('.')[:-1]) + ".csv"
    np.savetxt(outdir, matrix[:21,:].T, delimiter=",")
    return outdir

def get_pssm(fasta_msa, input_pssm):
    try:
        if input_pssm is not None:
            outdir = input_pssm.name
        elif fasta_msa is not None:
            outdir = save_pssm(fasta_msa)
        else:
            return gr.Plot(label="ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•ด์ฃผ์„ธ์š”"), None

        pssm = np.loadtxt(outdir, delimiter=",", dtype=float)
        fig, ax = plt.subplots(figsize=(15,6))
        plt.imshow(torch.permute(torch.tensor(pssm),(1,0)))
        return fig, outdir
    except Exception as e:
        return gr.Plot(label=f"์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"), None

# ํžˆ์–ด๋กœ ๋Šฅ๋ ฅ์น˜ ๊ณ„์‚ฐ ํ•จ์ˆ˜ ์ถ”๊ฐ€
def calculate_hero_stats(helix_bias, strand_bias, loop_bias, hydrophobic_score):
    stats = {
        'strength': strand_bias * 20,  # ๋ฒ ํƒ€์‹œํŠธ ๊ตฌ์กฐ ๊ธฐ๋ฐ˜
        'flexibility': helix_bias * 20, # ์•ŒํŒŒํ—ฌ๋ฆญ์Šค ๊ตฌ์กฐ ๊ธฐ๋ฐ˜
        'speed': loop_bias * 5,        # ๋ฃจํ”„ ๊ตฌ์กฐ ๊ธฐ๋ฐ˜
        'defense': abs(hydrophobic_score) if hydrophobic_score else 0
    }
    return stats

def toggle_seq_input(choice):
    if choice == "์ž๋™ ์„ค๊ณ„":
        return gr.update(visible=True), gr.update(visible=False)
    else:  # "์ง์ ‘ ์ž…๋ ฅ"
        return gr.update(visible=False), gr.update(visible=True)

def toggle_secondary_structure(choice):
    if choice == "์Šฌ๋ผ์ด๋”๋กœ ์„ค์ •":
        return (
            gr.update(visible=True),  # helix_bias
            gr.update(visible=True),  # strand_bias
            gr.update(visible=True),  # loop_bias
            gr.update(visible=False)  # secondary_structure
        )
    else:  # "์ง์ ‘ ์ž…๋ ฅ"
        return (
            gr.update(visible=False),  # helix_bias
            gr.update(visible=False),  # strand_bias
            gr.update(visible=False),  # loop_bias
            gr.update(visible=True)   # secondary_structure
        )


def create_radar_chart(stats):
    # ๋ ˆ์ด๋” ์ฐจํŠธ ์ƒ์„ฑ ๋กœ์ง
    categories = list(stats.keys())
    values = list(stats.values())
    
    fig = go.Figure(data=go.Scatterpolar(
        r=values,
        theta=categories,
        fill='toself'
    ))
    
    fig.update_layout(
        polar=dict(
            radialaxis=dict(
                visible=True,
                range=[0, 1]
            )),
        showlegend=False
    )
    
    return fig

def generate_hero_description(name, stats, abilities):
    # ํžˆ์–ด๋กœ ์„ค๋ช… ์ƒ์„ฑ ๋กœ์ง
    description = f"""
    ํžˆ์–ด๋กœ ์ด๋ฆ„: {name}
    
    ์ฃผ์š” ๋Šฅ๋ ฅ:
    - ๊ทผ๋ ฅ: {'โ˜…' * int(stats['strength'] * 5)}
    - ์œ ์—ฐ์„ฑ: {'โ˜…' * int(stats['flexibility'] * 5)}
    - ์Šคํ”ผ๋“œ: {'โ˜…' * int(stats['speed'] * 5)}
    - ๋ฐฉ์–ด๋ ฅ: {'โ˜…' * int(stats['defense'] * 5)}
    
    ํŠน์ˆ˜ ๋Šฅ๋ ฅ: {', '.join(abilities)}
    """
    return description

def combined_generation(name, strength, flexibility, speed, defense, size, abilities,
                       sequence, seq_len, helix_bias, strand_bias, loop_bias, 
                       secondary_structure, aa_bias, aa_bias_potential, 
                       num_steps, noise, hydrophobic_target_score, hydrophobic_potential,
                       contigs, pssm, seq_mask, str_mask, rewrite_pdb):
    try:
        # protein_diffusion_model ์‹คํ–‰
        generator = protein_diffusion_model(
            sequence=None,
            seq_len=size,  # ํžˆ์–ด๋กœ ํฌ๊ธฐ๋ฅผ seq_len์œผ๋กœ ์‚ฌ์šฉ
            helix_bias=flexibility,  # ํžˆ์–ด๋กœ ์œ ์—ฐ์„ฑ์„ helix_bias๋กœ ์‚ฌ์šฉ
            strand_bias=strength,    # ํžˆ์–ด๋กœ ๊ฐ•๋„๋ฅผ strand_bias๋กœ ์‚ฌ์šฉ
            loop_bias=speed,         # ํžˆ์–ด๋กœ ์Šคํ”ผ๋“œ๋ฅผ loop_bias๋กœ ์‚ฌ์šฉ
            secondary_structure=None,
            aa_bias=None,
            aa_bias_potential=None,
            num_steps="25",
            noise="normal",
            hydrophobic_target_score=str(-defense),  # ํžˆ์–ด๋กœ ๋ฐฉ์–ด๋ ฅ์„ hydrophobic score๋กœ ์‚ฌ์šฉ
            hydrophobic_potential="2",
            contigs=None,
            pssm=None,
            seq_mask=None,
            str_mask=None,
            rewrite_pdb=None
        )
        
        # ๋งˆ์ง€๋ง‰ ๊ฒฐ๊ณผ ๊ฐ€์ ธ์˜ค๊ธฐ
        final_result = None
        for result in generator:
            final_result = result
            
        if final_result is None:
            raise Exception("์ƒ์„ฑ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค")
            
        output_seq, output_pdb, structure_view, plddt_plot = final_result
        
        # ํžˆ์–ด๋กœ ๋Šฅ๋ ฅ์น˜ ๊ณ„์‚ฐ
        stats = calculate_hero_stats(flexibility, strength, speed, defense)
        
        # ๋ชจ๋“  ๊ฒฐ๊ณผ ๋ฐ˜ํ™˜
        return (
            create_radar_chart(stats),  # ๋Šฅ๋ ฅ์น˜ ์ฐจํŠธ
            generate_hero_description(name, stats, abilities),  # ํžˆ์–ด๋กœ ์„ค๋ช…
            output_seq,  # ๋‹จ๋ฐฑ์งˆ ์„œ์—ด
            output_pdb,  # PDB ํŒŒ์ผ
            structure_view,  # 3D ๊ตฌ์กฐ
            plddt_plot  # ์‹ ๋ขฐ๋„ ์ฐจํŠธ
        )
    except Exception as e:
        print(f"Error in combined_generation: {str(e)}")
        return (
            None,
            f"์—๋Ÿฌ: {str(e)}",
            None,
            None,
            gr.HTML("์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค"),
            None
        )


def extract_parameters_from_chat(chat_response):
    """์ฑ—๋ด‡ ์‘๋‹ต์—์„œ ํŒŒ๋ผ๋ฏธํ„ฐ ์ถ”์ถœ"""
    try:
        params = {
            'sequence_length': 100,
            'helix_bias': 0.02,
            'strand_bias': 0.02,
            'loop_bias': 0.1,
            'hydrophobic_target_score': 0
        }
        
        # ์‘๋‹ต ํ…์ŠคํŠธ์—์„œ ๊ฐ’ ์ถ”์ถœ
        if "๊ธธ์ด:" in chat_response:
            length_match = re.search(r'๊ธธ์ด: (\d+)', chat_response)
            if length_match:
                params['sequence_length'] = int(length_match.group(1))
                
        if "์•ŒํŒŒ ํ—ฌ๋ฆญ์Šค ๋น„์œจ:" in chat_response:
            helix_match = re.search(r'์•ŒํŒŒ ํ—ฌ๋ฆญ์Šค ๋น„์œจ: ([\d.]+)', chat_response)
            if helix_match:
                params['helix_bias'] = float(helix_match.group(1)) / 100
                
        if "๋ฒ ํƒ€ ์‹œํŠธ ๋น„์œจ:" in chat_response:
            strand_match = re.search(r'๋ฒ ํƒ€ ์‹œํŠธ ๋น„์œจ: ([\d.]+)', chat_response)
            if strand_match:
                params['strand_bias'] = float(strand_match.group(1)) / 100
                
        if "๋ฃจํ”„ ๊ตฌ์กฐ ๋น„์œจ:" in chat_response:
            loop_match = re.search(r'๋ฃจํ”„ ๊ตฌ์กฐ ๋น„์œจ: ([\d.]+)', chat_response)
            if loop_match:
                params['loop_bias'] = float(loop_match.group(1)) / 100
                
        if "์†Œ์ˆ˜์„ฑ ์ ์ˆ˜:" in chat_response:
            hydro_match = re.search(r'์†Œ์ˆ˜์„ฑ ์ ์ˆ˜: ([-\d.]+)', chat_response)
            if hydro_match:
                params['hydrophobic_target_score'] = float(hydro_match.group(1))
        
        return params
    except Exception as e:
        print(f"ํŒŒ๋ผ๋ฏธํ„ฐ ์ถ”์ถœ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
        return None

def update_protein_display(chat_response):
    if "์ƒ์„ฑ๋œ ๋‹จ๋ฐฑ์งˆ ๋ถ„์„" in chat_response:
        params = extract_parameters_from_chat(chat_response)
        if params:
            result = generate_protein(params)
            stats = calculate_hero_stats(
                helix_bias=params['helix_bias'],
                strand_bias=params['strand_bias'],
                loop_bias=params['loop_bias'],
                hydrophobic_score=params['hydrophobic_target_score']
            )
            return {
                hero_stats: create_radar_chart(stats),
                hero_description: chat_response,
                output_seq: result[0],
                output_pdb: result[1],
                output_viewer: display_pdb(result[1]),
                plddt_plot: result[3]
            }
    return None

def analyze_active_sites(sequence):
    """ํ™œ์„ฑ ๋ถ€์œ„ ๋ถ„์„"""
    return "๋ถ„์„ ์ค‘..."  # ์ž„์‹œ ๊ตฌํ˜„

def predict_interactions(params):
    """์ƒํ˜ธ์ž‘์šฉ ์˜ˆ์ธก"""
    return "์˜ˆ์ธก ์ค‘..."  # ์ž„์‹œ ๊ตฌํ˜„

def evaluate_stability(plddt_data):
    """์•ˆ์ •์„ฑ ํ‰๊ฐ€"""
    if not plddt_data:
        return "ํ‰๊ฐ€ ๋ถˆ๊ฐ€"
    avg_score = np.mean(plddt_data)
    if avg_score > 0.8:
        return "๋งค์šฐ ์•ˆ์ •์ "
    elif avg_score > 0.6:
        return "์•ˆ์ •์ "
    else:
        return "๋ณดํ†ต"

def process_chat_and_generate(message, history):
    try:
        # 1. ์ดˆ๊ธฐ ์‘๋‹ต ์ƒ์„ฑ (์ด์ „ ๋Œ€ํ™” ๊ธฐ๋ก ์œ ์ง€)
        current_history = history + [
            {"role": "user", "content": message},
            {"role": "assistant", "content": "๋‹จ๋ฐฑ์งˆ ์„ค๊ณ„๋ฅผ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. ์ž ์‹œ๋งŒ ๊ธฐ๋‹ค๋ ค์ฃผ์„ธ์š”..."}
        ]
        yield (current_history, None, None, None, None, None, None)

        # 2. ํ”„๋กฌํ”„ํŠธ ๋ถ„์„
        analysis = analyze_prompt(message)
        if not analysis:
            return history + [
                {"role": "user", "content": message},
                {"role": "assistant", "content": "์š”์ฒญ ๋ถ„์„์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."}
            ], None, None, None, None, None, None

        similar_structures = search_protein_data(analysis, ds)
        if not similar_structures:
            return history + [
                {"role": "user", "content": message},
                {"role": "assistant", "content": "์ ํ•ฉํ•œ ์ฐธ์กฐ ๊ตฌ์กฐ๋ฅผ ์ฐพ์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค."}
            ], None, None, None, None, None, None

        params = extract_parameters(analysis, similar_structures)
        if not params:
            return history + [
                {"role": "user", "content": message},
                {"role": "assistant", "content": "ํŒŒ๋ผ๋ฏธํ„ฐ ์„ค์ •์— ์‹คํŒจํ–ˆ์Šต๋‹ˆ๋‹ค."}
            ], None, None, None, None, None, None

        # 3. ๋ถ„์„ ๊ฒฐ๊ณผ ์ถ”๊ฐ€ (์ด์ „ ๋ฉ”์‹œ์ง€ ์œ ์ง€)
        current_history = current_history[:-1] + [
            {"role": "assistant", "content": f"""
            ๋ถ„์„ ๊ฒฐ๊ณผ:
            {analysis}
            
            ๋‹จ๋ฐฑ์งˆ ๊ตฌ์กฐ ์ƒ์„ฑ์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค...
            """}
        ]
        yield (current_history, None, None, None, None, None, None)

        # 4. ๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ
        try:
            generator = protein_diffusion_model(
                sequence=None,
                seq_len=params['sequence_length'],
                helix_bias=params['helix_bias'],
                strand_bias=params['strand_bias'],
                loop_bias=params['loop_bias'],
                secondary_structure=None,
                aa_bias=None,
                aa_bias_potential=None,
                num_steps="25",
                noise="normal",
                hydrophobic_target_score=str(params['hydrophobic_target_score']),
                hydrophobic_potential="2",
                contigs=None,
                pssm=None,
                seq_mask=None,
                str_mask=None,
                rewrite_pdb=None
            )

            # 5. ์ƒ์„ฑ ๊ณผ์ • ์ถ”์  (์ด์ „ ๋ฉ”์‹œ์ง€๋“ค ์œ ์ง€)
            step = 0
            final_result = None
            for result in generator:
                step += 1
                final_result = result
                progress_msg = f"๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ ์ค‘... {step}/25 ๋‹จ๊ณ„ ์™„๋ฃŒ"
                current_history = current_history[:-1] + [
                    {"role": "assistant", "content": progress_msg}
                ]
                yield (
                    current_history,
                    create_radar_chart(calculate_hero_stats(
                        params['helix_bias'],
                        params['strand_bias'],
                        params['loop_bias'],
                        float(params['hydrophobic_target_score'])
                    )),
                    progress_msg,
                    result[0],  # output_seq
                    result[1],  # output_pdb
                    result[2],  # structure_view
                    result[3]   # plddt_plot
                )

            if final_result is None:
                raise Exception("์ƒ์„ฑ ๊ฒฐ๊ณผ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค")

            # 6. ์ตœ์ข… ๊ฒฐ๊ณผ ๋ฐ ์„ค๋ช… ์ถ”๊ฐ€
            output_seq, output_pdb, structure_view, plddt_plot = final_result
            
            final_explanation = f"""
            ๋‹จ๋ฐฑ์งˆ ์„ค๊ณ„๊ฐ€ ์™„๋ฃŒ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

            [๋ถ„์„ ๊ฒฐ๊ณผ]
            {analysis}

            [๊ตฌ์กฐ์  ํŠน์ง•]
            - ๊ธธ์ด: {params['sequence_length']} ์•„๋ฏธ๋…ธ์‚ฐ
            - ์•ŒํŒŒ ํ—ฌ๋ฆญ์Šค ๋น„์œจ: {params['helix_bias']*100:.1f}%
            - ๋ฒ ํƒ€ ์‹œํŠธ ๋น„์œจ: {params['strand_bias']*100:.1f}%
            - ๋ฃจํ”„ ๊ตฌ์กฐ ๋น„์œจ: {params['loop_bias']*100:.1f}%
            - ์†Œ์ˆ˜์„ฑ ์ ์ˆ˜: {params['hydrophobic_target_score']}

            [์ƒ์„ฑ ๊ณผ์ •]
            - ์ด {step}๋‹จ๊ณ„์˜ ์ตœ์ ํ™” ์™„๋ฃŒ
            - ์ตœ์ข… ์•ˆ์ •์„ฑ ์ ์ˆ˜: {np.mean(plddt_data) if plddt_data else 0:.2f}
            - ์ฐธ์กฐ๋œ ์œ ์‚ฌ ๊ตฌ์กฐ: {len(similar_structures)}๊ฐœ

            3D ๊ตฌ์กฐ์™€ ์ƒ์„ธ ๋ถ„์„ ๊ฒฐ๊ณผ๋ฅผ ํ™•์ธํ•˜์‹ค ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
            """

            final_history = current_history + [
                {"role": "assistant", "content": final_explanation}
            ]

            stats = calculate_hero_stats(
                params['helix_bias'],
                params['strand_bias'],
                params['loop_bias'],
                float(params['hydrophobic_target_score'])
            )

            return (
                final_history,
                create_radar_chart(stats),
                final_explanation,
                output_seq,
                output_pdb,
                structure_view,
                plddt_plot
            )

        except Exception as e:
            error_msg = f"๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
            print(error_msg)
            traceback.print_exc()
            return (
                current_history + [
                    {"role": "assistant", "content": error_msg}
                ],
                None, None, None, None, None, None
            )

    except Exception as e:
        error_msg = f"์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
        print(f"Error in process_chat_and_generate: {str(e)}")
        traceback.print_exc()
        return (
            history + [
                {"role": "user", "content": message},
                {"role": "assistant", "content": error_msg}
            ],
            None, None, None, None, None, None
        )


# ์‹œ์ž‘ ๋ถ€๋ถ„์— ์ถ”๊ฐ€
def extract_keywords(analysis):
    """๋ถ„์„ ํ…์ŠคํŠธ์—์„œ ํ‚ค์›Œ๋“œ ์ถ”์ถœ"""
    try:
        keywords = []
        # ์ฃผ์š” ๊ธฐ๋Šฅ ํ‚ค์›Œ๋“œ
        if "์น˜๋ฃŒ" in analysis: keywords.extend(["therapeutic", "binding"])
        if "๊ฒฐํ•ฉ" in analysis: keywords.extend(["binding", "interaction"])
        if "์ด‰๋งค" in analysis: keywords.extend(["enzyme", "catalytic"])
        
        # ํ™˜๊ฒฝ ํ‚ค์›Œ๋“œ
        if "๋ง‰" in analysis: keywords.extend(["membrane", "transmembrane"])
        if "์ˆ˜์šฉ์„ฑ" in analysis: keywords.extend(["soluble", "hydrophilic"])
        if "์†Œ์ˆ˜์„ฑ" in analysis: keywords.extend(["hydrophobic"])
        
        # ๊ตฌ์กฐ ํ‚ค์›Œ๋“œ
        if "์•ŒํŒŒ" in analysis or "๋‚˜์„ " in analysis: keywords.append("helix")
        if "๋ฒ ํƒ€" in analysis or "์‹œํŠธ" in analysis: keywords.append("sheet")
        if "๋ฃจํ”„" in analysis: keywords.append("loop")
        
        return list(set(keywords))
    except Exception as e:
        print(f"ํ‚ค์›Œ๋“œ ์ถ”์ถœ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
        return []

def calculate_similarity(keywords, entry):
    """ํ‚ค์›Œ๋“œ์™€ ๋ฐ์ดํ„ฐ์…‹ ํ•ญ๋ชฉ ๊ฐ„์˜ ์œ ์‚ฌ๋„ ๊ณ„์‚ฐ"""
    try:
        score = 0
        if not isinstance(entry, dict):
            return 0
            
        # ์•ˆ์ „ํ•œ ์ ‘๊ทผ์„ ์œ„ํ•œ get ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ
        sequence = entry.get('sequence', '').lower()
        description = entry.get('description', '')
        
        for keyword in keywords:
            if keyword in description.lower():
                score += 2
            if keyword in sequence:
                score += 1
            if 'secondary_structure' in entry:
                sec_structure = entry['secondary_structure']
                if keyword in ['helix'] and 'H' in sec_structure:
                    score += 1
                if keyword in ['sheet'] and 'E' in sec_structure:
                    score += 1
                if keyword in ['loop'] and 'L' in sec_structure:
                    score += 1
        return score
    except Exception as e:
        print(f"์œ ์‚ฌ๋„ ๊ณ„์‚ฐ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
        return 0

# ์ „์—ญ ๋ณ€์ˆ˜ ์ •์˜
plddt_data = []
stats = {}  # ๋Šฅ๋ ฅ์น˜ ์ €์žฅ์šฉ
output_seq = None
output_pdb = None
structure_view = None
plddt_plot = None

# ์˜ˆ์ œ ํ”„๋กฌํ”„ํŠธ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜ ์ˆ˜์ •
def use_example(example):
    try:
        if example:
            return example
        return ""
    except Exception as e:
        print(f"์˜ˆ์ œ ์ฒ˜๋ฆฌ ์ค‘ ์˜ค๋ฅ˜: {str(e)}")
        return ""

# ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ์—์„œ ํ•„์š”ํ•œ ๋ณ€์ˆ˜๋“ค ์ •์˜
current_protein_result = None


def download_checkpoint_files():
    """ํ•„์š”ํ•œ ์ฒดํฌํฌ์ธํŠธ ํŒŒ์ผ ๋‹ค์šด๋กœ๋“œ"""
    try:
        import requests
        
        # ์ฒดํฌํฌ์ธํŠธ ํŒŒ์ผ URL (์‹ค์ œ URL๋กœ ๊ต์ฒด ํ•„์š”)
        dssp_url = "YOUR_DSSP_CHECKPOINT_URL"
        og_url = "YOUR_OG_CHECKPOINT_URL"
        
        # DSSP ์ฒดํฌํฌ์ธํŠธ ๋‹ค์šด๋กœ๋“œ
        if not os.path.exists(dssp_checkpoint):
            print("Downloading DSSP checkpoint...")
            response = requests.get(dssp_url)
            with open(dssp_checkpoint, 'wb') as f:
                f.write(response.content)
        
        # OG ์ฒดํฌํฌ์ธํŠธ ๋‹ค์šด๋กœ๋“œ
        if not os.path.exists(og_checkpoint):
            print("Downloading OG checkpoint...")
            response = requests.get(og_url)
            with open(og_checkpoint, 'wb') as f:
                f.write(response.content)
                
        print("Checkpoint files downloaded successfully")
    except Exception as e:
        print(f"Error downloading checkpoint files: {str(e)}")
        raise

# ์‹œ์ž‘ ์‹œ ์ฒดํฌํฌ์ธํŠธ ํŒŒ์ผ ํ™•์ธ ๋ฐ ๋‹ค์šด๋กœ๋“œ
try:
    download_checkpoint_files()
except Exception as e:
    print(f"Warning: Could not download checkpoint files: {str(e)}")



with gr.Blocks(theme='ParityError/Interstellar') as demo:
    # ์˜ˆ์ œ ํ”„๋กฌํ”„ํŠธ ๋ฆฌ์ŠคํŠธ ์ •์˜
    example_prompts = [
        "์•”์„ธํฌ๋งŒ ์„ ํƒ์ ์œผ๋กœ ๊ณต๊ฒฉํ•˜๋Š” ๋ฉด์—ญ ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "COVID-19 ์ŠคํŒŒ์ดํฌ ๋‹จ๋ฐฑ์งˆ์— ๊ฐ•ํ•˜๊ฒŒ ๊ฒฐํ•ฉํ•˜๋Š” ํ•ญ์ฒด ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
        "ํ˜ˆ๋‹น ์ˆ˜์ค€์„ ์‹ค์‹œ๊ฐ„์œผ๋กœ ๋ชจ๋‹ˆํ„ฐ๋งํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”",
        "์•Œ์ธ ํ•˜์ด๋จธ ๋ฒ ํƒ€ ์•„๋ฐ€๋กœ์ด๋“œ๋ฅผ ๋ถ„ํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ํšจ์†Œ ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "์•” ๋งˆ์ปค๋ฅผ ์ดˆ๊ณ ๊ฐ๋„๋กœ ๊ฒ€์ถœํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
        "ํ”Œ๋ผ์Šคํ‹ฑ์„ ๋ถ„ํ•ดํ•  ์ˆ˜ ์žˆ๋Š” ํšจ์†Œ ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "์ด์‚ฐํ™”ํƒ„์†Œ๋ฅผ ํšจ์œจ์ ์œผ๋กœ ํฌ์ง‘ํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”",
        "์‹ํ’ˆ์˜ ๋ณด์กด๊ธฐ๊ฐ„์„ ์—ฐ์žฅํ•˜๋Š” ํ•ญ๊ท  ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "์ˆ˜์†Œ ์ƒ์‚ฐ์„ ์ด‰์ง„ํ•˜๋Š” ํšจ์†Œ ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
        "ํ˜ˆ์ „์„ ํšจ๊ณผ์ ์œผ๋กœ ๋ถ„ํ•ดํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "์ธ์Š๋ฆฐ ์ €ํ•ญ์„ฑ์„ ๊ฐœ์„ ํ•˜๋Š” ์ƒˆ๋กœ์šด ํ˜ธ๋ฅด๋ชฌ ๋‹จ๋ฐฑ์งˆ์„ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”",
        "์‹๋ฌผ์˜ ๊ฐ€๋ญ„ ์ €ํ•ญ์„ฑ์„ ๋†’์ด๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "ํƒœ์–‘๊ด‘ ์—๋„ˆ์ง€๋ฅผ ํšจ์œจ์ ์œผ๋กœ ํฌ์ง‘ํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
        "ํ•ด์ˆ˜์—์„œ ์ค‘๊ธˆ์†์„ ์ œ๊ฑฐํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "์งˆ์†Œ ๊ณ ์ • ํšจ์œจ์„ ๋†’์ด๋Š” ํšจ์†Œ ๋‹จ๋ฐฑ์งˆ์„ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”",
        "์‹ ๊ฒฝ์ „๋‹ฌ๋ฌผ์งˆ์„ ๊ฐ์ง€ํ•˜๋Š” ๋‚˜๋…ธ๋ฐ”์ด์˜ค์„ผ์„œ๋ฅผ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "ํŠน์ • ๋…์„ฑ ๋ฌผ์งˆ์„ ๊ฐ์ง€ํ•˜๋Š” ๋ฐ”์ด์˜ค์„ผ์„œ ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
        "๋ฐฐํ„ฐ๋ฆฌ ์„ฑ๋Šฅ์„ ํ–ฅ์ƒ์‹œํ‚ค๋Š” ์ „๋„์„ฑ ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "๊ทนํ•œ์˜ ๊ณ ์˜จ์—์„œ๋„ ์•ˆ์ •ํ•œ ์ดˆ๋‚ด์—ด์„ฑ ๋‹จ๋ฐฑ์งˆ์„ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”",
        "์ƒ๋ถ„ํ•ด์„ฑ ํ”Œ๋ผ์Šคํ‹ฑ ์ƒ์‚ฐ์„ ์œ„ํ•œ ์ค‘ํ•ฉํšจ์†Œ๋ฅผ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "์‹๋ฌผ์˜ ๋ณ‘ํ•ด์ถฉ ์ €ํ•ญ์„ฑ์„ ๊ฐ•ํ™”ํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
        "๊ณผ์ผ์˜ ์ˆ™์„ฑ์„ ์กฐ์ ˆํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "๋Œ€๊ธฐ ์˜ค์—ผ๋ฌผ์งˆ์„ ์‹ค์‹œ๊ฐ„ ๊ฐ์ง€ํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”",
        "์„์œ  ์˜ค์—ผ์„ ๋ถ„ํ•ดํ•˜๋Š” ํ•ด์–‘ ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "๊ทน์ €์˜จ์—์„œ ํ™œ์„ฑ์„ ์œ ์ง€ํ•˜๋Š” ์ €์˜จ ์ ์‘ ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
        "๊ณ ์•• ํ™˜๊ฒฝ์—์„œ ์•ˆ์ •ํ•œ ์‹ฌํ•ด ์ ์‘ ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "๊ฐ•ํ•œ ์‚ฐ์„ฑ ํ™˜๊ฒฝ์—์„œ ์ž‘๋™ํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ๋งŒ๋“ค์–ด์ฃผ์„ธ์š”",
        "๋‚˜๋…ธ ๊ตฌ์กฐ์ฒด๋ฅผ ์ž๊ฐ€ ์กฐ๋ฆฝํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”",
        "๋ฐฉ์‚ฌ๋Šฅ ๋ฌผ์งˆ์„ ์•ˆ์ „ํ•˜๊ฒŒ ๋ถ„ํ•ดํ•˜๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
        "๋ฐฉ์‚ฌ์„ ์— ์ €ํ•ญ์„ฑ์ด ์žˆ๋Š” ์šฐ์ฃผ ํ™˜๊ฒฝ์šฉ ๋‹จ๋ฐฑ์งˆ์„ ์„ค๊ณ„ํ•ด์ฃผ์„ธ์š”"
    ]

    with gr.Row():
        with gr.Column(scale=1):
            # ์ฑ—๋ด‡ ์ธํ„ฐํŽ˜์ด์Šค
            gr.Markdown("# ๐Ÿค– ProteinGPT: AI ๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ๊ธฐ๊ธฐ")
            
            # ์˜ˆ์ œ ํ”„๋กฌํ”„ํŠธ ๋“œ๋กญ๋‹ค์šด๊ณผ ๋ฒ„ํŠผ์„ Row๋กœ ๋ฐฐ์น˜
            with gr.Row():
                example_dropdown = gr.Dropdown(
                    choices=example_prompts,
                    label="์˜ˆ์ œ ํ”„๋กฌํ”„ํŠธ ์„ ํƒ",
                    info="์›ํ•˜๋Š” ์˜ˆ์ œ๋ฅผ ์„ ํƒํ•˜์„ธ์š”",
                    scale=4
                )
                example_btn = gr.Button("๐Ÿ‘‰ ์˜ˆ์ œ ์‚ฌ์šฉ", scale=1)
            
            # ์ฑ—๋ด‡
            chatbot = gr.Chatbot(
                height=600,
                type='messages'
            )
            
            # ๋ฉ”์‹œ์ง€ ์ž…๋ ฅ
            with gr.Row():
                msg = gr.Textbox(
                    label="๋ฉ”์‹œ์ง€๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”",
                    placeholder="์˜ˆ: COVID-19๋ฅผ ์น˜๋ฃŒํ•  ์ˆ˜ ์žˆ๋Š” ๋‹จ๋ฐฑ์งˆ์„ ์ƒ์„ฑํ•ด์ฃผ์„ธ์š”",
                    lines=2,
                    scale=4
                )
                submit_btn = gr.Button("์ „์†ก", variant="primary", scale=1)
            
            clear = gr.Button("๋Œ€ํ™” ๋‚ด์šฉ ์ง€์šฐ๊ธฐ")


            with gr.Accordion("์ฑ„ํŒ… ์„ค์ •", open=False):
                system_message = gr.Textbox(
                    value="๋‹น์‹ ์€ ๋‹จ๋ฐฑ์งˆ ์„ค๊ณ„๋ฅผ ๋„์™€์ฃผ๋Š” ์ „๋ฌธ๊ฐ€์ž…๋‹ˆ๋‹ค.",
                    label="์‹œ์Šคํ…œ ๋ฉ”์‹œ์ง€"
                )
                max_tokens = gr.Slider(
                    minimum=1,
                    maximum=3800,
                    value=3800,
                    step=1,
                    label="์ตœ๋Œ€ ํ† ํฐ ์ˆ˜"
                )
                temperature = gr.Slider(
                    minimum=0.1,
                    maximum=4.0,
                    value=0.7,
                    step=0.1,
                    label="Temperature"
                )
                top_p = gr.Slider(
                    minimum=0.1,
                    maximum=1.0,
                    value=0.95,
                    step=0.05,
                    label="Top-P"
                )

            # ํƒญ ์ธํ„ฐํŽ˜์ด์Šค
            with gr.Tabs():
                with gr.TabItem("๐Ÿงฌ ์ปค์Šคํ…€ ๋””์ž์ธ"):
                    gr.Markdown("""
                    ### โœจ ๋‹น์‹ ๋งŒ์˜ ํŠน๋ณ„ํ•œ ์ปค์Šคํ…€์„ ๋งŒ๋“ค์–ด๋ณด์„ธ์š”!
                    ๊ฐ ๋Šฅ๋ ฅ์น˜๋ฅผ ์กฐ์ ˆํ•˜๋ฉด ์ปค์Šคํ…€๋œ ๋‹จ๋ฐฑ์งˆ์ด ์ž๋™์œผ๋กœ ์„ค๊ณ„๋ฉ๋‹ˆ๋‹ค.
                    """)
                    
                    # ๊ธฐ๋ณธ ์ •๋ณด
                    hero_name = gr.Textbox(
                        label="์ปค์Šคํ…€ ์ด๋ฆ„", 
                        placeholder="๋‹น์‹ ์˜ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์ด๋ฆ„์„ ์ง€์–ด์ฃผ์„ธ์š”!",
                        info="๋‹น์‹ ๋งŒ์˜ ์ •์ฒด์„ฑ์„ ๋‚˜ํƒ€๋‚ด๋Š” ์ด๋ฆ„์„ ์ž…๋ ฅํ•˜์„ธ์š”"
                    )
                    
                    # ๋Šฅ๋ ฅ์น˜ ์„ค์ •
                    gr.Markdown("### ๐Ÿ’ช ์ปค์Šคํ…€ ๋Šฅ๋ ฅ์น˜ ์„ค์ •")
                    with gr.Row():
                        strength = gr.Slider(
                            minimum=0.0, maximum=0.05, 
                            label="๐Ÿ’ช ์ดˆ๊ฐ•๋ ฅ(๊ทผ๋ ฅ)", 
                            value=0.02,
                            info="๋‹จ๋‹จํ•œ ๋ฒ ํƒ€์‹œํŠธ ๊ตฌ์กฐ๋กœ ๊ฐ•๋ ฅํ•œ ํž˜์„ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค"
                        )
                        flexibility = gr.Slider(
                            minimum=0.0, maximum=0.05, 
                            label="๐Ÿคธโ€โ™‚๏ธ ์œ ์—ฐ์„ฑ", 
                            value=0.02,
                            info="๋‚˜์„ ํ˜• ์•ŒํŒŒํ—ฌ๋ฆญ์Šค ๊ตฌ์กฐ๋กœ ์œ ์—ฐํ•œ ์›€์ง์ž„์„ ๊ฐ€๋Šฅํ•˜๊ฒŒ ํ•ฉ๋‹ˆ๋‹ค"
                        )
                    
                    with gr.Row():
                        speed = gr.Slider(
                            minimum=0.0, maximum=0.20, 
                            label="โšก ์Šคํ”ผ๋“œ", 
                            value=0.1,
                            info="๋ฃจํ”„ ๊ตฌ์กฐ๋กœ ๋น ๋ฅธ ์›€์ง์ž„์„ ๊ตฌํ˜„ํ•ฉ๋‹ˆ๋‹ค"
                        )
                        defense = gr.Slider(
                            minimum=-10, maximum=10, 
                            label="๐Ÿ›ก๏ธ ๋ฐฉ์–ด๋ ฅ", 
                            value=0,
                            info="์Œ์ˆ˜: ์ˆ˜์ค‘ ํ™œ๋™์— ํŠนํ™”, ์–‘์ˆ˜: ์ง€์ƒ ํ™œ๋™์— ํŠนํ™”"
                        )
                    
                    # ํฌ๊ธฐ ์„ค์ •
                    hero_size = gr.Slider(
                        minimum=50, maximum=200, 
                        label="๐Ÿ“ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ํฌ๊ธฐ", 
                        value=100,
                        info="์ „์ฒด์ ์ธ ํฌ๊ธฐ๋ฅผ ๊ฒฐ์ •ํ•ฉ๋‹ˆ๋‹ค"
                    )
                    
                    # ํŠน์ˆ˜ ๋Šฅ๋ ฅ ์„ค์ •
                    with gr.Accordion("๐ŸŒŸ ํŠน์ˆ˜ ๋Šฅ๋ ฅ", open=False):
                        gr.Markdown("""
                        ํŠน์ˆ˜ ๋Šฅ๋ ฅ์„ ์„ ํƒํ•˜๋ฉด ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ์— ํŠน๋ณ„ํ•œ ๊ตฌ์กฐ๊ฐ€ ์ถ”๊ฐ€๋ฉ๋‹ˆ๋‹ค.
                        - ์ž๊ฐ€ ํšŒ๋ณต: ๋‹จ๋ฐฑ์งˆ ๊ตฌ์กฐ ๋ณต๊ตฌ ๋Šฅ๋ ฅ ๊ฐ•ํ™”
                        - ์›๊ฑฐ๋ฆฌ ๊ณต๊ฒฉ: ํŠน์ˆ˜ํ•œ ๊ตฌ์กฐ์  ๋Œ์ถœ๋ถ€ ํ˜•์„ฑ
                        - ๋ฐฉ์–ด๋ง‰ ์ƒ์„ฑ: ์•ˆ์ •์ ์ธ ๋ณดํ˜ธ์ธต ๊ตฌ์กฐ ์ƒ์„ฑ
                        """)
                        special_ability = gr.CheckboxGroup(
                            choices=["์ž๊ฐ€ ํšŒ๋ณต", "์›๊ฑฐ๋ฆฌ ๊ณต๊ฒฉ", "๋ฐฉ์–ด๋ง‰ ์ƒ์„ฑ"],
                            label="ํŠน์ˆ˜ ๋Šฅ๋ ฅ ์„ ํƒ"
                        )
                    
                    # ์ƒ์„ฑ ๋ฒ„ํŠผ
                    create_btn = gr.Button("๐Ÿงฌ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ!", variant="primary", scale=2)

                with gr.TabItem("๐Ÿงฌ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์„ค๊ณ„"):
                    gr.Markdown("""
                    ### ๐Ÿงช ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ๊ณ ๊ธ‰ ์„ค์ •
                    ์œ ์ „์ž ๊ตฌ์กฐ๋ฅผ ๋” ์„ธ๋ฐ€ํ•˜๊ฒŒ ์กฐ์ •ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
                    """)
                    
                    seq_opt = gr.Radio(
                        ["์ž๋™ ์„ค๊ณ„", "์ง์ ‘ ์ž…๋ ฅ"],
                        label="DNA ์„ค๊ณ„ ๋ฐฉ์‹",
                        value="์ž๋™ ์„ค๊ณ„"
                    )

                    sequence = gr.Textbox(
                        label="๋‹จ๋ฐฑ์งˆ ์‹œํ€€์Šค", 
                        lines=1, 
                        placeholder='์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์•„๋ฏธ๋…ธ์‚ฐ: A,C,D,E,F,G,H,I,K,L,M,N,P,Q,R,S,T,V,W,Y (X๋Š” ๋ฌด์ž‘์œ„)',
                        visible=False
                    )
                    seq_len = gr.Slider(
                        minimum=5.0, maximum=250.0, 
                        label="DNA ๊ธธ์ด", 
                        value=100, 
                        visible=True
                    )
                    
                    with gr.Accordion(label='๐Ÿฆด ๊ณจ๊ฒฉ ๊ตฌ์กฐ ์„ค์ •', open=True):
                        gr.Markdown("""
                        ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ๊ธฐ๋ณธ ๊ณจ๊ฒฉ ๊ตฌ์กฐ๋ฅผ ์„ค์ •ํ•ฉ๋‹ˆ๋‹ค.
                        - ๋‚˜์„ ํ˜• ๊ตฌ์กฐ: ์œ ์—ฐํ•˜๊ณ  ํƒ„๋ ฅ์žˆ๋Š” ์›€์ง์ž„
                        - ๋ณ‘ํ’ํ˜• ๊ตฌ์กฐ: ๋‹จ๋‹จํ•˜๊ณ  ๊ฐ•๋ ฅํ•œ ํž˜
                        - ๊ณ ๋ฆฌํ˜• ๊ตฌ์กฐ: ๋น ๋ฅด๊ณ  ๋ฏผ์ฒฉํ•œ ์›€์ง์ž„
                        """)
                        sec_str_opt = gr.Radio(
                            ["์Šฌ๋ผ์ด๋”๋กœ ์„ค์ •", "์ง์ ‘ ์ž…๋ ฅ"],
                            label="๊ณจ๊ฒฉ ๊ตฌ์กฐ ์„ค์ • ๋ฐฉ์‹",
                            value="์Šฌ๋ผ์ด๋”๋กœ ์„ค์ •"
                        )

                        secondary_structure = gr.Textbox(
                            label="๊ณจ๊ฒฉ ๊ตฌ์กฐ",
                            lines=1,
                            placeholder='H:๋‚˜์„ ํ˜•, S:๋ณ‘ํ’ํ˜•, L:๊ณ ๋ฆฌํ˜•, X:์ž๋™์„ค์ •',
                            visible=False
                        )
                        
                        with gr.Column():
                            helix_bias = gr.Slider(
                                minimum=0.0, maximum=0.05,
                                label="๋‚˜์„ ํ˜• ๊ตฌ์กฐ ๋น„์œจ",
                                visible=True
                            )
                            strand_bias = gr.Slider(
                                minimum=0.0, maximum=0.05,
                                label="๋ณ‘ํ’ํ˜• ๊ตฌ์กฐ ๋น„์œจ",
                                visible=True
                            )
                            loop_bias = gr.Slider(
                                minimum=0.0, maximum=0.20,
                                label="๊ณ ๋ฆฌํ˜• ๊ตฌ์กฐ ๋น„์œจ",
                                visible=True
                            )
                    
                    with gr.Accordion(label='๐Ÿงฌ ๋‹จ๋ฐฑ์งˆ ๊ตฌ์„ฑ ์„ค์ •', open=False):
                        gr.Markdown("""
                        ํŠน์ • ์•„๋ฏธ๋…ธ์‚ฐ์˜ ๋น„์œจ์„ ์กฐ์ ˆํ•˜์—ฌ ํŠน์„ฑ์„ ๊ฐ•ํ™”ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
                        ์˜ˆ์‹œ: W0.2,E0.1 (ํŠธ๋ฆฝํ† ํŒ 20%, ๊ธ€๋ฃจํƒ์‚ฐ 10%)
                        """)
                        with gr.Row():
                            aa_bias = gr.Textbox(
                                label="์•„๋ฏธ๋…ธ์‚ฐ ๋น„์œจ", 
                                lines=1, 
                                placeholder='์˜ˆ์‹œ: W0.2,E0.1'
                            )
                            aa_bias_potential = gr.Textbox(
                                label="๊ฐ•ํ™” ์ •๋„", 
                                lines=1, 
                                placeholder='1.0-5.0 ์‚ฌ์ด ๊ฐ’ ์ž…๋ ฅ'
                            )

                    with gr.Accordion(label='๐ŸŒ ํ™˜๊ฒฝ ์ ์‘๋ ฅ ์„ค์ •', open=False):
                        gr.Markdown("""
                        ํ™˜๊ฒฝ ์ ์‘๋ ฅ์„ ์กฐ์ ˆํ•ฉ๋‹ˆ๋‹ค.
                        ์Œ์ˆ˜: ์ˆ˜์ค‘ ํ™œ๋™์— ํŠนํ™”, ์–‘์ˆ˜: ์ง€์ƒ ํ™œ๋™์— ํŠนํ™”
                        """)
                        with gr.Row():
                            hydrophobic_target_score = gr.Textbox(
                                label="ํ™˜๊ฒฝ ์ ์‘ ์ ์ˆ˜",
                                lines=1,
                                placeholder='์˜ˆ์‹œ: -5 (์ˆ˜์ค‘ ํ™œ๋™์— ํŠนํ™”)'
                            )
                            hydrophobic_potential = gr.Textbox(
                                label="์ ์‘๋ ฅ ๊ฐ•ํ™” ์ •๋„",
                                lines=1,
                                placeholder='1.0-2.0 ์‚ฌ์ด ๊ฐ’ ์ž…๋ ฅ'
                            )

                    with gr.Accordion(label='โš™๏ธ ๊ณ ๊ธ‰ ์„ค์ •', open=False):
                        gr.Markdown("""
                        DNA ์ƒ์„ฑ ๊ณผ์ •์˜ ์„ธ๋ถ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์กฐ์ •ํ•ฉ๋‹ˆ๋‹ค.
                        """)
                        with gr.Row():
                            num_steps = gr.Textbox(
                                label="์ƒ์„ฑ ๋‹จ๊ณ„",
                                lines=1,
                                placeholder='25 ์ดํ•˜ ๊ถŒ์žฅ'
                            )
                            noise = gr.Dropdown(
                                ['normal','gmm2 [-1,1]','gmm3 [-1,0,1]'],
                                label='๋…ธ์ด์ฆˆ ํƒ€์ž…',
                                value='normal'
                            )
                    
                    design_btn = gr.Button("๐Ÿงฌ ๋‹จ๋ฐฑ์งˆ ์„ค๊ณ„ ์ƒ์„ฑ!", variant="primary", scale=2)

                with gr.TabItem("๐Ÿงช ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ๊ฐ•ํ™”"):
                    gr.Markdown("""
                    ### โšก ๊ธฐ์กด ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ํ™œ์šฉ
                    ๊ธฐ์กด ๋‹จ๋ฐฑ์งˆ ์ผ๋ถ€๋ฅผ ์ƒˆ๋กœ์šด ์ปค์Šคํ…€์—๊ฒŒ ์ด์‹ํ•ฉ๋‹ˆ๋‹ค.
                    """)
                    
                    gr.Markdown("๊ณต๊ฐœ๋œ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์—์„œ ์ฝ”๋“œ๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค")
                    pdb_id_code = gr.Textbox(
                        label="์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์ฝ”๋“œ",
                        lines=1,
                        placeholder='๊ธฐ์กด ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š” (์˜ˆ: 1DPX)'
                    )
                    
                    gr.Markdown("์ด์‹ํ•˜๊ณ  ์‹ถ์€ ๋‹จ๋ฐฑ์งˆ ์˜์—ญ์„ ์„ ํƒํ•˜๊ณ  ์ƒˆ๋กœ์šด ๋‹จ๋ฐฑ์งˆ์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค")
                    contigs = gr.Textbox(
                        label="์ด์‹ํ•  ๋‹จ๋ฐฑ์งˆ ์˜์—ญ",
                        lines=1,
                        placeholder='์˜ˆ์‹œ: 15,A3-10,20-30'
                    )
                    
                    with gr.Row():
                        seq_mask = gr.Textbox(
                            label='๋Šฅ๋ ฅ ์žฌ์„ค๊ณ„',
                            lines=1,
                            placeholder='์„ ํƒํ•œ ์˜์—ญ์˜ ๋Šฅ๋ ฅ์„ ์ƒˆ๋กญ๊ฒŒ ๋””์ž์ธ'
                        )
                        str_mask = gr.Textbox(
                            label='๊ตฌ์กฐ ์žฌ์„ค๊ณ„',
                            lines=1,
                            placeholder='์„ ํƒํ•œ ์˜์—ญ์˜ ๊ตฌ์กฐ๋ฅผ ์ƒˆ๋กญ๊ฒŒ ๋””์ž์ธ'
                        )
                    
                    preview_viewer = gr.HTML()
                    rewrite_pdb = gr.File(label='์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ํŒŒ์ผ')
                    preview_btn = gr.Button("๐Ÿ” ๋ฏธ๋ฆฌ๋ณด๊ธฐ", variant="secondary")
                    enhance_btn = gr.Button("โšก ๊ฐ•ํ™”๋œ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ!", variant="primary", scale=2)

                with gr.TabItem("๐Ÿ‘‘ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์กฑ๋ณด"):
                    gr.Markdown("""
                    ### ๐Ÿฐ ์œ„๋Œ€ํ•œ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ๊ฐ€๋ฌธ์˜ ์œ ์‚ฐ
                    ๊ฐ•๋ ฅํ•œ ํŠน์„ฑ์„ ๊ณ„์Šนํ•˜์—ฌ ์ƒˆ๋กœ์šด ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ์„ ๋งŒ๋“ญ๋‹ˆ๋‹ค.
                    """)
                    
                    with gr.Row():
                        with gr.Column():
                            gr.Markdown("์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์ •๋ณด๊ฐ€ ๋‹ด๊ธด ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•˜์„ธ์š”")
                            fasta_msa = gr.File(label='๊ฐ€๋ฌธ DNA ๋ฐ์ดํ„ฐ')
                        with gr.Column():
                            gr.Markdown("์ด๋ฏธ ๋ถ„์„๋œ ๊ฐ€๋ฌธ ํŠน์„ฑ ๋ฐ์ดํ„ฐ๊ฐ€ ์žˆ๋‹ค๋ฉด ์—…๋กœ๋“œํ•˜์„ธ์š”")
                            input_pssm = gr.File(label='๊ฐ€๋ฌธ ํŠน์„ฑ ๋ฐ์ดํ„ฐ')
                    
                    pssm = gr.File(label='๋ถ„์„๋œ ๊ฐ€๋ฌธ ํŠน์„ฑ')
                    pssm_view = gr.Plot(label='๊ฐ€๋ฌธ ํŠน์„ฑ ๋ถ„์„ ๊ฒฐ๊ณผ')
                    pssm_gen_btn = gr.Button("โœจ ๊ฐ€๋ฌธ ํŠน์„ฑ ๋ถ„์„", variant="secondary")
                    inherit_btn = gr.Button("๐Ÿ‘‘ ๊ฐ€๋ฌธ์˜ ํž˜ ๊ณ„์Šน!", variant="primary", scale=2)

        # ์˜ค๋ฅธ์ชฝ ์—ด: ๊ฒฐ๊ณผ ํ‘œ์‹œ
        with gr.Column(scale=1):
            gr.Markdown("## ๐Ÿงฌ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ํ”„๋กœํ•„")
            hero_stats = gr.Plot(label="๋Šฅ๋ ฅ์น˜ ๋ถ„์„")
            hero_description = gr.Textbox(label="์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ํŠน์„ฑ", lines=3)
            
            gr.Markdown("## ๐Ÿงฌ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ๋ถ„์„ ๊ฒฐ๊ณผ")
            gr.Markdown("#### โšก ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์•ˆ์ •์„ฑ ์ ์ˆ˜")
            plddt_plot = gr.Plot(label='์•ˆ์ •์„ฑ ๋ถ„์„')
            gr.Markdown("#### ๐Ÿ“ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์‹œํ€€์Šค")
            output_seq = gr.Textbox(label="์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ์„œ์—ด")
            gr.Markdown("#### ๐Ÿ’พ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ๋ฐ์ดํ„ฐ")
            output_pdb = gr.File(label="์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ํŒŒ์ผ")
            gr.Markdown("#### ๐Ÿ”ฌ ์ปค์Šคํ…€ ๋‹จ๋ฐฑ์งˆ ๊ตฌ์กฐ")
            output_viewer = gr.HTML()

    # ์˜ˆ์ œ ์„ ํƒ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
    def use_example(example):
        if example:
            return example
        return ""

    example_btn.click(
        fn=use_example,
        inputs=[example_dropdown],
        outputs=[msg]
    )            



# ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
    # ์ฑ—๋ด‡ ์ด๋ฒคํŠธ
    msg.submit(process_chat, [msg, chatbot], [chatbot])
    clear.click(lambda: None, None, chatbot, queue=False)

    # ์ž…๋ ฅ ๋ฐฉ์‹ ๋ณ€๊ฒฝ ์ด๋ฒคํŠธ
    seq_opt.change(
        fn=toggle_seq_input,
        inputs=[seq_opt],
        outputs=[seq_len, sequence],
        queue=False
    )

    # ๊ตฌ์กฐ ์„ค์ • ๋ฐฉ์‹ ๋ณ€๊ฒฝ ์ด๋ฒคํŠธ
    sec_str_opt.change(
        fn=toggle_secondary_structure,
        inputs=[sec_str_opt],
        outputs=[helix_bias, strand_bias, loop_bias, secondary_structure],
        queue=False
    )

    # ๋ฏธ๋ฆฌ๋ณด๊ธฐ ์ด๋ฒคํŠธ
    preview_btn.click(
        get_motif_preview,
        inputs=[pdb_id_code, contigs],
        outputs=[preview_viewer, rewrite_pdb]
    )

    # PSSM ๋ถ„์„ ์ด๋ฒคํŠธ
    pssm_gen_btn.click(
        get_pssm,
        inputs=[fasta_msa, input_pssm],
        outputs=[pssm_view, pssm]
    )

    # ์ฑ—๋ด‡ ๊ธฐ๋ฐ˜ ๋‹จ๋ฐฑ์งˆ ์ƒ์„ฑ ๊ฒฐ๊ณผ ์—…๋ฐ์ดํŠธ
    def update_protein_display(chat_response):
        if "์ƒ์„ฑ๋œ ๋‹จ๋ฐฑ์งˆ ๋ถ„์„" in chat_response:
            params = extract_parameters_from_chat(chat_response)
            result = generate_protein(params)
            return {
                hero_stats: create_radar_chart(calculate_hero_stats(params)),
                hero_description: chat_response,
                output_seq: result[0],
                output_pdb: result[1],
                output_viewer: display_pdb(result[1]),
                plddt_plot: result[3]
            }
        return None

    # ๊ฐ ์ƒ์„ฑ ๋ฒ„ํŠผ ์ด๋ฒคํŠธ ์—ฐ๊ฒฐ
    for btn in [create_btn, design_btn, enhance_btn, inherit_btn]:
        btn.click(
            combined_generation,
            inputs=[
                hero_name, strength, flexibility, speed, defense, hero_size, special_ability,
                sequence, seq_len, helix_bias, strand_bias, loop_bias, 
                secondary_structure, aa_bias, aa_bias_potential, 
                num_steps, noise, hydrophobic_target_score, hydrophobic_potential,
                contigs, pssm, seq_mask, str_mask, rewrite_pdb
            ],
            outputs=[
                hero_stats, 
                hero_description, 
                output_seq,
                output_pdb,
                output_viewer,
                plddt_plot
            ]
        )

    # ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ ์—ฐ๊ฒฐ
    msg.submit(
        fn=process_chat_and_generate,
        inputs=[msg, chatbot],
        outputs=[
            chatbot,
            hero_stats,
            hero_description,
            output_seq,
            output_pdb,
            output_viewer,
            plddt_plot
        ]
    )

    submit_btn.click(
        fn=process_chat_and_generate,
        inputs=[msg, chatbot],
        outputs=[
            chatbot,
            hero_stats,
            hero_description,
            output_seq,
            output_pdb,
            output_viewer,
            plddt_plot
        ]
    )

    # ์ฑ„ํŒ… ๋‚ด์šฉ ์ง€์šฐ๊ธฐ
    clear.click(
        lambda: (None, None, None, None, None, None, None),
        None,
        [chatbot, hero_stats, hero_description, output_seq, output_pdb, output_viewer, plddt_plot],
        queue=False
    )

    # ์ฑ—๋ด‡ ์‘๋‹ต์— ๋”ฐ๋ฅธ ๊ฒฐ๊ณผ ์—…๋ฐ์ดํŠธ
    msg.submit(
        update_protein_display,
        inputs=[chatbot],
        outputs=[hero_stats, hero_description, output_seq, output_pdb, output_viewer, plddt_plot]
    )

    # ๊ธฐ๋ณธ ์ฑ—๋ด‡ ์‘๋‹ต ์ฒ˜๋ฆฌ
    submit_btn.click(respond, 
                    [msg, chatbot, system_message, max_tokens, temperature, top_p], 
                    [chatbot])
    msg.submit(respond, 
              [msg, chatbot, system_message, max_tokens, temperature, top_p], 
              [chatbot])
    clear.click(lambda: None, None, chatbot, queue=False)

    # ์ง„ํ–‰ ์ƒํƒœ ํ‘œ์‹œ ์ด๋ฒคํŠธ
    msg.submit(
        fn=process_chat_and_generate,
        inputs=[msg, chatbot],
        outputs=[
            chatbot,
            hero_stats,
            hero_description,
            output_seq,
            output_pdb,
            output_viewer,
            plddt_plot
        ],
        show_progress=True
    )
    
    submit_btn.click(
        fn=process_chat_and_generate,
        inputs=[msg, chatbot],
        outputs=[
            chatbot,
            hero_stats,
            hero_description,
            output_seq,
            output_pdb,
            output_viewer,
            plddt_plot
        ],
        show_progress=True
    )

# ์‹คํ–‰
demo.queue()
demo.launch(debug=True, share=True)