Spaces:
Sleeping
Sleeping
File size: 9,186 Bytes
5d94a6e cf71cf5 5d94a6e |
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 |
# -*- coding: utf-8 -*-
"""
Created on May 15 16:21:25 2023
@author: luol2
"""
import streamlit as st
from src.nn_model import bioTag_CNN,bioTag_BERT
from src.dic_ner import dic_ont
from src.tagging_text import bioTag
import os
import json
from pandas import DataFrame
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
st.set_page_config(
page_title="PhenoTagger_CL",
page_icon="π",
layout="wide",
menu_items={
'Get Help': 'https://www.ncbi.nlm.nih.gov/research/bionlp/',
'About': "PhenoTagger-CL"
}
)
# def _max_width_():
# max_width_str = f"max-width: 2400px;"
# st.markdown(
# f"""
# <style>
# .reportview-container .main .block-container{{
# {max_width_str}
# }}
# </style>
# """,
# unsafe_allow_html=True,
# )
# _max_width_()
# c30, c31, c32 = st.columns([2.5, 1, 3])
# with c30:
# # st.image("logo.png", width=400)
st.title("π¨ββοΈ PhenoTagger_CL Demo")
with st.expander("βΉοΈ - About this app", expanded=True):
st.write(
"""
- This app is an easy-to-use interface built in Streamlit for [PhenoTagger](https://github.com/ncbi-nlp/PhenoTagger) library!
- PhenoTagger is a hybrid method that combines dictionary and deep learning-based methods to recognize Human Phenotype Ontology (HPO) concepts in unstructured biomedical text. Please refer to [our paper](https://doi.org/10.1093/bioinformatics/btab019) for more details.
- Contact: [NLM/NCBI BioNLP Research Group](https://www.ncbi.nlm.nih.gov/research/bionlp/)
"""
)
st.markdown("")
st.markdown("")
st.markdown("## π Paste document ")
with st.form(key="my_form"):
ce, c1, ce, c2, c3 = st.columns([0.07, 1, 0.07, 4, 0.07])
with c1:
ModelType = st.radio(
"Choose your Ontology",
['CL'], #["HPO(Default)", "UBERON"],
#help="Bioformer is more precise, CNN is more efficient",
)
if ModelType == "CL":
# kw_model = KeyBERT(model=roberta)
#@st.cache(allow_output_mutation=True)
def load_model():
ontfiles={'dic_file':'./dict_cl/noabb_lemma.dic',
'word_id_file':'./dict_cl/word_id_map.json',
'id_word_file':'./dict_cl/id_word_map.json'}
vocabfiles={'labelfile':'./dict_cl/lable.vocab',
'checkpoint_path':'./models/bioformer-cased-v1.0/',
'lowercase':False}
modelfile='./models/bioformer-CL.h5'
biotag_dic=dic_ont(ontfiles)
nn_model=bioTag_BERT(vocabfiles)
nn_model.load_model(modelfile)
return nn_model,biotag_dic
nn_model,biotag_dic = load_model()
else:
pass
'''
#@st.cache(allow_output_mutation=True)
def load_model():
ontfiles={'dic_file':'./dict_uberon/noabb_lemma.dic',
'word_id_file':'./dict_uberon/word_id_map.json',
'id_word_file':'./dict_uberon/id_word_map.json'}
vocabfiles={'labelfile':'./dict_uberon/lable.vocab',
'checkpoint_path':'./models_v1.2/bioformer-cased-v1.0/',
'lowercase':False}
modelfile='./models_v1.2/bioformer-UBERON.h5'
biotag_dic=dic_ont(ontfiles)
nn_model=bioTag_BERT(vocabfiles)
nn_model.load_model(modelfile)
return nn_model,biotag_dic
nn_model,biotag_dic = load_model()
'''
para_overlap = st.checkbox(
"Overlap concept",
value=False,
help="Tick this box to identify overlapping concepts",
)
para_abbr = st.checkbox(
"Abbreviaitons",
value=True,
help="Tick this box to identify abbreviations",
)
para_threshold = st.slider(
"Threshold",
min_value=0.5,
max_value=1.0,
value=0.95,
step=0.05,
help="Retrun the preditions which socre over the threshold.",
)
with c2:
doc = st.text_area(
"Paste your text below",
value = 'Uniparental disomy has recently been recognized to cause human disorders, including Prader-Willi syndrome (PWS). We describe a particularly instructive case which raises important issues concerning the mechanisms producing uniparental disomy and whose evaluation provides evidence that trisomy may precede uniparental disomy in a fetus. Chorionic villus sampling performed for advanced maternal age revealed trisomy 15 in all direct and cultured cells, though the fetus appeared normal. Chromosome analysis of amniocytes obtained at 15 wk was normal in over 100 cells studied. The child was hypotonic at birth, and high-resolution banding failed to reveal the deletion of 15q11-13, a deletion which is found in 50%-70% of patients with PWS. Over time, typical features of PWS developed. Molecular genetic analysis using probes for chromosome 15 revealed maternal disomy. Maternal nondisjunction with fertilization of a disomic egg by a normal sperm, followed by loss of the paternal 15, is a likely cause of confined placental mosaicism and uniparental disomy in this case of PWS, and advanced maternal age may be a predisposing factor.',
height=400,
)
# MAX_WORDS = 500
# import re
# res = len(re.findall(r"\w+", doc))
# if res > MAX_WORDS:
# st.warning(
# "β οΈ Your text contains "
# + str(res)
# + " words."
# + " Only the first 500 words will be reviewed. Stay tuned as increased allowance is coming! π"
# )
# doc = doc[:MAX_WORDS]
submit_button = st.form_submit_button(label="β¨ Submit!")
if not submit_button:
st.stop()
#st.write(para_overlap,para_abbr,para_threshold)
para_set={
#model_type':para_model, # cnn or bioformer
'onlyLongest': not para_overlap, # False: return overlap concepts, True only longgest
'abbrRecog':para_abbr,# False: don't identify abbr, True: identify abbr
'ML_Threshold':para_threshold,# the Threshold of deep learning model
}
st.markdown("")
st.markdown("## π‘ Tagging results:")
with st.spinner('Wait for tagging...'):
tag_result=bioTag(doc,biotag_dic,nn_model,onlyLongest=para_set['onlyLongest'], abbrRecog=para_set['abbrRecog'],Threshold=para_set['ML_Threshold'])
st.markdown('<font style="color: rgb(128, 128, 128);">Move the mouseπ±οΈ over the entity to display the HPO id.</font>', unsafe_allow_html=True)
# print('dic...........:',biotag_dic.keys())
# st.write('parameters:', para_overlap,para_abbr,para_threshold)
html_results=''
text_results=doc+'\n'
entity_end=0
hpoid_count={}
if len(tag_result)>=0:
for ele in tag_result:
entity_start=int(ele[0])
html_results+=doc[entity_end:entity_start]
entity_end=int(ele[1])
entity_id=ele[2]
entity_score=ele[3]
text_results+=ele[0]+'\t'+ele[1]+'\t'+doc[entity_start:entity_end]+'\t'+ele[2]+'\t'+format(float(ele[3]),'.2f')+'\n'
if entity_id not in hpoid_count.keys():
hpoid_count[entity_id]=1
else:
hpoid_count[entity_id]+=1
html_results+='<font style="background-color: rgb(255, 204, 0)'+';" title="'+entity_id+'">'+doc[entity_start:entity_end]+'</font>'
html_results+=doc[entity_end:]
else:
html_results=doc
st.markdown('<table border="1"><tr><td>'+html_results+'</td></tr></table>', unsafe_allow_html=True)
#table
data_entity=[]
for ele in hpoid_count.keys():
segs=ele.split(';')
term_name=''
for seg in segs:
term_name+=biotag_dic.id_word[seg][0]+';'
temp=[ele,term_name,hpoid_count[ele]] #hpoid, term name, count
data_entity.append(temp)
st.markdown("")
st.markdown("")
# st.markdown("## Table output:")
# cs, c1, c2, c3, cLast = st.columns([2, 1.5, 1.5, 1.5, 2])
# with c1:
# CSVButton2 = download_button(keywords, "Data.csv", "π₯ Download (.csv)")
# with c2:
# CSVButton2 = download_button(keywords, "Data.txt", "π₯ Download (.txt)")
# with c3:
# CSVButton2 = download_button(keywords, "Data.json", "π₯ Download (.json)")
# st.header("")
df = (
DataFrame(data_entity, columns=["Ontology_id", "Term name","Frequency"])
.sort_values(by="Frequency", ascending=False)
.reset_index(drop=True)
)
df.index += 1
c1, c2, c3 = st.columns([1, 4, 1])
# format_dictionary = {
# "Relevancy": "{:.1%}",
# }
# df = df.format(format_dictionary)
with c2:
st.table(df)
c1, c2, c3 = st.columns([1, 1, 1])
with c2:
st.download_button('Download annotations', text_results)
|