File size: 46,036 Bytes
7e4fb15
 
 
c383a1a
7e4fb15
 
 
 
0398d1e
7e4fb15
 
cb1dc3c
0398d1e
cb1dc3c
0398d1e
 
 
 
 
 
 
 
7e4fb15
 
 
cb1dc3c
0398d1e
cb1dc3c
0398d1e
7e4fb15
 
 
cb1dc3c
0398d1e
cb1dc3c
0398d1e
7e4fb15
 
cb1dc3c
 
0398d1e
cb1dc3c
0398d1e
7e4fb15
 
 
cb1dc3c
0398d1e
cb1dc3c
0398d1e
7e4fb15
ecc2bb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0398d1e
c383a1a
0398d1e
7e4fb15
cb1dc3c
7e4fb15
 
0398d1e
7e4fb15
0398d1e
 
cb1dc3c
 
 
7e4fb15
 
0398d1e
7e4fb15
 
0398d1e
 
 
 
 
7e4fb15
 
 
 
0398d1e
7e4fb15
0398d1e
7e4fb15
 
 
 
 
 
 
 
 
 
0398d1e
7e4fb15
0398d1e
7e4fb15
0398d1e
7e4fb15
c383a1a
 
7e4fb15
 
0398d1e
7e4fb15
 
 
29ce347
0398d1e
c383a1a
0398d1e
7e4fb15
 
0398d1e
7e4fb15
 
 
 
 
 
 
c383a1a
7e4fb15
0398d1e
7e4fb15
0398d1e
7e4fb15
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0398d1e
ecc2bb4
7e4fb15
 
ecc2bb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e4fb15
0398d1e
7e4fb15
cb1dc3c
0398d1e
7e4fb15
0398d1e
cb1dc3c
7e4fb15
0398d1e
7e4fb15
0398d1e
7e4fb15
cb1dc3c
 
7e4fb15
 
 
c383a1a
 
0398d1e
 
 
 
 
 
 
 
 
 
 
 
 
 
c383a1a
cb1dc3c
0398d1e
7e4fb15
 
c383a1a
 
0398d1e
 
 
7e4fb15
0398d1e
 
 
7e4fb15
0398d1e
 
7e4fb15
c383a1a
 
7e4fb15
 
 
 
0398d1e
 
 
 
7e4fb15
 
0398d1e
 
 
 
 
cb1dc3c
7e4fb15
 
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0398d1e
c383a1a
0398d1e
 
7e4fb15
 
0398d1e
 
7e4fb15
 
 
16c1e8a
0398d1e
 
16c1e8a
c383a1a
 
 
16c1e8a
 
 
 
 
 
0398d1e
 
c383a1a
 
 
 
 
0398d1e
7e4fb15
 
 
0398d1e
c383a1a
0398d1e
 
7e4fb15
 
16c1e8a
 
 
 
4fd4c0d
16c1e8a
c383a1a
 
 
 
 
 
 
 
4fd4c0d
 
 
 
 
 
 
 
 
 
 
 
 
 
bad7e32
7e4fb15
 
c383a1a
4fd4c0d
 
c383a1a
4fd4c0d
 
c383a1a
4fd4c0d
7e4fb15
4fd4c0d
 
 
 
 
 
 
0398d1e
4fd4c0d
 
 
 
 
 
16c1e8a
 
 
 
 
 
0398d1e
 
c383a1a
 
 
 
 
0398d1e
4fd4c0d
7e4fb15
4fd4c0d
7e4fb15
29ce347
cb1dc3c
29ce347
 
 
 
0398d1e
 
29ce347
0398d1e
29ce347
0398d1e
 
c383a1a
 
29ce347
0398d1e
29ce347
c383a1a
0398d1e
 
 
 
c383a1a
 
0398d1e
 
 
 
c383a1a
 
0398d1e
cb1dc3c
29ce347
 
 
 
7e4fb15
0398d1e
7e4fb15
c383a1a
0398d1e
 
c383a1a
 
0398d1e
 
 
c383a1a
 
29ce347
cb1dc3c
c383a1a
 
 
0398d1e
c383a1a
 
 
 
 
 
 
 
 
 
 
0398d1e
 
c383a1a
0398d1e
 
 
 
c383a1a
 
 
 
29ce347
 
0398d1e
29ce347
0398d1e
29ce347
ecc2bb4
 
c383a1a
ecc2bb4
 
0398d1e
 
 
c383a1a
29ce347
0398d1e
cb1dc3c
0398d1e
 
c383a1a
0398d1e
 
c383a1a
0398d1e
 
 
 
c383a1a
29ce347
c383a1a
0398d1e
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
0398d1e
 
c383a1a
 
0398d1e
 
 
c383a1a
 
 
 
 
 
 
0398d1e
c383a1a
0398d1e
c383a1a
 
 
 
 
 
 
 
0398d1e
 
 
 
 
 
 
 
 
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0398d1e
c383a1a
 
0398d1e
c383a1a
 
 
 
 
 
 
 
 
 
0398d1e
 
 
 
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ce347
c383a1a
0398d1e
c383a1a
0398d1e
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bad7e32
0398d1e
c383a1a
0398d1e
c383a1a
0398d1e
 
7e4fb15
c383a1a
 
 
29ce347
c383a1a
bad7e32
29ce347
c383a1a
bad7e32
 
c383a1a
bad7e32
c383a1a
 
 
bad7e32
c383a1a
bad7e32
 
c383a1a
 
 
 
 
 
bad7e32
c383a1a
 
 
 
 
 
bad7e32
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bad7e32
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29ce347
c383a1a
0398d1e
c383a1a
0398d1e
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bad7e32
0398d1e
c383a1a
0398d1e
c383a1a
0398d1e
 
 
c383a1a
 
 
0398d1e
c383a1a
 
 
bad7e32
c383a1a
bad7e32
c383a1a
bad7e32
c383a1a
bad7e32
c383a1a
 
 
 
 
bad7e32
c383a1a
 
 
bad7e32
 
c383a1a
bad7e32
c383a1a
 
 
 
0398d1e
bad7e32
c383a1a
 
 
 
bad7e32
c383a1a
 
 
 
 
 
 
 
 
bad7e32
c383a1a
0398d1e
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
bad7e32
 
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0398d1e
c383a1a
 
 
 
 
 
 
 
bad7e32
 
 
 
 
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bad7e32
 
0398d1e
c383a1a
 
0398d1e
c383a1a
0398d1e
c383a1a
0398d1e
c383a1a
bad7e32
c383a1a
bad7e32
c383a1a
bad7e32
c383a1a
 
 
bad7e32
 
c383a1a
 
 
 
 
 
 
 
