File size: 59,234 Bytes
1699569
 
6ce67d2
1699569
575134c
 
1699569
 
6ce67d2
e5a12b8
 
 
62faff0
 
2267bcd
66e83e0
575134c
5e8245c
b96b5eb
e36ad26
7978486
e36ad26
 
c6e3011
5e8245c
 
b96b5eb
5e8245c
b96b5eb
 
 
 
 
 
 
 
 
5e8245c
b96b5eb
 
5e8245c
 
b96b5eb
1699569
62faff0
 
 
 
 
 
 
f21967a
a6d026f
f192d73
62faff0
3559da9
f2f40f0
f192d73
afb8bf9
62faff0
3559da9
f2f40f0
afb8bf9
a6d026f
f21967a
2bba935
e36ad26
6ce67d2
7978486
e80527e
 
7978486
6ce67d2
 
 
 
7978486
e80527e
e36ad26
7978486
e80527e
7978486
6ce67d2
c6e3011
e48b5b5
7978486
6ce67d2
 
 
 
 
 
 
 
 
 
 
 
 
 
e36ad26
8d11e9c
1604b8a
6ce67d2
 
 
 
 
 
 
 
 
6f8b956
0bb1f3c
6ce67d2
 
 
0bb1f3c
6ce67d2
e36ad26
 
 
 
7978486
 
e36ad26
7978486
8d11e9c
 
 
 
1604b8a
 
 
 
6ce67d2
105ed33
62faff0
2bba935
b2912c4
89540ca
6ce67d2
 
 
 
 
 
1699569
e48b5b5
2267bcd
7978486
 
62faff0
e48b5b5
 
 
f21967a
8d11e9c
 
 
 
 
 
 
 
e32c352
e80527e
 
 
 
 
8d11e9c
 
 
 
6ce67d2
 
8d11e9c
6ce67d2
 
8d11e9c
 
 
 
 
 
 
 
 
6ce67d2
7978486
e32c352
 
 
8d11e9c
f67304b
8d11e9c
 
 
 
 
c5c0a51
8d11e9c
 
8eb1090
029e89d
 
 
 
 
6ce67d2
8d11e9c
 
6ce67d2
575134c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
029e89d
 
 
 
a363af1
575134c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d11e9c
 
 
 
 
 
6ce67d2
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
6ce67d2
8d11e9c
6ce67d2
8d11e9c
6ce67d2
8d11e9c
 
f67304b
8d11e9c
 
 
 
7978486
 
 
 
 
8d11e9c
6ce67d2
8d11e9c
 
6ce67d2
8d11e9c
 
 
6ce67d2
8d11e9c
 
7978486
6ce67d2
8d11e9c
 
 
 
 
 
575134c
 
 
 
 
 
 
 
 
 
 
6ce67d2
575134c
 
 
 
6ce67d2
 
575134c
 
 
6ce67d2
575134c
 
6ce67d2
575134c
 
 
 
6ce67d2
575134c
 
 
 
 
6ce67d2
575134c
 
 
6ce67d2
575134c
 
 
 
6ce67d2
575134c
 
 
 
 
6ce67d2
575134c
 
 
6ce67d2
575134c
f67304b
6ce67d2
 
8d11e9c
 
 
 
 
 
 
575134c
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314d3c7
029e89d
 
 
 
 
 
575134c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
029e89d
3501b81
575134c
a363af1
575134c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575134c
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ce67d2
 
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575134c
 
 
 
 
 
 
 
 
 
 
 
8d11e9c
 
575134c
 
 
8d11e9c
575134c
 
 
8d11e9c
575134c
 
8d11e9c
575134c
 
 
 
8d11e9c
575134c
 
 
 
 
 
8d11e9c
575134c
 
 
 
 
8d11e9c
575134c
 
 
 
8d11e9c
575134c
 
 
 
 
8d11e9c
575134c
 
 
8d11e9c
575134c
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b2cc15
6ce67d2
ae598a1
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575134c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d11e9c
 
575134c
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae598a1
8d11e9c
d2396af
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
575134c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d11e9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ce67d2
8eb1090
62faff0
6ce67d2
62faff0
fb7bdf2
 
 
 
 
62faff0
fb7bdf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2267bcd
 
8eb1090
2267bcd
6ce67d2
2267bcd
6ce67d2
2267bcd
6ce67d2
8eb1090
66e83e0
40e9078
 
 
 
 
 
527140e
 
 
 
 
 
 
 
 
40e9078
575134c
6ce67d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2f40f0
 
ff86fbf
 
66e83e0
 
 
 
 
 
 
 
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
import streamlit as st
import time
import concurrent.futures
import json

# import tensorflow
from gensim.models import Word2Vec
import pandas as pd
import threading
import matplotlib.pyplot as plt
import squarify
import numpy as np
import re
import urllib.request
import random
import plotly.express as px
import plotly.graph_objs as go
from streamlit.components.v1 import html

st.set_page_config(page_title="OncoDigger", page_icon=":microscope:", layout="wide",  # centered
                   initial_sidebar_state="auto",
                   menu_items={'About': "OncoDigger is a Natural Language Processing (NLP) that harnesses Word2Vec to mine"
                         " insight from pubmed abstracts. Created by Jimmie E. Fata, PhD, [email protected]"})



analytics_code = '''
<head>
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-EKFSW65C2P"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-EKFSW65C2P');
</script>
</head>
'''

html(analytics_code, height=0)


# Define the HTML and CSS styles
st.markdown("""
<style>
    [data-testid=stSidebar] {
        background-color: #99CCFF;
    }
</style>
""", unsafe_allow_html=True)
st.markdown("""
    <style>
    body {
        background-color: #CCFFFF;
        # color: #ffffff;
        # font-size: 1px
    }
    .stApp {
        background-color: #CCFFFF;
        # color: #ffffff;
        # font-size: 1px
    }
    </style>
    """, unsafe_allow_html=True)

st.header(":red[*O*]nco:red[*D*]igger")

st.subheader(
    "A web app designed to explore massive amounts of :red[*PubMed abstracts*] for a deeper understanding of your research. Results are driven "
    "by Machine Learning and Natural Language Processing algorithms, which allow you to scan and mine information from hundreds of thousands of abstracts in seconds.")


def custom_subheader(text, identifier, font_size):
    st.markdown(f"<h3 id='{identifier}' style='font-size: {font_size}px;'>{text}</h3>", unsafe_allow_html=True)


custom_subheader("To begin, simply select a cancer corpus from the left sidebar and enter a keyword "
                 "you wish to explore within the corpus. OncoDigger will determine the top words, "
                 "genes, drugs, phytochemicals, and compounds that are contextually and semantically related "
                 "to your input, both directly and indirectly. Dive in and enjoy the exploration!",
                 "unique-id", 18)

st.markdown("---")

# Define the correct password
# CORRECT_PASSWORD = "123"

