DifeiT commited on
Commit
411342e
Β·
1 Parent(s): 3d24191

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +338 -0
app.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Mon Nov 21 16:21:25 2022
4
+
5
+ @author: luol2
6
+ """
7
+
8
+ import streamlit as st
9
+ from src.nn_model import bioTag_CNN,bioTag_Bioformer
10
+ from src.dic_ner import dic_ont
11
+ from src.tagging_text import bioTag
12
+ import os
13
+ import json
14
+ from pandas import DataFrame
15
+ import nltk
16
+ nltk.download('punkt')
17
+ nltk.download('averaged_perceptron_tagger')
18
+ nltk.download('wordnet')
19
+
20
+ st.set_page_config(
21
+ page_title="Demo",
22
+ page_icon="🎈",
23
+ layout="wide",
24
+ menu_items={
25
+ }
26
+ )
27
+
28
+
29
+ # def _max_width_():
30
+ # max_width_str = f"max-width: 2400px;"
31
+ # st.markdown(
32
+ # f"""
33
+ # <style>
34
+ # .reportview-container .main .block-container{{
35
+ # {max_width_str}
36
+ # }}
37
+ # </style>
38
+ # """,
39
+ # unsafe_allow_html=True,
40
+ # )
41
+
42
+
43
+ # _max_width_()
44
+
45
+ # c30, c31, c32 = st.columns([2.5, 1, 3])
46
+
47
+ # with c30:
48
+ # # st.image("logo.png", width=400)
49
+ st.title("Demo")
50
+
51
+ with st.expander("🎈 About this demo", expanded=True):
52
+
53
+ st.write(
54
+ """
55
+ - This demo is an extension work using [PhenoTagger](https://github.com/ncbi-nlp/PhenoTagger) library
56
+ - Hackathon: Nonaworks - Gingko Problem 2
57
+ """
58
+ )
59
+
60
+ st.markdown("")
61
+
62
+ st.markdown("")
63
+ st.markdown("## βœ‚ Paste your text ")
64
+ with st.form(key="my_form"):
65
+
66
+
67
+ ce, c1, ce, c2, c3 = st.columns([0.07, 1, 0.07, 4, 0.07])
68
+ with c1:
69
+ ModelType = st.radio(
70
+ "Choose your model",
71
+ ["Bioformer(Default)"],
72
+ help="Bioformer is more precise, CNN is more efficient",
73
+ )
74
+
75
+ if ModelType == "Bioformer(Default)":
76
+ # kw_model = KeyBERT(model=roberta)
77
+
78
+ @st.cache(allow_output_mutation=True)
79
+ def load_model(model='hpo'):
80
+ if model =='1':
81
+ ontfiles = {'dic_file': './dict_new_fyeco/noabb_lemma.dic',
82
+ 'word_hpo_file': './dict_new_fyeco/word_id_map.json',
83
+ 'hpo_word_file': './dict_new_fyeco/id_word_map.json'}
84
+
85
+ vocabfiles = {'labelfile': './dict_new_fyeco/lable.vocab',
86
+ 'config_path': './vocab/bioformer-cased-v1.0/bert_config.json',
87
+ 'checkpoint_path': './vocab/bioformer-cased-v1.0/bioformer-cased-v1.0-model.ckpt-2000000',
88
+ 'vocab_path': './vocab/bioformer-cased-v1.0/vocab.txt'}
89
+
90
+ modelfile = './vocab/bioformer.h5'
91
+
92
+ elif model == '2':
93
+ vocabfiles = {'labelfile': './dict_new_hpo/lable.vocab',
94
+ 'config_path': './vocab/bioformer-cased-v1.0/bert_config.json',
95
+ 'checkpoint_path': './vocab/bioformer-cased-v1.0/bioformer-cased-v1.0-model.ckpt-2000000',
96
+ 'vocab_path': './vocab/bioformer-cased-v1.0/vocab.txt'}
97
+
98
+ ontfiles = {'dic_file': './dict_new_hpo/noabb_lemma.dic',
99
+ 'word_hpo_file': './dict_new_hpo/word_id_map.json',
100
+ 'hpo_word_file': './dict_new_hpo/id_word_map.json'}
101
+
102
+ modelfile='./vocab/bioformer_p5n5_b64_1e-5_95_hponew3.h5'
103
+
104
+ biotag_dic=dic_ont(ontfiles)
105
+
106
+ nn_model=bioTag_Bioformer(vocabfiles)
107
+ nn_model.load_model(modelfile)
108
+ return nn_model,biotag_dic
109
+
110
+ nn_model1, biotag_dic1 = load_model(model='1')
111
+ nn_model2, biotag_dic2 = load_model(model='2')
112
+
113
+ else:
114
+ @st.cache(allow_output_mutation=True)
115
+ def load_model():
116
+ ontfiles={'dic_file':'./dict_new/noabb_lemma.dic',
117
+ 'word_hpo_file':'./dict_new/word_id_map.json',
118
+ 'hpo_word_file':'./dict_new/id_word_map.json'}
119
+
120
+
121
+ vocabfiles={'w2vfile':'./vocab/bio_embedding_intrinsic.d200',
122
+ 'charfile':'./vocab/char.vocab',
123
+ 'labelfile':'./dict_new/lable.vocab',
124
+ 'posfile':'./vocab/pos.vocab'}
125
+ modelfile='./vocab/cnn_p5n5_b128_95_hponew1.h5'
126
+
127
+ biotag_dic=dic_ont(ontfiles)
128
+
129
+ nn_model=bioTag_CNN(vocabfiles)
130
+ nn_model.load_model(modelfile)
131
+
132
+ return nn_model,biotag_dic
133
+
134
+ nn_model,biotag_dic = load_model()
135
+
136
+ para_overlap = st.checkbox(
137
+ "Overlap concept",
138
+ value=False,
139
+ help="Tick this box to identify overlapping concepts",
140
+ )
141
+ para_abbr = st.checkbox(
142
+ "Abbreviaitons",
143
+ value=True,
144
+ help="Tick this box to identify abbreviations",
145
+ )
146
+
147
+ para_threshold = st.slider(
148
+ "Threshold",
149
+ min_value=0.5,
150
+ max_value=1.0,
151
+ value=0.95,
152
+ step=0.05,
153
+ help="Retrun the preditions which socre over the threshold.",
154
+ )
155
+
156
+
157
+
158
+
159
+ with c2:
160
+
161
+
162
+ doc = st.text_area(
163
+ "Paste your text below",
164
+ value = 'The clinical features of Angelman syndrome (AS) comprise severe mental retardation, postnatal microcephaly, macrostomia and prognathia, absence of speech, ataxia, and a happy disposition. We report on seven patients who lack most of these features, but presented with obesity, muscular hypotonia and mild mental retardation. Based on the latter findings, the patients were initially suspected of having Prader-Willi syndrome. DNA methylation analysis of SNRPN and D15S63, however, revealed an AS pattern, ie the maternal band was faint or absent. Cytogenetic studies and microsatellite analysis demonstrated apparently normal chromosomes 15 of biparental inheritance. We conclude that these patients have an imprinting defect and a previously unrecognised form of AS. The mild phenotype may be explained by an incomplete imprinting defect or by cellular mosaicism.',
165
+ height=400,
166
+ )
167
+
168
+
169
+ # MAX_WORDS = 500
170
+ # import re
171
+ # res = len(re.findall(r"\w+", doc))
172
+ # if res > MAX_WORDS:
173
+ # st.warning(
174
+ # "⚠️ Your text contains "
175
+ # + str(res)
176
+ # + " words."
177
+ # + " Only the first 500 words will be reviewed. Stay tuned as increased allowance is coming! 😊"
178
+ # )
179
+
180
+ # doc = doc[:MAX_WORDS]
181
+
182
+ submit_button = st.form_submit_button(label="πŸ–±οΈ Submit!")
183
+
184
+
185
+ if not submit_button:
186
+ st.stop()
187
+
188
+ #st.write(para_overlap,para_abbr,para_threshold)
189
+ para_set={
190
+ #model_type':para_model, # cnn or bioformer
191
+ 'onlyLongest': not para_overlap, # False: return overlap concepts, True only longgest
192
+ 'abbrRecog':para_abbr,# False: don't identify abbr, True: identify abbr
193
+ 'ML_Threshold':para_threshold,# the Threshold of deep learning model
194
+ }
195
+ st.markdown("")
196
+ st.markdown("## ⏳ Tagging results:")
197
+ with st.spinner('Wait for tagging...'):
198
+
199
+ tag_result1=bioTag(doc,biotag_dic1,nn_model1,onlyLongest=para_set['onlyLongest'], abbrRecog=para_set['abbrRecog'],Threshold=para_set['ML_Threshold'])
200
+ tag_result2=bioTag(doc,biotag_dic2,nn_model2,onlyLongest=para_set['onlyLongest'], abbrRecog=para_set['abbrRecog'],Threshold=para_set['ML_Threshold'])
201
+
202
+
203
+ st.markdown('<font style="color: rgb(128, 128, 128);">Move the mouse over the entity to display the id.</font>', unsafe_allow_html=True)
204
+ # print('dic...........:',biotag_dic.keys())
205
+ # st.write('parameters:', para_overlap,para_abbr,para_threshold)
206
+
207
+ html_results=''
208
+ text_results=doc+'\n'
209
+ entity_end=0
210
+
211
+ # poid_counts = []
212
+
213
+ hpoid_count1={}
214
+ hpoid_count2 = {}
215
+
216
+ tag_display = {}
217
+
218
+ flag = False
219
+ if len(tag_result1)>=0:
220
+ for ele in tag_result1:
221
+ entity_start=int(ele[0])
222
+ #html_results+=doc[entity_end:entity_start]
223
+ entity_end=int(ele[1])
224
+ entity_id=ele[2]
225
+ entity_score=ele[3]
226
+ tag_display[entity_start] = (entity_end, entity_id, "1")
227
+ text_results+=ele[0]+'\t'+ele[1]+'\t'+doc[entity_start:entity_end]+'\t'+ele[2]+'\t'+format(float(ele[3]),'.2f')+'\n'
228
+
229
+ if entity_id not in hpoid_count1.keys():
230
+ hpoid_count1[entity_id]=1
231
+ else:
232
+ hpoid_count1[entity_id]+=1
233
+
234
+ #html_results+='<font style="background-color: rgb(255, 204, 0)'+';" title="'+entity_id+'">'+doc[entity_start:entity_end]+'</font>'
235
+ #html_results+=doc[entity_end:]
236
+
237
+ flag = True
238
+
239
+ if len(tag_result2) >= 0:
240
+ entity_end = 0
241
+ for ele in tag_result2:
242
+ entity_start = int(ele[0])
243
+ #html_results += doc[entity_end:entity_start]
244
+ entity_end = int(ele[1])
245
+ entity_id = ele[2]
246
+ entity_score = ele[3]
247
+ tag_display[entity_start] = (entity_end, entity_id, "2")
248
+ text_results += ele[0] + '\t' + ele[1] + '\t' + doc[entity_start:entity_end] + '\t' + ele[2] + '\t' + format(
249
+ float(ele[3]), '.2f') + '\n'
250
+
251
+ if entity_id not in hpoid_count2.keys():
252
+ hpoid_count2[entity_id] = 1
253
+ else:
254
+ hpoid_count2[entity_id] += 1
255
+
256
+ # html_results += '<font style="background-color: rgb(255, 0, 0)' + ';" title="' + entity_id + '">' + doc[entity_start:entity_end] + '</font>'
257
+ #html_results += doc[entity_end:]
258
+
259
+ flag = True
260
+
261
+ if not flag:
262
+ html_results = doc
263
+ else:
264
+ myKeys = list(tag_display.keys())
265
+ myKeys.sort()
266
+ sorted_tag_display = {i: tag_display[i] for i in myKeys}
267
+ entity_end = 0
268
+
269
+ for entity_start, value in sorted_tag_display.items():
270
+ html_results += doc[entity_end:entity_start]
271
+ entity_end = value[0]
272
+ entity_id = value[1]
273
+ type = value[2]
274
+ if type == "1":
275
+ html_results += '<font style="background-color: rgb(255, 204, 0)' + ';" title="' + entity_id + '">' + doc[entity_start:entity_end] + '</font>'
276
+ elif type == "2":
277
+ html_results += '<font style="background-color: rgb(255, 0, 0)' + ';" title="' + entity_id + '">' + doc[entity_start:entity_end] + '</font>'
278
+ html_results += doc[entity_end:]
279
+
280
+ st.markdown('<table border="1"><tr><td>'+html_results+'</td></tr></table>', unsafe_allow_html=True)
281
+
282
+
283
+ #table
284
+ data_entity=[]
285
+ for ele in hpoid_count1.keys():
286
+ segs=ele.split(';')
287
+ term_name=''
288
+ for seg in segs:
289
+ term_name+=biotag_dic1.hpo_word[seg][0]+';'
290
+ temp=[ele,term_name,hpoid_count1[ele]] #hpoid, term name, count
291
+ data_entity.append(temp)
292
+
293
+ for ele in hpoid_count2.keys():
294
+ segs=ele.split(';')
295
+ term_name=''
296
+ for seg in segs:
297
+ term_name+=biotag_dic2.hpo_word[seg][0]+';'
298
+ temp=[ele,term_name,hpoid_count2[ele]] #hpoid, term name, count
299
+ data_entity.append(temp)
300
+
301
+ st.markdown("")
302
+ st.markdown("")
303
+ # st.markdown("## Table output:")
304
+
305
+ # cs, c1, c2, c3, cLast = st.columns([2, 1.5, 1.5, 1.5, 2])
306
+
307
+ # with c1:
308
+ # CSVButton2 = download_button(keywords, "Data.csv", "πŸ“₯ Download (.csv)")
309
+ # with c2:
310
+ # CSVButton2 = download_button(keywords, "Data.txt", "πŸ“₯ Download (.txt)")
311
+ # with c3:
312
+ # CSVButton2 = download_button(keywords, "Data.json", "πŸ“₯ Download (.json)")
313
+
314
+ # st.header("")
315
+
316
+ df = (
317
+ DataFrame(data_entity, columns=["Phenotype ID", "Term Name","Frequency"])
318
+ .sort_values(by="Frequency", ascending=False)
319
+ .reset_index(drop=True)
320
+ )
321
+
322
+ df.index += 1
323
+
324
+ c1, c2, c3 = st.columns([1, 4, 1])
325
+
326
+ # format_dictionary = {
327
+ # "Relevancy": "{:.1%}",
328
+ # }
329
+
330
+ # df = df.format(format_dictionary)
331
+
332
+ with c2:
333
+ st.table(df)
334
+
335
+ c1, c2, c3 = st.columns([1, 1, 1])
336
+ with c2:
337
+ st.download_button('Download annotations', text_results)
338
+