bad7e32
29ce347
c383a1a
29ce347
c383a1a
0398d1e
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0398d1e
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0398d1e
 
c383a1a
 
 
 
0398d1e
 
 
 
c383a1a
 
 
0398d1e
ecc2bb4
c383a1a
 
0398d1e
 
c383a1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
from typing import List, Dict, Tuple
import time

import streamlit as st
import requests

# ์„ ํƒ์  ์˜์กด์„ฑ ๊ฐ€๋“œ
try:
    import torch
    TORCH_AVAILABLE = True
except ImportError:
    TORCH_AVAILABLE = False
    print("[WARNING] torch not available")

try:
    from transformers import AutoTokenizer, AutoModel, AutoModelForMaskedLM
    TRANSFORMERS_AVAILABLE = True
except ImportError:
    TRANSFORMERS_AVAILABLE = False
    print("[WARNING] transformers not available")

try:
    from datasets import load_dataset
    DATASETS_AVAILABLE = True
except ImportError:
    DATASETS_AVAILABLE = False
    print("[WARNING] datasets not available")

try:
    from sentence_transformers import SentenceTransformer
    SENTENCE_TRANSFORMERS_AVAILABLE = True
except ImportError:
    SENTENCE_TRANSFORMERS_AVAILABLE = False
    print("[WARNING] sentence_transformers not available")

try:
    import faiss
    FAISS_AVAILABLE = True
except ImportError:
    FAISS_AVAILABLE = False
    print("[WARNING] faiss not available")

try:
    from Bio import SeqIO
    BIOPYTHON_AVAILABLE = True
except ImportError:
    BIOPYTHON_AVAILABLE = False
    print("[WARNING] biopython not available")

# PDF ์ง€์› ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
try:
    import pdfplumber
    PDFPLUMBER_AVAILABLE = True
except ImportError:
    PDFPLUMBER_AVAILABLE = False
    print("[WARNING] pdfplumber not available")

try:
    import PyPDF2
    PYPDF2_AVAILABLE = True
except ImportError:
    PYPDF2_AVAILABLE = False
    print("[WARNING] PyPDF2 not available")

# ์ƒ์ˆ˜
APP_TITLE = "BioSeq Chat Pro: Advanced Collaborative AI System"
DISCLAIMER = "This tool is for research/education and is not a medical device. Do not use outputs for diagnosis or treatment decisions."

# --------------- Helper Functions ---------------

def get_secret(name: str, fallback: str = "") -> str:
    """Get secret from st.secrets or environment"""
    try:
        if hasattr(st, 'secrets') and name in st.secrets:
            return st.secrets[name]
    except:
        pass
    return os.environ.get(name, fallback)

def brave_search(query: str, count: int = 5) -> List[Dict]:
    """Brave Search API"""
    key = get_secret("BRAVE_API_KEY", "")
    if not key:
        return [{
            "title": "BRAVE_API_KEY missing",
            "url": "",
            "snippet": "Set BRAVE_API_KEY in Space secrets or sidebar"
        }]
    
    url = "https://api.search.brave.com/res/v1/web/search"
    headers = {
        "Accept": "application/json",
        "X-Subscription-Token": key
    }
    params = {"q": query, "count": count}
    
    try:
        r = requests.get(url, headers=headers, params=params, timeout=15)
        r.raise_for_status()
        data = r.json()
        results = []
        for item in data.get("web", {}).get("results", [])[:count]:
            results.append({
                "title": item.get("title", ""),
                "url": item.get("url", ""),
                "snippet": item.get("description", "")
            })
        return results if results else [{"title": "No results", "url": "", "snippet": ""}]
    except Exception as e:
        return [{"title": "Error", "url": "", "snippet": str(e)}]

def call_llm(messages: List[Dict], temperature: float = 0.6, max_tokens: int = 8000) -> str:
    """Call Fireworks AI API with increased token limit"""
    api_key = get_secret("FIREWORKS_API_KEY", "")
    if not api_key:
        return "FIREWORKS_API_KEY missing. Set it in Secrets or sidebar."
    
    url = "https://api.fireworks.ai/inference/v1/chat/completions"
    payload = {
        "model": "accounts/fireworks/models/llama-v3p1-70b-instruct",
        "messages": messages,
        "max_tokens": max_tokens,  # 8000์œผ๋กœ ์ฆ๊ฐ€
        "temperature": temperature,
        "top_p": 1,
        "frequency_penalty": 0,
        "presence_penalty": 0
    }
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    
    try:
        r = requests.post(url, headers=headers, json=payload, timeout=120)
        r.raise_for_status()
        return r.json()["choices"][0]["message"]["content"]
    except Exception as e:
        return f"[LLM Error] {e}"