# Define a function to check if the password is correct
# def authenticate(password):
#     if password == CORRECT_PASSWORD:
#         return True
#     else:
#         return False
#
# # Create a Streamlit input field for the password
# password = st.text_input("Enter password:", type="password")
#
# # If the password is correct, show the app content
# if authenticate(password):
opt = st.sidebar.radio("Select a PubMed Corpus", options=('Breast Cancer corpus', 'Lung Cancer corpus',
                                                          'Skin Cancer corpus', 'Colorectal Cancer corpus',
                                                          'Prostate Cancer corpus', 'Lymphoma Cancer corpus'))
# if opt == "Clotting corpus":
#     model_used = ("pubmed_model_clotting")
#     num_abstracts = 45493
#     database_name = "Clotting"
# if opt == "Neuroblastoma corpus":
#     model_used = ("pubmed_model_neuroblastoma")
#     num_abstracts = 29032
#     database_name = "Neuroblastoma"
if opt == "Breast Cancer corpus":
    model_used = ("breast_cancer_pubmed_model")
    num_abstracts = 204381
    database_name = "Breast_cancer"
if opt == "Lung Cancer corpus":
    model_used = ("lung_cancer_pubmed_model")
    num_abstracts = 143886
    database_name = "Lung_cancer"
if opt == "Colorectal Cancer corpus":
    model_used = ("colorectal_cancer_pubmed_model")
    num_abstracts = 140000
    database_name = "Colorectal_cancer"
if opt == "Prostate Cancer corpus":
    model_used = ("prostate_cancer_pubmed_model")
    num_abstracts = 89782
    database_name = "Prostate_cancer"
if opt == "Skin Cancer corpus":
    model_used = ("skin_cancer_pubmed_model")
    num_abstracts = 176568
    database_name = "Skin_cancer"
if opt == "Lymphoma corpus":
    model_used = ("lymphoma_cancer_pubmed_model")
    num_abstracts = 79000
    database_name = "Lymphoma_cancer"