def collaborative_answer(query: str, context: str, collaboration_type: str = "full") -> Dict[str, str]:
    """
    ํ˜‘์—… AI ์‹œ์Šคํ…œ: ๊ฐ๋…์ž, ๋น„ํ‰์ž, ์กฐ์‚ฌ์ž๊ฐ€ ํ˜‘๋ ฅํ•˜์—ฌ ๋‹ต๋ณ€ ์ƒ์„ฑ
    
    Args:
        query: ์‚ฌ์šฉ์ž ์งˆ๋ฌธ
        context: ๊ฒ€์ƒ‰๋œ ๋ฌธ๋งฅ ์ •๋ณด
        collaboration_type: "full" (์ „์ฒด ํ˜‘์—…), "quick" (๋น ๋ฅธ ๋‹ต๋ณ€), "deep" (์‹ฌ์ธต ๋ถ„์„)
    
    Returns:
        ๊ฐ ์—ญํ• ์ž์˜ ๊ธฐ์—ฌ์™€ ์ตœ์ข… ๋‹ต๋ณ€์„ ํฌํ•จํ•œ ๋”•์…”๋„ˆ๋ฆฌ
    """
    
    # 1. ์กฐ์‚ฌ์ž(Investigator) - ์‚ฌ์‹ค ์ˆ˜์ง‘ ๋ฐ ๊ฒ€์ฆ
    investigator_prompt = f"""You are an INVESTIGATOR specializing in bioinformatics fact-checking.

Context: {context}
Question: {query}

Your task:
1. Extract and verify all relevant facts from the context
2. Identify any missing information that would improve the answer
3. Flag any potentially conflicting or uncertain information
4. Suggest additional areas for research
5. Provide confidence scores for key facts (0-100%)

Format your response with:
- VERIFIED FACTS: (with confidence scores)
- UNCERTAIN AREAS:
- MISSING INFORMATION:
- RESEARCH SUGGESTIONS:
- KEY CITATIONS:"""

    investigator_msg = [
        {"role": "system", "content": "You are a meticulous scientific fact-checker and researcher."},
        {"role": "user", "content": investigator_prompt}
    ]
    
    investigator_response = call_llm(investigator_msg, temperature=0.2, max_tokens=2000)
    
    # 2. ๊ฐ๋…์ž(Supervisor) - ๊ตฌ์กฐํ™”๋œ ๋‹ต๋ณ€ ์ƒ์„ฑ
    supervisor_prompt = f"""You are a SUPERVISOR creating a comprehensive answer.

Question: {query}
Context: {context}
Investigator's Analysis:
{investigator_response}

Your task:
1. Create a well-structured, scientifically accurate answer
2. Include:
   - Executive Summary (2-3 sentences)
   - Background & Context
   - Detailed Explanation with subsections
   - Practical Applications
   - Current Research Status
   - Future Perspectives
3. Use clear headings and logical flow
4. Integrate verified facts from the investigator
5. Aim for 500-1000 words minimum
6. Include relevant examples and analogies

Format with clear markdown headers and bullet points where appropriate."""

    supervisor_msg = [
        {"role": "system", "content": "You are an expert bioinformatics educator who creates comprehensive, well-structured scientific explanations."},
        {"role": "user", "content": supervisor_prompt}
    ]
    
    supervisor_response = call_llm(supervisor_msg, temperature=0.4, max_tokens=3500)
    
    # 3. ๋น„ํ‰์ž(Critic) - ํ’ˆ์งˆ ๊ฒ€์ฆ ๋ฐ ๊ฐœ์„ 
    critic_prompt = f"""You are a CRITIC reviewing the following answer for scientific accuracy.

Original Question: {query}
Supervisor's Answer:
{supervisor_response}

Investigator's Facts:
{investigator_response}

Your task:
1. Check for scientific accuracy and completeness
2. Identify any errors, omissions, or unclear explanations
3. Verify that all claims are properly supported
4. Assess the answer's clarity and accessibility
5. Suggest specific improvements
6. Provide a quality score (0-100)

Format your critique:
- ACCURACY ASSESSMENT:
- COMPLETENESS CHECK:
- CLARITY EVALUATION:
- ERRORS/ISSUES FOUND:
- IMPROVEMENT SUGGESTIONS:
- QUALITY SCORE: X/100"""

    critic_msg = [
        {"role": "system", "content": "You are a rigorous scientific peer reviewer specializing in bioinformatics."},
        {"role": "user", "content": critic_prompt}
    ]
    
    critic_response = call_llm(critic_msg, temperature=0.3, max_tokens=1500)
    
    # 4. ์ตœ์ข… ํ†ตํ•ฉ ๋‹ต๋ณ€ (Final Integration)
    if collaboration_type == "full":
        integration_prompt = f"""Create the FINAL INTEGRATED ANSWER incorporating all feedback.

Question: {query}
Supervisor's Answer: {supervisor_response}
Critic's Feedback: {critic_response}
Verified Facts: {investigator_response}

Create a polished, final answer that:
1. Addresses all critic's concerns
2. Maintains scientific rigor
3. Includes proper citations
4. Uses clear structure with markdown formatting
5. Provides comprehensive coverage (800-1500 words)
6. Includes a TL;DR section at the beginning
7. Ends with key takeaways and further reading suggestions

Use Korean if the question is in Korean, otherwise English."""

        integration_msg = [
            {"role": "system", "content": "You are a master science communicator creating the definitive answer by integrating all expert inputs."},
            {"role": "user", "content": integration_prompt}
        ]
        
        final_answer = call_llm(integration_msg, temperature=0.35, max_tokens=8000)
    else:
        final_answer = supervisor_response
    
    return {
        "investigator": investigator_response,
        "supervisor": supervisor_response,
        "critic": critic_response,
        "final": final_answer
    }

def load_file_text(upload) -> str:
    """Load text from uploaded file (PDF ์ง€์› ํฌํ•จ)"""
    name = upload.name.lower()
    
    # PDF ์ฒ˜๋ฆฌ
    if name.endswith(".pdf"):
        if PDFPLUMBER_AVAILABLE:
            try:
                text_parts = []
                with pdfplumber.open(upload) as pdf:
                    for page in pdf.pages:
                        page_text = page.extract_text()
                        if page_text:
                            text_parts.append(page_text)
                return "\n\n".join(text_parts)
            except Exception as e:
                st.error(f"PDF ์ฝ๊ธฐ ์˜ค๋ฅ˜ (pdfplumber): {e}")
                return ""
        
        elif PYPDF2_AVAILABLE:
            try:
                upload.seek(0)
                pdf_reader = PyPDF2.PdfReader(upload)
                text_parts = []
                for page_num in range(len(pdf_reader.pages)):
                    page = pdf_reader.pages[page_num]
                    text_parts.append(page.extract_text())
                return "\n\n".join(text_parts)
            except Exception as e:
                st.error(f"PDF ์ฝ๊ธฐ ์˜ค๋ฅ˜ (PyPDF2): {e}")
                return ""
        else:
            st.error("PDF ํŒŒ์ผ์„ ์ฝ์œผ๋ ค๋ฉด pdfplumber ๋˜๋Š” PyPDF2๊ฐ€ ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค")
            return ""
    
    # ๊ธฐ์กด ํ…์ŠคํŠธ ํŒŒ์ผ ์ฒ˜๋ฆฌ
    try:
        content = upload.read()
        text = content.decode("utf-8", errors="ignore")
    except:
        return ""
    
    # FASTA handling
    if name.endswith((".fa", ".fasta", ".faa", ".fna")) and BIOPYTHON_AVAILABLE:
        try:
            upload.seek(0)
            records = list(SeqIO.parse(upload, "fasta"))
            seqs = [f">{r.id}\n{str(r.seq)}" for r in records]
            return "\n\n".join(seqs)
        except:
            pass
    
    return text

def chunk_text(text: str, size: int = 1500, overlap: int = 300) -> List[str]:
    """Split text into chunks with larger size for better context"""
    chunks = []
    start = 0
    text_len = len(text)
    
    while start < text_len:
        end = min(start + size, text_len)
        chunks.append(text[start:end])
        if end >= text_len:
            break
        start = end - overlap
    
    return chunks

def build_index(texts: List[str]):
    """Build vector index with better model"""
    if not SENTENCE_TRANSFORMERS_AVAILABLE or not FAISS_AVAILABLE:
        return None, None
    
    try:
        # ๋” ๋‚˜์€ ์ž„๋ฒ ๋”ฉ ๋ชจ๋ธ ์‚ฌ์šฉ
        model = SentenceTransformer("sentence-transformers/all-mpnet-base-v2")
        embeddings = model.encode(texts, show_progress_bar=False)
        
        dim = embeddings.shape[1]
        index = faiss.IndexFlatIP(dim)
        index.add(embeddings.astype("float32"))
        
        return index, model
    except Exception as e:
        st.warning(f"Index build failed: {e}")
        return None, None

def search_index(query: str, index, model, texts: List[str], k: int = 5) -> List[Dict]:
    """Search vector index with more results"""
    if index is None or model is None:
        return []
    
    try:
        q_emb = model.encode([query])
        D, I = index.search(q_emb.astype("float32"), k)
        
        results = []
        for idx, score in zip(I[0], D[0]):
            if 0 <= idx < len(texts):
                results.append({
                    "score": float(score),
                    "text": texts[idx]
                })
        return results
    except:
        return []

def build_context(query: str, docs: List[str], index, model, use_web: bool, web_k: int) -> Tuple[str, List[Dict]]:
    """Build enhanced context from sources"""
    pieces = []
    sources = []
    
    # File search with more results
    if index and model and docs:
        hits = search_index(query, index, model, docs, k=6)
        for h in hits:
            pieces.append(f"[FILE SOURCE] {h['text'][:800]}")
            sources.append({"type": "file", "text": h['text'][:150], "score": h['score']})
    
    # Web search with scientific focus
    if use_web:
        # ๊ณผํ•™์  ํ‚ค์›Œ๋“œ ์ถ”๊ฐ€
        scientific_query = f"{query} scientific research pubmed nature science"
        results = brave_search(scientific_query, count=web_k)
        for r in results:
            pieces.append(f"[WEB SOURCE] {r['title']}\n{r['snippet']}")
            sources.append({"type": "web", "title": r['title'], "url": r['url']})
    
    context = "\n\n---\n\n".join(pieces)[:6000]  # ์ปจํ…์ŠคํŠธ ํฌ๊ธฐ ์ฆ๊ฐ€
    return context, sources

# Enhanced analysis functions
def esm2_embed(seq: str, model_name: str = "facebook/esm2_t6_8M_UR50D") -> Dict:
    """Enhanced ESM-2 protein embedding with more analysis"""
    if not TORCH_AVAILABLE or not TRANSFORMERS_AVAILABLE:
        return {"error": "PyTorch/Transformers not available"}
    
    try:
        tokenizer = AutoTokenizer.from_pretrained(model_name)
        model = AutoModelForMaskedLM.from_pretrained(model_name)
        model.eval()
        
        with torch.no_grad():
            inputs = tokenizer(seq, return_tensors="pt", truncation=True, max_length=1024)
            outputs = model(**inputs, output_hidden_states=True)
            hidden = outputs.hidden_states[-1].mean(dim=1).squeeze(0)
            vec = hidden.cpu().numpy()
            
            # ์ถ”๊ฐ€ ๋ถ„์„
            attention_weights = outputs.hidden_states[-1].std(dim=1).squeeze(0).cpu().numpy()
        
        # ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
        del model
        del tokenizer
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        
        return {
            "embedding": vec.tolist()[:10],
            "size": vec.shape[0],
            "mean": float(vec.mean()),
            "std": float(vec.std()),
            "attention_peaks": attention_weights.tolist()[:10]
        }
    except Exception as e:
        return {"error": str(e)}

def dna_embed(seq: str, model_name: str = "zhihan1996/DNABERT-2-117M") -> Dict:
    """Enhanced DNA embedding with k-mer analysis"""
    if not TORCH_AVAILABLE or not TRANSFORMERS_AVAILABLE:
        return {"error": "PyTorch/Transformers not available"}
    
    try:
        # einops ์ฒดํฌ
        try:
            import einops
        except ImportError:
            return {"error": "einops package required. Please wait for installation and refresh the page."}
        
        # k-mer ๋ณ€ํ™˜ ํ•จ์ˆ˜
        def seq_to_kmer(seq, k=6):
            kmers = []
            for i in range(len(seq) - k + 1):
                kmers.append(seq[i:i+k])
            return ' '.join(kmers)
        
        # ๋ชจ๋ธ ๋กœ๋”ฉ ์‹œ๋„
        try:
            from transformers import AutoTokenizer, AutoModel
            tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
            model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
        except Exception as model_error:
            # ๋Œ€์ฒด ๋ชจ๋ธ ์‚ฌ์šฉ
            try:
                from transformers import BertTokenizer, BertModel
                fallback_model = "bert-base-uncased"
                tokenizer = BertTokenizer.from_pretrained(fallback_model)
                model = BertModel.from_pretrained(fallback_model)
                st.warning(f"DNABERT-2 ๋กœ๋”ฉ ์‹คํŒจ. ๋Œ€์ฒด ๋ชจ๋ธ ์‚ฌ์šฉ์ค‘: {fallback_model}")
            except:
                return {"error": f"๋ชจ๋ธ ๋กœ๋”ฉ ์‹คํŒจ: {str(model_error)}"}
        
        model.eval()
        
        # k-mer ๋ณ€ํ™˜
        if len(seq) > 6:
            input_seq = seq_to_kmer(seq, k=6)
            kmer_count = len(seq) - 5
        else:
            input_seq = seq
            kmer_count = 1
        
        with torch.no_grad():
            inputs = tokenizer(
                input_seq, 
                return_tensors="pt", 
                truncation=True, 
                max_length=512,
                padding=True
            )
            outputs = model(**inputs)
            
            if hasattr(outputs, 'pooler_output') and outputs.pooler_output is not None:
                vec = outputs.pooler_output.squeeze(0).cpu().numpy()
            else:
                hidden = outputs.last_hidden_state.mean(dim=1).squeeze(0)
                vec = hidden.cpu().numpy()
        
        # ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
        del model
        del tokenizer
        if torch.cuda.is_available():
            torch.cuda.empty_cache()
        
        return {
            "embedding": vec.tolist()[:10],
            "size": vec.shape[0],
            "kmer_count": kmer_count,
            "mean": float(vec.mean()),
            "std": float(vec.std())
        }
        
    except Exception as e:
        return {"error": f"๋ถ„์„ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)[:200]}"}

# --------------- Streamlit UI ---------------

st.set_page_config(page_title=APP_TITLE, page_icon="๐Ÿงฌ", layout="wide")
st.title(APP_TITLE)
st.caption(DISCLAIMER)

# Session state init
if "docs" not in st.session_state:
    st.session_state.docs = []
if "index" not in st.session_state:
    st.session_state.index = None
if "model" not in st.session_state:
    st.session_state.model = None
if "chat_history" not in st.session_state:
    st.session_state.chat_history = []