st.header(f":blue[{database_name} Pubmed corpus.]")
text_input_value = st.text_input(f"Enter one term to search within the {database_name} corpus")
query = text_input_value
query = query.lower()
query = query.strip()  # This line will remove any leading or trailing spaces
query = re.sub("[,.?!&*;:]", "", query)
query = re.sub(" ", "-", query)
# matches = [" "]
# if any([x in query for x in matches]):
#     st.write("Please only enter one term or a term without spaces")
# # query = input ("Enter your keyword(s):")
if query:
    bar = st.progress(0)
    time.sleep(.05)
    st.caption(
        f"Searching {num_abstracts} {database_name} PubMed primary abstracts covering 1990-2022 (Reviews not included)")

    for i in range(10):
        bar.progress((i + 1) * 10)
        time.sleep(.1)

    try:
        model = Word2Vec.load(f"{model_used}")  # you can continue training with the loaded model!
        words = list(model.wv.key_to_index)
        X = model.wv[model.wv.key_to_index]
        # print(model.wv['bfgf'])
        model2 = model.wv[query]
        # print(model.wv.similar_by_word('bfgf', topn=50, restrict_vocab=None))
        df = pd.DataFrame(X)

        if 'melanin' in model.wv.key_to_index:
            print("The term 'melanin' is present in the model.")
        else:
            print("The term 'melanin' is not present in the model.")

        def get_compound_ids(compound_names):
            with concurrent.futures.ThreadPoolExecutor() as executor:
                compound_ids = list(executor.map(get_compound_id, compound_names))
            return compound_ids


        import requests


        def get_compound_id(compound_name):
            url = f"http://rest.kegg.jp/find/compound/{compound_name}"
            response = requests.get(url)
            if response.status_code == 200:
                result = response.text.split('\n')
                if result[0]:
                    compound_id = result[0].split('\t')[0]
                    return compound_id
            return None


    # except:
    #     st.error("Term occurrence is too low - please try another term")
    #     st.stop()
        st.markdown("---")

        try:
            table = model.wv.most_similar_cosmul(query, topn=10000)
            table = (pd.DataFrame(table))
            table.index.name = 'Rank'
            table.columns = ['Word', 'SIMILARITY']

            pd.set_option('display.max_rows', None)
            table2 = table.copy()

            st.markdown(
                f"<h2 style='text-align: center; font-family: Arial; font-size: 20px; font-weight: bold;'>"
                f"Top <span style='color:red; font-style: italic;'>10000</span> words in an interactive embedding map most similar to <span style='color:red; font-style: italic;'>{query}</span> in <span style='color:red; font-style: italic;'>{database_name}</span> "
                f"PubMed corpus: Zoom in to the black diamond to find <span style='color:red; font-style: italic;'>{query}</span></h2>",
                unsafe_allow_html=True)

            # Set the max number of words to display
            value_word = min(100, len(table2))

            try:
                value_word = min(50, len(table2))
                # Get the top 50 similar words to the query
                top_words = model.wv.most_similar_cosmul(query, topn=10000)
                words = [word for word, sim in top_words]
                words = [word.replace(' ', '-') for word in words]
                sims = [sim for word, sim in top_words]
                X_top = model.wv[words]

                # Compute similarities between query and top 100 words
                sims_query_top = sims  # print(sims_query_top)
            except Exception as e:
                print("Error:", e)

            # Generate a 2D scatter plot of word embeddings using Plotly
            fig = px.scatter(x=X_top[:, 0], y=X_top[:, 1], color=sims_query_top, color_continuous_scale="RdYlGn", )

            # Change background color to black
            fig.update_layout(plot_bgcolor='#CCFFFF')

            # Change color of text to white
            fig.update_layout(xaxis=dict(gridcolor='#CCFFFF', color='blue'),
                              yaxis=dict(gridcolor='#CCFFFF', color='blue'))

            # fig.update_traces(hovertemplate='<b>%{hovertext}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>')
            # fig.update_layout(title=dict(
                # text=f"Top 10000 words in an interactive embedding map for {query} in {database_name} PubMed corpus"
                #      f": Zoom in to the black diamond to find {query}", x=0.5, y=1, xanchor='center', yanchor='top',
                # font=dict(color='black')))
            fig.update_coloraxes(colorbar_title=f"Similarity with {query}")

            # Represent query as a large red diamond
            fig.add_trace(go.Scatter(x=[model.wv[query][0]], y=[model.wv[query][1]], mode='markers',
                                     marker=dict(size=12, color='black', symbol='diamond'), name=query, hovertext=query,
                                     showlegend=False))

            # Add label for the query above the diamond
            fig.add_trace(go.Scatter(x=[model.wv[query][0]], y=[model.wv[query][1]], mode='text', text=[query],
                                     textposition='top right', textfont=dict(color='blue', size=10), hoverinfo='none',
                                     showlegend=False))

            # Add circles for the top 50 similar words
            fig.add_trace(go.Scatter(x=X_top[:, 0], y=X_top[:, 1], mode='markers',
                                     marker=dict(size=2, color=sims_query_top, colorscale='RdYlGn', symbol='circle'),
                                     text=words, customdata=sims, name=''))

            fig.update(layout_coloraxis_showscale=True)
            fig.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
            fig.update_annotations(visible=False)

            st.plotly_chart(fig, use_container_width=True)

            st.markdown(
            f"<b><p style='font-family: Arial; font-size: 20px; font-style: Bold;'>Top <span style='color:red; font-style: italic;'>{value_word} "
            f"</span>words contextually and semantically similar to "
            f"<span style='color:red; font-style: italic;'>{query} </span>within the <span style='color:red; font-style: italic;'>{database_name}</span> corpus. "
            f"Click on the squares to expand and also the PubMed and Wikipedia links for more word information</span></p></b>",
            unsafe_allow_html=True)

            short_table = table2.head(value_word).round(2)
            short_table.index += 1
            short_table.index = (1 / short_table.index) * 10
            sizes = short_table.index.tolist()

            short_table.set_index('Word', inplace=True)
            table2["SIMILARITY"] = 'Similarity Score ' + table2.head(value_word)["SIMILARITY"].round(2).astype(str)
            rank_num = list(short_table.index.tolist())

            df = short_table


            df['text'] = short_table.index
            df['href'] = [f'https://pubmed.ncbi.nlm.nih.gov/?term={database_name}%5Bmh%5D+NOT+review%5Bpt%5D' \
                      '+AND+english%5Bla%5D+AND+hasabstract+AND+1990:2022%5Bdp%5D+AND+' + c for c in short_table.index]
            df['href2'] = [f'https://en.wikipedia.org/wiki/' + c for c in short_table.index]

            df.loc[:, 'database'] = database_name

            fig = px.treemap(df, path=[short_table.index], values=sizes, custom_data=['href', 'text', 'database', 'href2'],
                            hover_name=(table2.head(value_word)['SIMILARITY']))

            fig.update(layout_coloraxis_showscale=False)
            fig.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
            fig.update_annotations(visible=False)
            fig.update_traces(marker=dict(cornerradius=5), root_color="#CCFFFF", hovertemplate=None,
                          hoverlabel_bgcolor="lightblue", hoverlabel_bordercolor="#000000", texttemplate="<br><span "
                                                                                                         "style='font-family: Arial; font-size: 20px;'>%{customdata[1]}<br><br>"
                                                                                                         "<a href='%{customdata[0]}'>PubMed"
                                                                                                         "</a><br><br><a href='%{customdata[3]}'>Wikipedia"
                                                                                                         "</span></a>")
            fig.update_layout(uniformtext=dict(minsize=15), treemapcolorway=["lightgreen"])

            # st.pyplot(fig2)
            st.plotly_chart(fig, use_container_width=True)

            # st.caption(
            #     "Gene designation and database provided by HUGO Gene Nomenclature Committee (HGNC): https://www.genenames.org/")
            # st.caption("Gene designation add in exceptions [p21, p53, her2, her3]")

            csv = table2.head(value_word).to_csv().encode('utf-8')
            st.download_button(label=f"download top {value_word} words (csv)", data=csv,
                           file_name=f'{database_name}_words.csv', mime='text/csv')

        except:
            st.warning(
                f"This selection exceeds the number of similar words related to {query} within the {database_name} corpus, please choose a lower number")
    except KeyError:
        st.warning(
            "This word is not found in the corpus, it could be because it is not spelled correctly or could be that it does not have enough representation within the corpus, please try again")



    # try:
    #     value_word = min(50, len(table2))
    #     # Get the top 50 similar words to the query
    #     top_words = model.wv.most_similar_cosmul(query, topn=value_word)
    #     words = [word for word, sim in top_words]
    #     words = [word.replace(' ', '-') for word in words]
    #     sims = [sim for word, sim in top_words]
    #     X_top = model.wv[words]
    #
    #     # Compute similarities between query and top 100 words
    #     sims_query_top = sims  # print(sims_query_top)
    # except Exception as e:
    #     print("Error:", e)
    #
    #
    # # Generate a 3D scatter plot of word embeddings using Plotly
    # fig = px.scatter_3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], text=words, color=sims_query_top,
    #                     color_continuous_scale="RdYlGn", hover_name=words, hover_data={"color": sims_query_top})
    #
    # # Change background color to black
    # fig.update_layout(scene=dict(bgcolor='#CCFFFF'))
    #
    # # Change color of text to white
    # fig.update_layout(scene=dict(xaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
    #                              yaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
    #                              zaxis=dict(backgroundcolor='#CCFFFF', color='blue')))
    #
    # fig.update_traces(hovertemplate='<b>%{hovertext}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>')
    # fig.update_layout(title=dict(text=f"Word embedding map for {query} in {database_name} PubMed corpus", x=0.5, y=0.95,
    #                              xanchor='center', yanchor='top', font=dict(color='black')),
    #                   scene=dict(xaxis_title="Dimension 1", yaxis_title="Dimension 2", zaxis_title="Dimension 3"))
    # fig.update_coloraxes(colorbar_title="Similarity with query")
    #
    # # Represent query as a large red diamond
    # fig.add_trace(go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='markers',
    #                            marker=dict(size=7, color='black', symbol='diamond'), name=query, hovertext=query, showlegend=False))
    #
    # # Add label for the query above the diamond
    # fig.add_trace(
    #     go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='text', text=[query],
    #                  textposition='bottom center', textfont=dict(color='blue', size=10), hoverinfo='none', showlegend=False))
    #
    # # Add circles for the top 50 similar words
    # fig.add_trace(go.Scatter3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], mode='markers',
    #                            marker=dict(size=2, color=sims_query_top, colorscale='RdYlGn', symbol='circle'),
    #                            hovertemplate='<b>%{text}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>',
    #                            text=words, customdata=sims, name=''))
    #
    # fig.update(layout_coloraxis_showscale=True)
    # fig.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
    # fig.update_annotations(visible=False)
    #
    # st.plotly_chart(fig, use_container_width=True)

    st.markdown("---")

    try:
        df1 = table.copy()
        df2 = pd.read_csv('Human Genes.csv')
        m = df1.Word.isin(df2.symbol)
        df1 = df1[m]
        df1.rename(columns={'Word': 'Genes'}, inplace=True)
        df_len = len(df1)
        # print(len(df1))

        # st.markdown(f"<b><p style='font-family: Arial; font-size: 20px;'>Populate a treemap to visualize "
        #             f"<span style='color:red; font-style: italic;'>proteins</span> contextually "
        #             f"and semantically similar to <span style='color:red; font-style: italic;'>{query}</span> "
        #             f"within the <span style='color:red; font-style: italic;'>{database_name}</span> corpus.</p></b>",
        #     unsafe_allow_html=True)

        # Set the number of proteins to display
        value_gene = min(df_len, 100)

        st.markdown(
            f"<b><p style='font-family: Arial; font-size: 20px; font-style: Bold;'>Top <span style='color:red; font-style: italic;'>{value_gene} "
            f"</span>human genes contextually and semantically similar to "
            f"<span style='color:red; font-style: italic;'>{query}  </span>within the <span style='color:red; font-style: italic;'>{database_name} </span>corpus. Click on the squares to expand and also the Pubmed and GeneCard links for more gene information</span></p></b>",
            unsafe_allow_html=True)

        df11 = df1.head(value_gene).copy()

        df11.index = (1 / df11.index) * 10000
        sizes = df11.index.tolist()

        df11.set_index('Genes', inplace=True)

        df4 = df1.copy()
        # print(df4.head(10))
        df4["SIMILARITY"] = 'Similarity Score ' + df4.head(value_gene)["SIMILARITY"].round(2).astype(str)
        df4.reset_index(inplace=True)
        # df4 = df4.rename(columns={'Protein': 'symbol2'})
        # print(df4)
        # # Use df.query to get a subset of df1 based on ids in df2
        # subset = df4.head(value_gene).query('symbol2 in @df2b.symbol2')
        # # Use merge to join the two DataFrames on id
        # result = pd.merge(subset, df2b, on='symbol2')
        # print(result)
        if value_gene <= df_len:
            # Define the `text` column for labels and `href` column for links
            df11['text'] = df11.index
            df11['href'] = [f'https://pubmed.ncbi.nlm.nih.gov/?term={database_name}%5Bmh%5D+NOT+review%5Bpt%5D' \
                            '+AND+english%5Bla%5D+AND+hasabstract+AND+1990:2022%5Bdp%5D+AND+' + c for c in df11['text']]
            df11['href2'] = [f'https://www.genecards.org/cgi-bin/carddisp.pl?gene=' + c for c in df11['text']]
            assert isinstance(df11, object)
            df11['database'] = database_name

            # df11['name'] = [c for c in result['Approved name']]

            # Create the treemap using `px.treemap`
            fig = px.treemap(df11, path=[df11['text']], values=sizes, custom_data=['href', 'database', 'href2', 'text'],
                             hover_name=(df4.head(value_gene)['SIMILARITY']))

            fig.update(layout_coloraxis_showscale=False)
            fig.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
            fig.update_annotations(visible=False)
            fig.update_traces(marker=dict(cornerradius=5), root_color="#CCFFFF", hovertemplate=None,
                              hoverlabel_bgcolor="lightblue", hoverlabel_bordercolor="#000000",
                              texttemplate="<span style='font-family: Arial; font-size: 20px;'>%{customdata[3]}<br><br>"
                                           "<a href='%{customdata[0]}'>PubMed"
                                           "</a><br><br><a href='%{customdata[2]}'>GeneCard"
                                           "</span></a>")
            fig.update_layout(uniformtext=dict(minsize=15), treemapcolorway=["LightPink"])
            # # display the treemap in Streamlit
            # with treemap2:

            # st.pyplot(fig2)
            st.plotly_chart(fig, use_container_width=True)

            # st.caption(
            #         "Gene designation and database provided by KEGG homo sapien gene list: https://rest.kegg.jp/list/hsa")
            # st.caption("Gene information provided by GeneCards: https://www.genecards.org//")
            st.caption(
                "Human gene designation and database provided by HUGO Gene Nomenclature Committee (HGNC): https://www.genenames.org/")
            st.caption("Gene designation add in exceptions [p21, p53, her2, her3]")
            st.caption("Gene information provided by GeneCards: https://www.genecards.org//")

            csv = df1.head(value_gene).to_csv().encode('utf-8')
            st.download_button(label=f"download top {value_gene} genes (csv)", data=csv,
                               file_name=f'{database_name}_genes.csv', mime='text/csv')


        else:
            st.warning(
                f"This selection exceeds the number of similar proteins related to {query} within the {database_name} corpus, please choose a lower number")
        value_gene = min(df_len, 50)
        st.markdown(
            f"<h2 style='text-align: center; font-family: Arial; font-size: 20px; font-weight: bold;'>3D interactive "
            f"gene embedding map for <span style='color:red; font-style: italic;'>{value_gene}</span> genes most similar "
            f"with <span style='color:red; font-style: italic;'>{query}</span> in <span style='color:red; font-style: italic;'>{database_name}</span> PubMed corpus</h2>",
            unsafe_allow_html=True)

        try:
            # Get the top 50 similar genes to the query
            value_gene = min(df_len, 50)
            top_words = model.wv.most_similar_cosmul(query, topn=value_gene)
            words = df11.head(value_gene).index
            words = [word.replace(' ', '-') for word in words]
            # print(words)
            sims = df4.head(value_gene)["SIMILARITY"].tolist()
            # print(sims)
            X_top = model.wv[words]  # print(X_top)
        except Exception as e:
            print("Error:", e)


        # Remove the text "Similarity Score" from each element in the sims list
        sims_query_top = [float(sim.split()[-1]) for sim in sims]
        # print(sims_query_top)

        # Generate a 3D scatter plot of word embeddings using Plotly
        fig2 = px.scatter_3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], text=words, color=sims_query_top,
                                 color_continuous_scale="RdYlGn", hover_name=words,
                                 hover_data={"color": sims_query_top})

        # Change background color to black
        fig2.update_layout(scene=dict(bgcolor='#CCFFFF'))

        # Change color of text to white
        fig2.update_layout(scene=dict(xaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
                                          yaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
                                          zaxis=dict(backgroundcolor='#CCFFFF', color='blue')))

        fig2.update_traces(
                hovertemplate='<b>%{hovertext}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>')
        fig2.update_layout(
                title=dict(text=f"", x=0.5, y=0.95,
                           xanchor='center', yanchor='top', font=dict(color='black')),
                scene=dict(xaxis_title="Dimension 1", yaxis_title="Dimension 2", zaxis_title="Dimension 3"))
        fig2.update_coloraxes(colorbar_title=f"Similarity with {query}")

        # Represent query as a large red diamond
        fig2.add_trace(
                go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='markers',
                             marker=dict(size=7, color='black', symbol='diamond'), name=query, hovertext=query,
                             showlegend=False))

        # Add label for the query above the diamond
        fig2.add_trace(
                go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='text',
                             text=[query], textposition='bottom center', textfont=dict(color='blue', size=10),
                             hoverinfo='none', showlegend=False))

        # Add circles for the top 50 similar words
        fig2.add_trace(go.Scatter3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], mode='markers',
                                        marker=dict(size=2, color=sims_query_top, colorscale='RdYlGn', symbol='circle'),
                                        hovertemplate='<b>%{text}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>',
                                        text=words, customdata=sims, name=''))

        fig2.update(layout_coloraxis_showscale=True)
        fig2.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
        fig2.update_annotations(visible=False)

        st.plotly_chart(fig2, use_container_width=True)

        st.markdown("---")
        # print()
        # print("Human genes similar to " + str(query))
        df1 = table.copy()
        df2 = pd.read_csv('kegg_drug_list_lowercase.csv')
        m = df1.Word.isin(df2.drugs)
        df1 = df1[m]
        df1.rename(columns={'Word': 'Drugs'}, inplace=True)
        df_len = len(df1)
        # print(len(df1))
        # df1["Human Gene"] = df1["Human Gene"].str.upper()
        # print(df1.head(50))
        # print()
        # df1.head(50).to_csv("clotting_sim2.csv", index=True, header=False)
        # time.sleep(2)
        # Create the slider with increments of 5 up to 100

        # Remove the slider and set the value_compound to the minimum of the number of rows in the dataframe and 100
        value_drug = min(df1.shape[0], 100)
        # print(value_drug)
        # st.markdown(f"<b><p style='font-family: Arial; font-size: 20px;'>Visualize "
        #             f"<span style='color:red; font-style: italic;'>KEGG compounds</span> contextually "
        #             f"and semantically similar to <span style='color:red; font-style: italic;'>{query}</span> "
        #             f"within the <span style='color:red; font-style: italic;'>{database_name}</span> corpus.</p></b>",
        #     unsafe_allow_html=True)

        st.markdown(
            f"<b><p style='font-family: Arial; font-size: 20px; font-style: Bold;'>Top <span style='color:red; font-style: italic;'>{value_drug} "
            f"</span>Drugs contextually and semantically similar to "
            f"<span style='color:red; font-style: italic;'>{query}</span> within the <span style='color:red; font-style: italic;'>{database_name}</span> corpus. Click on the squares to expand and the Pubmed and Wikipedia links for more compound information</span></p></b>",
            unsafe_allow_html=True)

        df13 = df1.head(value_drug).copy()

        df13.index = (1 / df13.index) * 10000
        sizes = df13.index.tolist()

        df13.set_index('Drugs', inplace=True)

        df6 = df1.copy()
        # print(df4.head(10))
        df6["SIMILARITY"] = 'Similarity Score ' + df6.head(value_drug)["SIMILARITY"].round(2).astype(str)
        df6.reset_index(inplace=True)
        # df4 = df4.rename(columns={'Protein': 'symbol2'})
        # print(df4)
        # # Use df.query to get a subset of df1 based on ids in df2
        # subset = df4.head(value_gene).query('symbol2 in @df2b.symbol2')
        # # Use merge to join the two DataFrames on id
        # result = pd.merge(subset, df2b, on='symbol2')
        # print(result)
        if value_drug <= df_len:
            # Define the `text` column for labels and `href` column for links
            # Reset the index
            df13.reset_index(inplace=True)

            # Replace hyphens with spaces in the 'text' column
            df13['Drugs'] = df13['Drugs'].str.replace('-', ' ')

            # Set the 'text' column back as the index
            df13.set_index('Drugs', inplace=True)
            df13['text'] = df13.index
            df13['href'] = [f'https://pubmed.ncbi.nlm.nih.gov/?term={database_name}%5Bmh%5D+NOT+review%5Bpt%5D' \
                            '+AND+english%5Bla%5D+AND+hasabstract+AND+1990:2022%5Bdp%5D+AND+' + c for c in df13['text']]
            df13['href2'] = [f'https://en.wikipedia.org/wiki/' + c for c in df13['text']]
            assert isinstance(df13, object)
            df13['database'] = database_name

            # df11['name'] = [c for c in result['Approved name']]

            # Create the treemap using `px.treemap`
            fig = px.treemap(df13, path=[df13['text']], values=sizes, custom_data=['href', 'database', 'href2', 'text'],
                             hover_name=(df6.head(value_drug)['SIMILARITY']))

            fig.update(layout_coloraxis_showscale=False)
            fig.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
            fig.update_annotations(visible=False)
            fig.update_traces(marker=dict(cornerradius=5), root_color="#CCFFFF", hovertemplate=None,
                              hoverlabel_bgcolor="lightblue", hoverlabel_bordercolor="#000000",
                              texttemplate="<span style='font-family: Arial; font-size: 20px;'>%{customdata[3]}<br><br>"
                                           "<a href='%{customdata[0]}'>PubMed"
                                           "</a><br><br><a href='%{customdata[2]}'>Wikipedia"
                                           "</span></a>")
            fig.update_layout(uniformtext=dict(minsize=15), treemapcolorway=["Thistle"])
            # # display the treemap in Streamlit
            # with treemap2:

            # st.pyplot(fig2)
            st.plotly_chart(fig, use_container_width=True)

            st.caption("Drug designation and database provided by KEGG: https://www.kegg.jp/kegg/drug/")

            csv = df1.head(value_drug).to_csv().encode('utf-8')
            st.download_button(label=f"download top {value_drug} drugs (csv)", data=csv,
                               file_name=f'{database_name}_drugs.csv', mime='text/csv')


        else:
            st.warning(
                f"This selection exceeds the number of similar drugs related to {query} within the {database_name} corpus, please choose a lower number")
        # try:
        #     value_drug = min(df_len, 50)
        #     top_words = model.wv.most_similar_cosmul(query, topn=value_drug)
        #     # print(top_words)
        #     words = df13.head(value_drug).index
        #     words = [word.replace(' ', '-') for word in words]
        #     # print(words)
        #     sims = df6.head(value_drug)["SIMILARITY"].tolist()
        #     # print(sims)
        #     X_top = model.wv[words]
        # except Exception as e:
        #     print("Error:", e)
        #
        #
        # # Remove the text "Similarity Score" from each element in the sims list
        # sims_query_top = [float(sim.split()[-1]) for sim in sims]
        # # print(sims_query_top)
        #
        # # Generate a 3D scatter plot of word embeddings using Plotly
        # fig4 = px.scatter_3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], text=words, color=sims_query_top,
        #                      color_continuous_scale="RdYlGn", hover_name=words, hover_data={"color": sims_query_top})
        #
        # # Change background color to black
        # fig4.update_layout(scene=dict(bgcolor='#CCFFFF'))
        #
        # # Change color of text to white
        # fig4.update_layout(scene=dict(xaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
        #                               yaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
        #                               zaxis=dict(backgroundcolor='#CCFFFF', color='blue')))
        #
        # fig4.update_traces(hovertemplate='<b>%{hovertext}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>')
        # fig4.update_layout(
        #     title=dict(text=f"Word embedding map for {query} in {database_name} PubMed corpus", x=0.5, y=0.95,
        #                xanchor='center', yanchor='top', font=dict(color='black')),
        #     scene=dict(xaxis_title="Dimension 1", yaxis_title="Dimension 2", zaxis_title="Dimension 3"))
        # fig4.update_coloraxes(colorbar_title="Similarity with query")
        #
        # # Represent query as a large red diamond
        # fig4.add_trace(
        #     go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='markers',
        #                  marker=dict(size=7, color='black', symbol='diamond'), name=query, hovertext=query,
        #                  showlegend=False))
        #
        # # Add label for the query above the diamond
        # fig4.add_trace(go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='text',
        #                             text=[query], textposition='bottom center', textfont=dict(color='blue', size=10),
        #                             hoverinfo='none', showlegend=False))
        #
        # # Add circles for the top 50 similar words
        # fig4.add_trace(go.Scatter3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], mode='markers',
        #                             marker=dict(size=2, color=sims_query_top, colorscale='RdYlGn', symbol='circle'),
        #                             hovertemplate='<b>%{text}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>',
        #                             text=words, customdata=sims, name=''))
        #
        # fig4.update(layout_coloraxis_showscale=True)
        # fig4.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
        # fig4.update_annotations(visible=False)
        #
        # st.plotly_chart(fig4, use_container_width=True)
        # st.markdown("---")

        st.markdown("---")
        # print()
        # print("Human genes similar to " + str(query))
        df1 = table.copy()
        df2 = pd.read_csv('phytochemicals.csv')
        m = df1.Word.isin(df2.phyto)
        df1 = df1[m]
        df1.rename(columns={'Word': 'Phytochemical'}, inplace=True)
        df_len = len(df1)
        # print(len(df1))
        # df1["Human Gene"] = df1["Human Gene"].str.upper()
        # print(df1.head(50))
        # print()
        # df1.head(50).to_csv("clotting_sim2.csv", index=True, header=False)
        # time.sleep(2)
        # Create the slider with increments of 5 up to 100

        # Remove the slider and set the value_compound to the minimum of the number of rows in the dataframe and 100
        value_phyto = min(df1.shape[0], 100)

        # st.markdown(f"<b><p style='font-family: Arial; font-size: 20px;'>Visualize "
        #             f"<span style='color:red; font-style: italic;'>KEGG compounds</span> contextually "
        #             f"and semantically similar to <span style='color:red; font-style: italic;'>{query}</span> "
        #             f"within the <span style='color:red; font-style: italic;'>{database_name}</span> corpus.</p></b>",
        #     unsafe_allow_html=True)

        st.markdown(
            f"<b><p style='font-family: Arial; font-size: 20px; font-style: Bold;'>Top <span style='color:red; font-style: italic;'>{value_phyto} "
            f"</span>Phytochemicals contextually and semantically similar to "
            f"<span style='color:red; font-style: italic;'>{query}</span> within the <span style='color:red; font-style: italic;'>{database_name}</span> corpus. "
            f"Click on the squares to expand and also the Pubmed and Wikipedia links for more compound information</span></p></b>",
            unsafe_allow_html=True)

        df15 = df1.head(value_phyto).copy()

        df15.index = (1 / df15.index) * 10000
        sizes = df15.index.tolist()

        df15.set_index('Phytochemical', inplace=True)

        df8 = df1.copy()
        # print(df4.head(10))
        df8["SIMILARITY"] = 'Similarity Score ' + df8.head(value_phyto)["SIMILARITY"].round(2).astype(str)
        df8.reset_index(inplace=True)
        # df4 = df4.rename(columns={'Protein': 'symbol2'})
        # print(df4)
        # # Use df.query to get a subset of df1 based on ids in df2
        # subset = df4.head(value_gene).query('symbol2 in @df2b.symbol2')
        # # Use merge to join the two DataFrames on id
        # result = pd.merge(subset, df2b, on='symbol2')
        # print(result)
        if value_phyto <= df_len:
            # Define the `text` column for labels and `href` column for links
            # Reset the index
            df15.reset_index(inplace=True)

            # Replace hyphens with spaces in the 'text' column
            df15['Phytochemical'] = df15['Phytochemical'].str.replace('-', ' ')

            # Set the 'text' column back as the index
            df15.set_index('Phytochemical', inplace=True)
            df15['text'] = df15.index
            df15['href'] = [f'https://pubmed.ncbi.nlm.nih.gov/?term={database_name}%5Bmh%5D+NOT+review%5Bpt%5D' \
                            '+AND+english%5Bla%5D+AND+hasabstract+AND+1990:2022%5Bdp%5D+AND+' + c for c in df15['text']]
            df15['href2'] = [f'https://en.wikipedia.org/wiki/' + c for c in df15['text']]
            assert isinstance(df15, object)
            df15['database'] = database_name

            # df11['name'] = [c for c in result['Approved name']]

            # Create the treemap using `px.treemap`
            fig = px.treemap(df15, path=[df15['text']], values=sizes, custom_data=['href', 'database', 'href2', 'text'],
                             hover_name=(df8.head(value_phyto)['SIMILARITY']))

            fig.update(layout_coloraxis_showscale=False)
            fig.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
            fig.update_annotations(visible=False)
            fig.update_traces(marker=dict(cornerradius=5), root_color="#CCFFFF", hovertemplate=None,
                              hoverlabel_bgcolor="lightblue", hoverlabel_bordercolor="#000000",
                              texttemplate="<span style='font-family: Arial; font-size: 20px;'>%{customdata[3]}<br><br>"
                                           "<a href='%{customdata[0]}'>PubMed"
                                           "</a><br><br><a href='%{customdata[2]}'>Wikipedia"
                                           "</span></a>")
            fig.update_layout(uniformtext=dict(minsize=15), treemapcolorway=["LightSeaGreen"])
            # # display the treemap in Streamlit
            # with treemap2:

            # st.pyplot(fig2)
            st.plotly_chart(fig, use_container_width=True)

            st.caption("Phytochemical designation and database provided by PhytoHub: https://phytohub.eu/")

            csv = df1.head(value_phyto).to_csv().encode('utf-8')
            st.download_button(label=f"download top {value_phyto} phytochemicals (csv)", data=csv,
                               file_name=f'{database_name}_phytochemicals.csv', mime='text/csv')


        else:
            st.warning(
                f"This selection exceeds the number of similar pythochemicals related to {query} within the {database_name} corpus, please choose a lower number")

        # try:
        #     value_phyto = min(df_len, 50)
        #     top_words = model.wv.most_similar_cosmul(query, topn=value_phyto)
        #     words = df15.head(value_phyto).index
        #     words = [word.replace(' ', '-') for word in words]
        #     # print(words)
        #     sims = df8.head(value_phyto)["SIMILARITY"].tolist()
        #     # print(sims)
        #     X_top = model.wv[words]  # print(X_top)
        # except Exception as e:
        #     print("Error:", e)
        #
        # # Remove the text "Similarity Score" from each element in the sims list
        # sims_query_top = [float(sim.split()[-1]) for sim in sims]
        # # print(sims_query_top)
        #
        # # Generate a 3D scatter plot of word embeddings using Plotly
        # fig4 = px.scatter_3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], text=words, color=sims_query_top,
        #                      color_continuous_scale="RdYlGn", hover_name=words, hover_data={"color": sims_query_top})
        #
        # # Change background color to black
        # fig4.update_layout(scene=dict(bgcolor='#CCFFFF'))
        #
        # # Change color of text to white
        # fig4.update_layout(scene=dict(xaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
        #                               yaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
        #                               zaxis=dict(backgroundcolor='#CCFFFF', color='blue')))
        #
        # fig4.update_traces(hovertemplate='<b>%{hovertext}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>')
        # fig4.update_layout(
        #     title=dict(text=f"Word embedding map for {query} in {database_name} PubMed corpus", x=0.5, y=0.95,
        #                xanchor='center', yanchor='top', font=dict(color='black')),
        #     scene=dict(xaxis_title="Dimension 1", yaxis_title="Dimension 2", zaxis_title="Dimension 3"))
        # fig4.update_coloraxes(colorbar_title="Similarity with query")
        #
        # # Represent query as a large red diamond
        # fig4.add_trace(
        #     go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='markers',
        #                  marker=dict(size=7, color='black', symbol='diamond'), name=query, hovertext=query,
        #                  showlegend=False))
        #
        # # Add label for the query above the diamond
        # fig4.add_trace(go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='text',
        #                             text=[query], textposition='bottom center', textfont=dict(color='blue', size=10),
        #                             hoverinfo='none', showlegend=False))
        #
        # # Add circles for the top 50 similar words
        # fig4.add_trace(go.Scatter3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], mode='markers',
        #                             marker=dict(size=2, color=sims_query_top, colorscale='RdYlGn', symbol='circle'),
        #                             hovertemplate='<b>%{text}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>',
        #                             text=words, customdata=sims, name=''))
        #
        # fig4.update(layout_coloraxis_showscale=True)
        # fig4.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
        # fig4.update_annotations(visible=False)
        #
        # st.plotly_chart(fig4, use_container_width=True)
        # st.markdown("---")


        st.markdown("---")


        # print()
        # print("Human genes similar to " + str(query))
        df1 = table.copy()
        df2 = pd.read_csv('kegg_compounds_lowercase.csv')
        m = df1.Word.isin(df2.compound)
        df1 = df1[m]
        df1.rename(columns={'Word': 'Compounds'}, inplace=True)
        df_len = len(df1)
        # df1["Human Gene"] = df1["Human Gene"].str.upper()
        # print(df1.head(50))
        # print()
        # df1.head(50).to_csv("clotting_sim2.csv", index=True, header=False)
        # time.sleep(2)
        # Create the slider with increments of 5 up to 100

        # Remove the slider and set the value_compound to the minimum of the number of rows in the dataframe and 100
        value_compound = min(df1.shape[0], 100)

        # st.markdown(f"<b><p style='font-family: Arial; font-size: 20px;'>Visualize "
        #             f"<span style='color:red; font-style: italic;'>KEGG compounds</span> contextually "
        #             f"and semantically similar to <span style='color:red; font-style: italic;'>{query}</span> "
        #             f"within the <span style='color:red; font-style: italic;'>{database_name}</span> corpus.</p></b>",
        #     unsafe_allow_html=True)

        st.markdown(
            f"<b><p style='font-family: Arial; font-size: 20px; font-style: Bold;'>Top <span style='color:red; font-style: italic;'>{value_compound} "
            f"</span>Compounds contextually and semantically similar to "
            f"<span style='color:red; font-style: italic;'>{query}</span> within the <span style='color:red; font-style: italic;'>{database_name}</span> corpus. "
            f"Click on the squares to expand and the Pubmed, Wikipedia, and KEGG links for more compound information (may take time to load)</span></p></b>",
            unsafe_allow_html=True)

        df12 = df1.head(value_compound).copy()

        df12.index = (1 / df12.index) * 10000
        sizes = df12.index.tolist()

        df12.set_index('Compounds', inplace=True)

        df5 = df1.copy()
        # print(df4.head(10))
        df5["SIMILARITY"] = 'Similarity Score ' + df5.head(value_compound)["SIMILARITY"].round(2).astype(str)
        df5.reset_index(inplace=True)
        # df4 = df4.rename(columns={'Protein': 'symbol2'})
        # print(df4)
        # # Use df.query to get a subset of df1 based on ids in df2
        # subset = df4.head(value_gene).query('symbol2 in @df2b.symbol2')
        # # Use merge to join the two DataFrames on id
        # result = pd.merge(subset, df2b, on='symbol2')
        # print(result)

        if value_compound <= df_len:
            # Define the `text` column for labels and `href` column for links
            # Reset the index
            df12.reset_index(inplace=True)

            # Replace hyphens with spaces in the 'text' column
            df12['Compounds'] = df12['Compounds'].str.replace('-', ' ')

            # Set the 'text' column back as the index
            df12.set_index('Compounds', inplace=True)
            df12['text'] = df12.index
            df12['href'] = [f'https://pubmed.ncbi.nlm.nih.gov/?term={database_name}%5Bmh%5D+NOT+review%5Bpt%5D' \
                            '+AND+english%5Bla%5D+AND+hasabstract+AND+1990:2022%5Bdp%5D+AND+' + c for c in df12['text']]
            df12['href2'] = [f'https://en.wikipedia.org/wiki/' + c for c in df12['text']]
            df12['href3'] = [f'https://www.genome.jp/entry/{compound_id}' for compound_id in
                             get_compound_ids(df12['text'])]
            assert isinstance(df12, object)
            df12['database'] = database_name

            # df11['name'] = [c for c in result['Approved name']]

            # Create the treemap using `px.treemap`
            fig = px.treemap(df12, path=[df12['text']], values=sizes,
                             custom_data=['href', 'database', 'href2', 'text', 'href3'],
                             hover_name=(df5.head(value_compound)['SIMILARITY']))

            fig.update(layout_coloraxis_showscale=False)
            fig.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
            fig.update_annotations(visible=False)
            fig.update_traces(marker=dict(cornerradius=5), root_color="#CCFFFF", hovertemplate=None,
                              hoverlabel_bgcolor="lightblue", hoverlabel_bordercolor="#000000",
                              texttemplate="<span style='font-family: Arial; font-size: 20px;'>%{customdata[3]}<br><br>"
                                           "<a href='%{customdata[0]}'>PubMed"
                                           "</a><br><br><a href='%{customdata[2]}'>Wikipedia"
                                           "</a><br><br><a href='%{customdata[4]}'>KEGG Compound Page"
                                           "</span></a>")

            fig.update_layout(uniformtext=dict(minsize=15), treemapcolorway=["LightYellow"])
            # # display the treemap in Streamlit
            # with treemap2:

            # st.pyplot(fig2)
            st.plotly_chart(fig, use_container_width=True)

            st.caption("Compound designation and database provided by KEGG: https://www.kegg.jp/kegg/compound/")

            csv = df1.head(value_compound).to_csv().encode('utf-8')
            st.download_button(label=f"download top {value_compound} compounds (csv)", data=csv,
                               file_name=f'{database_name}_compounds.csv', mime='text/csv')


        else:
            st.warning(
                f"This selection exceeds the number of similar proteins related to {query} within the {database_name} corpus, please choose a lower number")

        # try:
        #     value_compound = min(df_len, 50)
        #     top_words = model.wv.most_similar_cosmul(query, topn=value_compound)
        #     words = df12.head(value_compound).index
        #     words = [word.replace(' ', '-') for word in words]
        #
        #     sims = df5.head(value_compound)["SIMILARITY"].tolist()
        #     # print(sims)
        #     X_top = model.wv[words]  # print(X_top)
        # except Exception as e:
        #     print("Error:", e)
        #
        # # Remove the text "Similarity Score" from each element in the sims list
        # sims_query_top = [float(sim.split()[-1]) for sim in sims]
        # # print(sims_query_top)
        #
        # # Generate a 3D scatter plot of word embeddings using Plotly
        # fig5 = px.scatter_3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], text=words, color=sims_query_top,
        #                      color_continuous_scale="RdYlGn", hover_name=words, hover_data={"color": sims_query_top})
        #
        # # Change background color to black
        # fig5.update_layout(scene=dict(bgcolor='#CCFFFF'))
        #
        # # Change color of text to white
        # fig5.update_layout(scene=dict(xaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
        #                               yaxis=dict(backgroundcolor='#CCFFFF', color='blue'),
        #                               zaxis=dict(backgroundcolor='#CCFFFF', color='blue')))
        #
        # fig5.update_traces(hovertemplate='<b>%{hovertext}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>')
        # fig5.update_layout(
        #     title=dict(text=f"Word embedding map for {query} in {database_name} PubMed corpus", x=0.5, y=0.95,
        #                xanchor='center', yanchor='top', font=dict(color='black')),
        #     scene=dict(xaxis_title="Dimension 1", yaxis_title="Dimension 2", zaxis_title="Dimension 3"))
        # fig5.update_coloraxes(colorbar_title="Similarity with query")
        #
        # # Represent query as a large red diamond
        # fig5.add_trace(
        #     go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='markers',
        #                  marker=dict(size=7, color='black', symbol='diamond'), name=query, hovertext=query,
        #                  showlegend=False))
        #
        # # Add label for the query above the diamond
        # fig5.add_trace(go.Scatter3d(x=[model.wv[query][0]], y=[model.wv[query][1]], z=[model.wv[query][2]], mode='text',
        #                             text=[query], textposition='bottom center', textfont=dict(color='blue', size=10),
        #                             hoverinfo='none', showlegend=False))
        #
        # # Add circles for the top 50 similar words
        # fig5.add_trace(go.Scatter3d(x=X_top[:, 0], y=X_top[:, 1], z=X_top[:, 2], mode='markers',
        #                             marker=dict(size=2, color=sims_query_top, colorscale='RdYlGn', symbol='circle'),
        #                             hovertemplate='<b>%{text}</b><br>Similarity score: %{customdata[0]:.2f}<extra></extra>',
        #                             text=words, customdata=sims, name=''))
        #
        # fig5.update(layout_coloraxis_showscale=True)
        # fig5.update_layout(autosize=True, paper_bgcolor="#CCFFFF", margin=dict(t=0, b=0, l=0, r=0))
        # fig5.update_annotations(visible=False)
        #
        # st.plotly_chart(fig5, use_container_width=True)
        # st.markdown("---")
        # import os

        # from datasets import Dataset

        # # Check if the comments directory exists
        # if os.path.exists('comments'):
        #     # Load the dataset from disk
        #     dataset = Dataset.load_from_disk('comments')
        # else:
        #     # Create a new dataset
        #     dataset = Dataset.from_dict({'id': [], 'text': []})

        # def save_comment(comment):
        #     # Check if the dataset exists
        #     if os.path.exists('comments'):
        #         dataset = Dataset.load_from_disk('comments')
        #     else:
        #         dataset = Dataset.from_dict({'id': [], 'text': []})

        #     # Append the new comment to the dataset
        #     new_comment = {'id': len(dataset), 'text': comment}
        #     dataset = dataset.concatenate(Dataset.from_dict(new_comment))

        #     # Save the dataset to disk
        #     dataset.save_to_disk('comments')

        #     print('Comment saved to dataset.')

        # st.title("Abstractalytics Web App")
        # st.write("We appreciate your feedback!")

        # user_comment = st.text_area("Please send us your anonymous remarks/suggestions about the Abstractalytics Web App: "
        #                         "(app will pause while we save your comments)")

        # if st.button("Submit"):
        #     if user_comment:
        #         save_comment(user_comment)
        #         st.success("Your comment has been saved. Thank you for your feedback!")
        #     else:
        #         st.warning("Please enter a comment before submitting.")

        # # Load the comments dataset from disk
        # if os.path.exists('comments'):
        #     dataset = Dataset.load_from_disk('comments')
        # else:
        #     dataset = Dataset.from_dict({'id': [], 'text': []})

        # # Access the text column of the dataset
        # comments = dataset['text']

        # # Define the password
        # PASSWORD = 'ram100pass'

        # # Prompt the user for the password
        # password = st.text_input('Password:', type='password')

        # # Display the comments if the password is correct
        # if password == PASSWORD:
        #     st.title('Comments')
        #     for comment in comments:
        #         st.write(comment)
        # else:
        #     st.warning('Incorrect password')

        st.markdown("---")
    except:
        st.warning("")

    st.subheader("Cancer-related videos")
    if query:
        idlist = []
        search_keyword = {query}
        html = urllib.request.urlopen("https://www.youtube.com/@NCIgov/search?query=cancer")
        html2 = urllib.request.urlopen("https://www.youtube.com/@CancerCenter/search?query=cancer")
        html3 = urllib.request.urlopen("https://www.youtube.com/@NorthwesternMedicine/search?query=cancer")
        html4 = urllib.request.urlopen("https://www.youtube.com/@TEDEd/search?query=cancer")
        html5 = urllib.request.urlopen("https://www.youtube.com/@CancerResearchUK/search?query=cancer")
        video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
        video_ids2 = re.findall(r"watch\?v=(\S{11})", html2.read().decode())
        video_ids3 = re.findall(r"watch\?v=(\S{11})", html3.read().decode())
        video_ids4 = re.findall(r"watch\?v=(\S{11})", html4.read().decode())
        video_ids5 = re.findall(r"watch\?v=(\S{11})", html5.read().decode())

        for i in video_ids2:
            video_ids.append(i)
        for i in video_ids3:
            video_ids.append(i)
        for i in video_ids4:
            video_ids.append(i)
        for i in video_ids5:
            video_ids.append(i)

        random.shuffle(video_ids)

        c1, c2, c3 = st.columns(3)

        with c1:
            st.video("https://www.youtube.com/watch?v=" + video_ids[0])
        with c2:
            st.video("https://www.youtube.com/watch?v=" + video_ids[1])
        with c3:
            st.video("https://www.youtube.com/watch?v=" + video_ids[2])
    st.markdown("---")

    # Add a section header for useful resources
    st.header("Learn More About Word2Vec the algorithm behind OncoDigger")

    # Add links to videos and webpages
    # Add links to videos and webpages
    st.markdown("""
            Here are some useful resources to help you learn more about Word2Vec:

            1. [Word2Vec Tutorial - The Skip-Gram Model](http://mccormickml.com/2016/04/19/word2vec-tutorial-the-skip-gram-model/) - A blog post by Chris McCormick providing a detailed explanation of the skip-gram model used in Word2Vec.
            2. [Word2Vec Tutorial Part 2 - Negative Sampling](http://mccormickml.com/2017/01/11/word2vec-tutorial-part-2-negative-sampling/) - A follow-up blog post by Chris McCormick discussing negative sampling in Word2Vec.
            3. [Efficient Estimation of Word Representations in Vector Space](https://arxiv.org/pdf/1301.3781.pdf) - The original research paper by Mikolov et al. that introduced the Word2Vec algorithm.
            4. [Word2Vec Tutorial: Vector Representation of Words](https://www.youtube.com/watch?v=64qSgA66P-8) - A YouTube video by Sentdex explaining the Word2Vec algorithm and its implementation in Python.
            5. [Word2Vec: How to Implement Word2Vec in Python](https://www.youtube.com/watch?v=ISPId9Lhc1g&t=6s) - A YouTube video by Data Talks demonstrating how to implement Word2Vec in Python using the Gensim library.
            6. [Cosine Similarity Calculator](https://www.omnicalculator.com/math/cosine-similarity) - A calculator for computing cosine similarity, a common metric used in measuring similarity between vectors.
            """)


# else:
#     st.error("The password you entered is incorrect.")