# Sidebar
with st.sidebar:
    st.header("โš™๏ธ Configuration")
    
    fw_key = st.text_input(
        "FIREWORKS_API_KEY",
        value=get_secret("FIREWORKS_API_KEY", ""),
        type="password",
        help="Required for AI responses"
    )
    brave_key = st.text_input(
        "BRAVE_API_KEY",
        value=get_secret("BRAVE_API_KEY", ""),
        type="password",
        help="Required for web search"
    )
    
    if fw_key:
        os.environ["FIREWORKS_API_KEY"] = fw_key
    if brave_key:
        os.environ["BRAVE_API_KEY"] = brave_key
    
    st.divider()
    
    st.subheader("๐Ÿค– AI Models")
    esm_model = st.text_input(
        "ESM-2 Model",
        value="facebook/esm2_t6_8M_UR50D",
        help="Protein analysis model"
    )
    dna_model = st.text_input(
        "DNA Model", 
        value="bert-base-uncased",
        help="DNA analysis model"
    )
    
    st.divider()
    
    st.subheader("๐Ÿ” Search Settings")
    use_web = st.checkbox("Enable web search", value=True)
    web_results = st.slider("Web results", 1, 10, 5)
    
    st.divider()
    
    st.subheader("๐ŸŽญ Collaboration Mode")
    collab_mode = st.radio(
        "AI Collaboration Type",
        ["full", "quick", "deep"],
        index=0,
        help="Full: Complete collaboration\nQuick: Fast response\nDeep: In-depth analysis"
    )

# Tabs
tab1, tab2, tab3, tab4, tab5 = st.tabs(["๐Ÿ’ฌ Chat", "๐Ÿงฌ Protein", "๐Ÿงฌ DNA", "๐Ÿ“Š Analysis", "โ„น๏ธ About"])

# File upload
with st.expander("๐Ÿ“ Upload Files", expanded=True):
    files = st.file_uploader(
        "Upload text/FASTA/PDF files",
        type=["txt", "fa", "fasta", "csv", "json", "pdf"],
        accept_multiple_files=True,
        help="Support for multiple file types including PDF"
    )
    
    if files:
        docs = []
        for f in files:
            try:
                if f.name.lower().endswith(".pdf"):
                    if not (PDFPLUMBER_AVAILABLE or PYPDF2_AVAILABLE):
                        st.warning(f"โš ๏ธ PDF support requires: pip install pdfplumber")
                        continue
                
                text = load_file_text(f)
                if text:
                    docs.extend(chunk_text(text))
                    st.success(f"โœ… {f.name} loaded ({len(text)} chars)")
            except Exception as e:
                st.error(f"Error reading {f.name}: {e}")
        
        if docs:
            st.session_state.docs = docs
            st.info(f"๐Ÿ“š Total chunks created: {len(docs)}")
            
            if SENTENCE_TRANSFORMERS_AVAILABLE and FAISS_AVAILABLE:
                with st.spinner("Building semantic index..."):
                    index, model = build_index(docs)
                    if index:
                        st.session_state.index = index
                        st.session_state.model = model
                        st.success("โœ… Index built successfully")

# Chat tab with collaborative AI
with tab1:
    st.subheader("๐Ÿ’ฌ Advanced Collaborative Chat")
    
    # ํ˜‘์—… ์‹œ์Šคํ…œ ์„ค๋ช…
    with st.expander("๐ŸŽญ How Collaborative AI Works", expanded=False):
        st.markdown("""
        ### Three AI Experts Work Together:
        
        1. **๐Ÿ” Investigator**: Fact-checks and verifies information
        2. **๐Ÿ“ Supervisor**: Creates structured, comprehensive answers
        3. **โœ… Critic**: Reviews for accuracy and clarity
        4. **๐ŸŽฏ Integrator**: Combines all inputs for the final answer
        
        This system ensures maximum accuracy and comprehensiveness.
        """)
    
    question = st.text_area(
        "Ask about proteins, DNA, or any bioinformatics topic:",
        value="Explain how AlphaFold revolutionized protein structure prediction and its impact on drug discovery.",
        height=100
    )
    
    col1, col2 = st.columns([3, 1])
    with col1:
        answer_button = st.button("๐Ÿš€ Get Collaborative Answer", type="primary", use_container_width=True)
    with col2:
        show_process = st.checkbox("Show process", value=False, help="Display each AI's contribution")
    
    if answer_button:
        if not get_secret("FIREWORKS_API_KEY"):
            st.error("โš ๏ธ Please set FIREWORKS_API_KEY")
        else:
            # Progress tracking
            progress_bar = st.progress(0)
            status_text = st.empty()
            
            with st.spinner("๐Ÿ” Building knowledge base..."):
                status_text.text("Searching sources...")
                progress_bar.progress(10)
                
                context, sources = build_context(
                    question,
                    st.session_state.docs,
                    st.session_state.index,
                    st.session_state.model,
                    use_web,
                    web_results
                )
                
                progress_bar.progress(20)
                status_text.text("Collaborative AI system working...")
                
                # Get collaborative answer
                start_time = time.time()
                collaborative_result = collaborative_answer(
                    question, 
                    context, 
                    collaboration_type=collab_mode
                )
                elapsed_time = time.time() - start_time
                
                progress_bar.progress(100)
                status_text.text(f"โœ… Completed in {elapsed_time:.1f} seconds")
            
            # Display results
            if show_process:
                # Show each AI's contribution
                with st.expander("๐Ÿ” Investigator's Analysis", expanded=False):
                    st.markdown(collaborative_result["investigator"])
                
                with st.expander("๐Ÿ“ Supervisor's Draft", expanded=False):
                    st.markdown(collaborative_result["supervisor"])
                
                with st.expander("โœ… Critic's Review", expanded=False):
                    st.markdown(collaborative_result["critic"])
            
            # Final answer
            st.markdown("### ๐ŸŽฏ Final Integrated Answer")
            st.markdown(collaborative_result["final"])
            
            # Sources
            if sources:
                with st.expander("๐Ÿ“š Sources & References", expanded=False):
                    for s in sources:
                        if s["type"] == "web":
                            st.write(f"- ๐ŸŒ [{s['title']}]({s['url']})")
                        elif s["type"] == "file":
                            st.write(f"- ๐Ÿ“„ File: {s['text'][:100]}... (Score: {s.get('score', 0):.2f})")
            
            # Save to history
            st.session_state.chat_history.append({
                "question": question,
                "answer": collaborative_result["final"],
                "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
                "mode": collab_mode
            })
            
            # Feedback
            col1, col2, col3 = st.columns(3)
            with col1:
                if st.button("๐Ÿ‘ Helpful"):
                    st.success("Thank you for your feedback!")
            with col2:
                if st.button("๐Ÿ‘Ž Not helpful"):
                    st.info("We'll work on improving our responses.")
            with col3:
                if st.button("๐Ÿ’พ Save Answer"):
                    st.download_button(
                        label="Download",
                        data=collaborative_result["final"],
                        file_name=f"bioseq_answer_{time.strftime('%Y%m%d_%H%M%S')}.md",
                        mime="text/markdown"
                    )

# Enhanced Protein tab
with tab2:
    st.subheader("๐Ÿงฌ Advanced Protein Analysis")
    
    with st.expander("๐Ÿ“š Learn About Protein Analysis", expanded=False):
        st.markdown("""
        ### What is Protein Sequence Analysis?
        
        **Proteins** are the workhorses of cells, performing nearly every function necessary for life:
        - ๐Ÿงช **Enzymes**: Catalyze chemical reactions
        - ๐Ÿ›ก๏ธ **Antibodies**: Defend against pathogens
        - ๐Ÿšš **Transporters**: Move molecules across membranes
        - ๐Ÿ“ก **Receptors**: Receive and transmit signals
        
        **ESM-2** (Evolutionary Scale Modeling) is Meta's breakthrough AI that:
        - Trained on 65 million protein sequences
        - Predicts structure and function from sequence alone
        - Enables drug discovery and protein engineering
        """)
    
    protein_seq = st.text_area(
        "Enter protein sequence (single letter amino acid code):",
        value="MKTIIALSYIFCLVFA",
        help="Standard amino acids: A,C,D,E,F,G,H,I,K,L,M,N,P,Q,R,S,T,V,W,Y",
        height=100
    )
    
    # Example sequences
    st.markdown("**๐Ÿงช Example Sequences (Click to copy):**")
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        if st.button("๐Ÿ’‰ Insulin", key="ins"):
            st.code("FVNQHLCGSHLVEALYLVCGERGFFYTPKT", language=None)
    with col2:
        if st.button("๐Ÿ˜Š Endorphin", key="end"):
            st.code("YGGFMTSEKSQTPLVTLFKNAIIKNAYKKGE", language=None)
    with col3:
        if st.button("โค๏ธ Oxytocin", key="oxy"):
            st.code("CYIQNCPLG", language=None)
    with col4:
        if st.button("๐Ÿฆ  Lysozyme", key="lys"):
            st.code("KVFGRCELAAAMKRHGLDNYRGYSLGNWVCAAKFESNFNTQATNR", language=None)
    
    if st.button("๐Ÿ”ฌ Analyze Protein", type="primary", use_container_width=True):
        seq = protein_seq.strip().upper()
        
        # Validation
        valid_aa = set("ACDEFGHIKLMNPQRSTVWY")
        invalid = set(seq) - valid_aa
        if invalid:
            st.warning(f"โš ๏ธ Invalid amino acids detected: {', '.join(invalid)}")
            seq = ''.join([aa for aa in seq if aa in valid_aa])
        
        if len(seq) < 3:
            st.error("Sequence too short. Please enter at least 3 amino acids.")
        else:
            # Basic analysis
            st.markdown("### ๐Ÿ“Š Sequence Statistics")
            col1, col2, col3, col4 = st.columns(4)
            
            with col1:
                st.metric("Length", f"{len(seq)} aa")
                st.metric("Mol. Weight", f"~{len(seq) * 110:.1f} Da")
            
            with col2:
                unique_aa = len(set(seq))
                st.metric("Unique AA", f"{unique_aa}/20")
                charged = sum(1 for aa in seq if aa in "DEKR")
                st.metric("Charged", f"{charged/len(seq)*100:.1f}%")
            
            with col3:
                hydrophobic = sum(1 for aa in seq if aa in "AVILMFYW")
                st.metric("Hydrophobic", f"{hydrophobic/len(seq)*100:.1f}%")
                aromatic = sum(1 for aa in seq if aa in "FWY")
                st.metric("Aromatic", f"{aromatic/len(seq)*100:.1f}%")
            
            with col4:
                basic = sum(1 for aa in seq if aa in "KRH")
                acidic = sum(1 for aa in seq if aa in "DE")
                pi_estimate = 7 + (basic - acidic) * 0.5
                st.metric("pI (est.)", f"~{pi_estimate:.1f}")
                st.metric("Basic/Acidic", f"{basic}/{acidic}")
            
            # Secondary structure prediction (simplified)
            st.markdown("### ๐Ÿ”ฎ Predicted Properties")
            col1, col2 = st.columns(2)
            
            with col1:
                # Helix propensity
                helix_aa = "AELMQKRH"
                helix_score = sum(1 for aa in seq if aa in helix_aa) / len(seq)
                st.metric("ฮฑ-Helix Propensity", f"{helix_score*100:.1f}%")
                
                # Beta propensity
                beta_aa = "FIVWY"
                beta_score = sum(1 for aa in seq if aa in beta_aa) / len(seq)
                st.metric("ฮฒ-Sheet Propensity", f"{beta_score*100:.1f}%")
            
            with col2:
                # Disorder prediction
                disorder_aa = "PESKTQ"
                disorder_score = sum(1 for aa in seq if aa in disorder_aa) / len(seq)
                st.metric("Disorder Tendency", f"{disorder_score*100:.1f}%")
                
                # Solubility estimate
                soluble_score = 100 - (hydrophobic/len(seq)*100)
                st.metric("Solubility Score", f"{soluble_score:.1f}%")
            
            # AI Analysis
            if TORCH_AVAILABLE and TRANSFORMERS_AVAILABLE:
                st.markdown("### ๐Ÿค– AI-Powered Analysis")
                with st.spinner("Running ESM-2 analysis... This may take 10-30 seconds"):
                    result = esm2_embed(seq, esm_model)
                    
                    if "error" in result:
                        st.error(f"Analysis failed: {result['error']}")
                    else:
                        st.success("โœ… AI analysis complete!")
                        
                        col1, col2, col3 = st.columns(3)
                        with col1:
                            st.metric("Embedding Dimension", result['size'])
                        with col2:
                            st.metric("Mean Value", f"{result.get('mean', 0):.3f}")
                        with col3:
                            st.metric("Std Dev", f"{result.get('std', 0):.3f}")
                        
                        # Visualization placeholder
                        st.markdown("**๐ŸŽจ Embedding Visualization:**")
                        st.info("The protein has been encoded into a high-dimensional space where similar proteins cluster together.")
                        
                        # Applications
                        st.markdown("""
                        ### ๐ŸŽฏ Applications of This Analysis:
                        
                        1. **๐Ÿ” Similar Protein Search**: Find proteins with similar functions
                        2. **๐Ÿ’Š Drug Target Identification**: Predict binding sites and interactions
                        3. **๐Ÿงฌ Mutation Impact**: Assess how changes affect protein function
                        4. **๐Ÿ—๏ธ Structure Prediction**: Input for AlphaFold-like systems
                        5. **โš—๏ธ Protein Engineering**: Design improved variants
                        """)
            else:
                st.warning("โš ๏ธ AI models are loading. Please refresh in a moment.")

# Enhanced DNA tab
with tab3:
    st.subheader("๐Ÿงฌ Advanced DNA Analysis")
    
    with st.expander("๐Ÿ“š Learn About DNA Analysis", expanded=False):
        st.markdown("""
        ### Understanding DNA Sequences
        
        **DNA** is the blueprint of life, encoding all genetic information in four bases:
        - **A** (Adenine): Pairs with T
        - **T** (Thymine): Pairs with A  
        - **G** (Guanine): Pairs with C
        - **C** (Cytosine): Pairs with G
        
        **Key Concepts:**
        - **Gene**: A DNA segment that codes for a protein
        - **Promoter**: Controls when genes are turned on/off
        - **Codon**: Three bases that code for one amino acid
        - **GC Content**: Affects stability and gene expression
        
        **DNABERT-2** is an AI model that understands DNA "language" to predict:
        - Gene function
        - Regulatory elements
        - Disease-causing mutations
        - Evolution patterns
        """)
    
    dna_seq = st.text_area(
        "Enter DNA sequence:",
        value="ATGCGATCGTAGC",
        help="Use A, T, G, C for DNA (U will be converted to T for RNA)",
        height=100
    )
    
    # Example sequences
    st.markdown("**๐Ÿงช Example Sequences (Click to analyze):**")
    col1, col2, col3, col4 = st.columns(4)
    with col1:
        if st.button("๐Ÿ“‹ TATA Box", key="tata"):
            st.code("TATAAAAGCGCGCGCG", language=None)
            st.caption("Gene start signal")
    with col2:
        if st.button("๐ŸŽฏ Promoter", key="prom"):
            st.code("TTGACAGGCTAGCTCAGTCCTAGGTATAATGCTAGC", language=None)
            st.caption("Gene control region")
    with col3:
        if st.button("โœ‚๏ธ CRISPR", key="crispr"):
            st.code("GTCACCTCCAATGACTAGGGTGG", language=None)
            st.caption("Gene editing target")
    with col4:
        if st.button("๐Ÿงฌ Telomere", key="telo"):
            st.code("TTAGGGTTAGGGTTAGGG", language=None)
            st.caption("Chromosome end")
    
    if st.button("๐Ÿ”ฌ Analyze DNA", type="primary", use_container_width=True):
        seq = dna_seq.strip().upper().replace("U", "T")
        seq = ''.join(c for c in seq if c in 'ATGC')
        
        if len(seq) < 3:
            st.error("Sequence too short. Please enter at least 3 bases.")
        else:
            # Advanced statistics
            st.markdown("### ๐Ÿ“Š Sequence Analysis")
            
            col1, col2, col3, col4 = st.columns(4)
            
            with col1:
                st.metric("Length", f"{len(seq)} bp")
                st.metric("Size", f"~{len(seq)*660:.0f} Da")
            
            with col2:
                gc = (seq.count("G") + seq.count("C")) / len(seq) * 100
                st.metric("GC Content", f"{gc:.1f}%")
                if gc > 65:
                    st.caption("๐Ÿ”ด Very high")
                elif gc > 55:
                    st.caption("๐ŸŸ  High")
                elif gc < 35:
                    st.caption("๐Ÿ”ต Low")
                elif gc < 25:
                    st.caption("๐ŸŸฃ Very low")
                else:
                    st.caption("๐ŸŸข Normal")
            
            with col3:
                at = 100 - gc
                st.metric("AT Content", f"{at:.1f}%")
                tm = 4 * (seq.count("G") + seq.count("C")) + 2 * (seq.count("A") + seq.count("T"))
                st.metric("Tm (est.)", f"{tm}ยฐC")
            
            with col4:
                cpg = seq.count("CG")
                cpg_ratio = (cpg * len(seq)) / (seq.count("C") * seq.count("G")) if seq.count("C") * seq.count("G") > 0 else 0
                st.metric("CpG Sites", cpg)
                st.metric("CpG O/E", f"{cpg_ratio:.2f}")
            
            # Motif search
            st.markdown("### ๐Ÿ” Regulatory Elements & Motifs")
            
            motifs_found = []
            motif_positions = []
            
            # Extended motif database
            motif_db = {
                "TATA Box": ["TATAAA", "TATAWAW"],
                "CAAT Box": ["CAAT", "CCAAT", "GGCCAATCT"],
                "GC Box": ["GGGCGG", "GGCGGG"],
                "Start Codon": ["ATG"],
                "Stop Codons": ["TAA", "TAG", "TGA"],
                "Kozak Sequence": ["GCCRCCATGG"],
                "Poly-A Signal": ["AATAAA", "ATTAAA"],
                "E-box": ["CANNTG"],
                "CRE": ["TGACGTCA"],
                "NF-ฮบB": ["GGGACTTTCC"]
            }
            
            for motif_name, patterns in motif_db.items():
                for pattern in patterns:
                    # Simple pattern matching (R=A/G, W=A/T, N=any)
                    simple_pattern = pattern.replace("R", "[AG]").replace("W", "[AT]").replace("N", "[ATGC]")
                    import re
                    if re.search(simple_pattern, seq):
                        motifs_found.append(f"โœ… {motif_name}: {pattern}")
                        break
            
            if motifs_found:
                for motif in motifs_found:
                    st.write(motif)
            else:
                st.info("No known regulatory motifs detected")
            
            # Codon analysis
            if len(seq) >= 3:
                st.markdown("### ๐Ÿงฌ Coding Potential Analysis")
                
                col1, col2 = st.columns(2)
                
                with col1:
                    # Reading frames
                    st.markdown("**Open Reading Frames:**")
                    for frame in range(3):
                        frame_seq = seq[frame:]
                        if "ATG" in frame_seq:
                            start_pos = frame_seq.index("ATG") + frame
                            st.write(f"Frame {frame+1}: Start at position {start_pos+1}")
                
                with col2:
                    # Codon usage
                    if len(seq) % 3 == 0:
                        st.markdown("**Codon Statistics:**")
                        codon_count = len(seq) // 3
                        st.metric("Total Codons", codon_count)
                        
                        # Count stops
                        stops = seq.count("TAA") + seq.count("TAG") + seq.count("TGA")
                        st.metric("Stop Codons", stops)
            
            # AI Analysis
            if TORCH_AVAILABLE and TRANSFORMERS_AVAILABLE:
                st.markdown("### ๐Ÿค– AI-Powered Genomic Analysis")
                with st.spinner("Running DNABERT analysis... This may take 10-30 seconds"):
                    result = dna_embed(seq, dna_model)
                    
                    if "error" in result:
                        st.error(f"Analysis failed: {result['error']}")
                    else:
                        st.success("โœ… AI analysis complete!")
                        
                        col1, col2, col3 = st.columns(3)
                        with col1:
                            st.metric("Embedding Dimension", result['size'])
                        with col2:
                            st.metric("k-mer Count", result.get('kmer_count', 'N/A'))
                        with col3:
                            st.metric("Mean Value", f"{result.get('mean', 0):.3f}")
                        
                        st.markdown("""
                        ### ๐ŸŽฏ Applications of DNA Analysis:
                        
                        1. **๐Ÿ”ฌ Gene Discovery**: Identify coding and regulatory regions
                        2. **๐Ÿฅ Disease Diagnosis**: Detect pathogenic mutations
                        3. **โœ‚๏ธ CRISPR Design**: Find optimal gene editing sites
                        4. **๐ŸŒฑ Evolution Studies**: Compare sequences across species
                        5. **๐Ÿ’Š Personalized Medicine**: Tailor treatments to genetic profiles
                        6. **๐Ÿฆ  Pathogen Detection**: Identify viral/bacterial DNA
                        """)
            else:
                st.warning("โš ๏ธ AI models are loading. Please refresh in a moment.")

# Analysis History tab
with tab4:
    st.subheader("๐Ÿ“Š Analysis History & Insights")
    
    if st.session_state.chat_history:
        st.markdown(f"### ๐Ÿ’พ Previous Analyses ({len(st.session_state.chat_history)} total)")
        
        for i, entry in enumerate(reversed(st.session_state.chat_history[-5:])):
            with st.expander(f"๐Ÿ• {entry['timestamp']} - Mode: {entry['mode']}", expanded=False):
                st.markdown("**Question:**")
                st.write(entry['question'])
                st.markdown("**Answer:**")
                st.write(entry['answer'][:500] + "..." if len(entry['answer']) > 500 else entry['answer'])
                
                if st.button(f"View Full", key=f"view_{i}"):
                    st.markdown(entry['answer'])
    else:
        st.info("No analysis history yet. Start by asking a question in the Chat tab!")
    
    # Export options
    if st.session_state.chat_history:
        st.markdown("### ๐Ÿ“ค Export Options")
        col1, col2 = st.columns(2)
        
        with col1:
            if st.button("Export as Markdown"):
                md_content = "\n\n---\n\n".join([
                    f"## {entry['timestamp']}\n\n**Q:** {entry['question']}\n\n**A:** {entry['answer']}"
                    for entry in st.session_state.chat_history
                ])
                st.download_button(
                    "Download MD",
                    md_content,
                    f"bioseq_history_{time.strftime('%Y%m%d')}.md",
                    "text/markdown"
                )
        
        with col2:
            if st.button("Clear History"):
                st.session_state.chat_history = []
                st.rerun()

# Enhanced About tab
with tab5:
    st.subheader("โ„น๏ธ About BioSeq Chat Pro")
    
    st.markdown("""
    ### ๐Ÿš€ Enhanced Features
    
    #### **Collaborative AI System**
    - ๐Ÿ” **Investigator**: Verifies facts and identifies knowledge gaps
    - ๐Ÿ“ **Supervisor**: Creates comprehensive, structured answers
    - โœ… **Critic**: Reviews for accuracy and clarity
    - ๐ŸŽฏ **Integrator**: Synthesizes all inputs into final answer
    
    #### **Technical Improvements**
    - **8000 token responses** for comprehensive answers
    - **Enhanced context building** with semantic search
    - **Multiple collaboration modes** (Full, Quick, Deep)
    - **Scientific source prioritization** in web search
    - **Larger embedding models** for better accuracy
    
    ### ๐Ÿงฌ Supported Analyses
    - **Protein Analysis**: ESM-2 embeddings, property prediction
    - **DNA Analysis**: DNABERT-2/BERT embeddings, motif search
    - **RAG Chat**: Context-aware Q&A with file integration
    - **PDF Support**: Direct analysis of research papers
    
    ### ๐Ÿ“š Models & Technologies
    - **LLM**: Llama 3.1 70B (via Fireworks AI)
    - **Protein**: ESM-2 (Meta/Facebook)
    - **DNA**: DNABERT-2 (Microsoft) / BERT (Google)
    - **Embeddings**: all-mpnet-base-v2 (Sentence Transformers)
    - **Vector Search**: FAISS (Facebook)
    
    ### โš ๏ธ Disclaimer
    This tool is designed for **research and educational purposes only**.
    - Not intended for medical diagnosis or treatment
    - Not validated for clinical use
    - Always consult qualified professionals for medical decisions
    
    ### ๐Ÿ”ง System Status
    """)
    
    # System status with better formatting
    col1, col2 = st.columns(2)
    
    deps_essential = {
        "PyTorch": TORCH_AVAILABLE,
        "Transformers": TRANSFORMERS_AVAILABLE,
        "Sentence Transformers": SENTENCE_TRANSFORMERS_AVAILABLE,
        "FAISS": FAISS_AVAILABLE,
    }
    
    deps_optional = {
        "BioPython": BIOPYTHON_AVAILABLE,
        "Datasets": DATASETS_AVAILABLE,
        "PDF (pdfplumber)": PDFPLUMBER_AVAILABLE,
        "PDF (PyPDF2)": PYPDF2_AVAILABLE
    }
    
    with col1:
        st.markdown("**Essential Components:**")
        for name, available in deps_essential.items():
            if available:
                st.success(f"โœ… {name}")
            else:
                st.error(f"โŒ {name}")
    
    with col2:
        st.markdown("**Optional Components:**")
        for name, available in deps_optional.items():
            if available:
                st.success(f"โœ… {name}")
            else:
                st.warning(f"โš ๏ธ {name}")
    
    # Performance metrics
    if st.session_state.chat_history:
        st.markdown("### ๐Ÿ“ˆ Usage Statistics")
        col1, col2, col3 = st.columns(3)
        with col1:
            st.metric("Total Queries", len(st.session_state.chat_history))
        with col2:
            modes = [h['mode'] for h in st.session_state.chat_history]
            most_used = max(set(modes), key=modes.count) if modes else "N/A"
            st.metric("Most Used Mode", most_used)
        with col3:
            avg_length = sum(len(h['answer']) for h in st.session_state.chat_history) / len(st.session_state.chat_history)
            st.metric("Avg Answer Length", f"{avg_length:.0f} chars")
    
    st.markdown("""
    ---
    ### ๐Ÿ“ž Support & Feedback
    - Report issues or suggest features
    - Contribute to development
    - Share your research results
    
    **Version**: 2.0.0 Pro | **Last Updated**: 2025
    """)