wzkariampuzha commited on
Commit
b564537
1 Parent(s): 94675c0

Upload epi_pipeline.py

Browse files
Files changed (1) hide show
  1. epi_pipeline.py +1011 -0
epi_pipeline.py ADDED
@@ -0,0 +1,1011 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Dict, Union, Optional, Set, Tuple
2
+
3
+ # coding=utf-8
4
+ # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
5
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ # ALSO See NCATS LICENSE
19
+
20
+ # Written by William Kariampuzha at NIH/NCATS. Adapted from code written by Jennifer John, et al. above
21
+
22
+ # Each section has its own import statements to facilitate clean code reuse, except for typing which applies to all.
23
+ # the `Any` type is used in place of the specific class variable, not necessarily to mean that any object type can go there...
24
+
25
+ ## Section: GATHER ABSTRACTS FROM APIs
26
+ import requests
27
+ import xml.etree.ElementTree as ET
28
+ from nltk.corpus import stopwords
29
+ STOPWORDS = set(stopwords.words('english'))
30
+ from nltk import tokenize as nltk_tokenize
31
+
32
+ #Retreives abstract and title (concatenated) from EBI API based on PubMed ID
33
+ def PMID_getAb(PMID:Union[int,str]) -> str:
34
+ url = 'https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:'+str(PMID)+'&resulttype=core'
35
+ r = requests.get(url)
36
+ root = ET.fromstring(r.content)
37
+ titles = [title.text for title in root.iter('title')]
38
+ abstracts = [abstract.text for abstract in root.iter('abstractText')]
39
+ if len(abstracts) > 0 and len(abstracts[0])>5:
40
+ return titles[0]+' '+abstracts[0]
41
+ else:
42
+ return ''
43
+
44
+ ## This is the main, most comprehensive search_term function, it can take in a search term or a list of search terms and output a dictionary of {pmids:abstracts}
45
+ ## Gets results from searching through both PubMed and EBI search term APIs, also makes use of the EBI API for PMIDs.
46
+ ## EBI API and PubMed API give different results
47
+ # This makes n+2 API calls where n<=maxResults, which is slow
48
+ # There is a way to optimize by gathering abstracts from the EBI API when also getting pmids but did not pursue due to time constraints
49
+ # Filtering can be
50
+ # 'strict' - must have some exact match to at leastone of search terms/phrases in text)
51
+ # 'lenient' - part of the abstract must match at least one word in the search term phrases.
52
+ # 'none'
53
+ def search_getAbs(searchterm_list:Union[List[str],List[int],str], maxResults:int, filtering:str) -> Dict[str,str]:
54
+ #set of all pmids
55
+ pmids = set()
56
+
57
+ #dictionary {pmid:abstract}
58
+ pmid_abs = {}
59
+
60
+ #type validation, allows string or list input
61
+ if type(searchterm_list)!=list:
62
+ if type(searchterm_list)==str:
63
+ searchterm_list = [searchterm_list]
64
+ else:
65
+ searchterm_list = list(searchterm_list)
66
+
67
+ #gathers pmids into a set first
68
+ for dz in searchterm_list:
69
+ term = ''
70
+ dz_words = dz.split()
71
+ for word in dz_words:
72
+ term += word + '%20'
73
+ query = term[:-3]
74
+
75
+ ## get pmid results from searching for disease name through PubMed API
76
+ url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term='+query
77
+ r = requests.get(url)
78
+ root = ET.fromstring(r.content)
79
+
80
+ # loop over resulting articles
81
+ for result in root.iter('IdList'):
82
+ if len(pmids) >= maxResults:
83
+ break
84
+ pmidlist = [pmid.text for pmid in result.iter('Id')]
85
+ pmids.update(pmidlist)
86
+
87
+ ## get results from searching for disease name through EBI API
88
+ url = 'https://www.ebi.ac.uk/europepmc/webservices/rest/search?query='+query+'&resulttype=core'
89
+ r = requests.get(url)
90
+ root = ET.fromstring(r.content)
91
+
92
+ # loop over resulting articles
93
+ for result in root.iter('result'):
94
+ if len(pmids) >= maxResults:
95
+ break
96
+ pmidlist = [pmid.text for pmid in result.iter('id')]
97
+ #can also gather abstract and title here but for some reason did not work as intended the first time. Optimize in future versions to reduce latency.
98
+ if len(pmidlist) > 0:
99
+ pmid = pmidlist[0]
100
+ if pmid[0].isdigit():
101
+ pmids.add(pmid)
102
+
103
+ #Construct sets for filtering (right before adding abstract to pmid_abs
104
+ # The purpose of this is to do a second check of the abstracts, filters out any abstracts unrelated to the search terms
105
+ #if filtering is 'lenient' or default
106
+ if filtering !='none' or filtering !='strict':
107
+ filter_terms = set(searchterm_list).union(set(str(re.sub(',','',' '.join(searchterm_list))).split()).difference(STOPWORDS))
108
+ '''
109
+ # The above is equivalent to this but uses less memory and may be faster:
110
+ #create a single string of the terms within the searchterm_list
111
+ joined = ' '.join(searchterm_list)
112
+ #remove commas
113
+ comma_gone = re.sub(',','',joined)
114
+ #split the string into list of words and convert list into a Pythonic set
115
+ split = set(comma_gone.split())
116
+ #remove the STOPWORDS from the set of key words
117
+ key_words = split.difference(STOPWORDS)
118
+ #create a new set of the list members in searchterm_list
119
+ search_set = set(searchterm_list)
120
+ #join the two sets
121
+ terms = search_set.union(key_words)
122
+ #if any word(s) in the abstract intersect with any of these terms then the abstract is good to go.
123
+ '''
124
+
125
+ ## get abstracts from EBI PMID API and output a dictionary
126
+ for pmid in pmids:
127
+ abstract = PMID_getAb(pmid)
128
+ if len(abstract)>5:
129
+ #do filtering here
130
+ if filtering == 'strict':
131
+ uncased_ab = abstract.lower()
132
+ for term in searchterm_list:
133
+ if term.lower() in uncased_ab:
134
+ pmid_abs[pmid] = abstract
135
+ break
136
+ elif filtering =='none':
137
+ pmid_abs[pmid] = abstract
138
+
139
+ #Default filtering is 'lenient'.
140
+ else:
141
+ #Else and if are separated for readability and to better understand logical flow.
142
+ if set(filter_terms).intersection(set(nltk_tokenize.word_tokenize(abstract))):
143
+ pmid_abs[pmid] = abstract
144
+
145
+
146
+ print('Found',len(pmids),'PMIDs. Gathered',len(pmid_abs),'Relevant Abstracts.')
147
+
148
+ return pmid_abs
149
+
150
+ #This is a streamlit version of search_getAbs. Refer to search_getAbs for documentation
151
+ import streamlit as st
152
+ def streamlit_getAbs(searchterm_list:Union[List[str],List[int],str], maxResults:int, filtering:str) -> Dict[str,str]:
153
+ pmids = set()
154
+
155
+ pmid_abs = {}
156
+
157
+ if type(searchterm_list)!=list:
158
+ if type(searchterm_list)==str:
159
+ searchterm_list = [searchterm_list]
160
+ else:
161
+ searchterm_list = list(searchterm_list)
162
+ #maxResults is multiplied by a little bit because sometimes the results returned is more than maxResults
163
+ percent_by_step = 1/maxResults
164
+ with st.spinner("Gathering PubMed IDs..."):
165
+ PMIDs_bar = st.progress(0)
166
+ for dz in searchterm_list:
167
+ term = ''
168
+ dz_words = dz.split()
169
+ for word in dz_words:
170
+ term += word + '%20'
171
+ query = term[:-3]
172
+
173
+ url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term='+query
174
+ r = requests.get(url)
175
+ root = ET.fromstring(r.content)
176
+
177
+ for result in root.iter('IdList'):
178
+ for pmid in result.iter('Id'):
179
+ if len(pmids) >= maxResults:
180
+ break
181
+ pmids.add(pmid.text)
182
+ PMIDs_bar.progress(min(round(len(pmids)*percent_by_step,1),1.0))
183
+
184
+ url = 'https://www.ebi.ac.uk/europepmc/webservices/rest/search?query='+query+'&resulttype=core'
185
+ r = requests.get(url)
186
+ root = ET.fromstring(r.content)
187
+
188
+ for result in root.iter('result'):
189
+ if len(pmids) >= maxResults:
190
+ break
191
+ pmidlist = [pmid.text for pmid in result.iter('id')]
192
+ if len(pmidlist) > 0:
193
+ pmid = pmidlist[0]
194
+ if pmid[0].isdigit():
195
+ pmids.add(pmid)
196
+ PMIDs_bar.progress(min(round(len(pmids)*percent_by_step,1),1.0))
197
+ PMIDs_bar.empty()
198
+
199
+ with st.spinner("Found "+str(len(pmids))+" PMIDs. Gathering Abstracts and Filtering..."):
200
+ abstracts_bar = st.progress(0)
201
+ percent_by_step = 1/maxResults
202
+ if filtering !='none' or filtering !='strict':
203
+ filter_terms = set(searchterm_list).union(set(str(re.sub(',','',' '.join(searchterm_list))).split()).difference(STOPWORDS))
204
+
205
+ for pmid in pmids:
206
+ abstract = PMID_getAb(pmid)
207
+ if len(abstract)>5:
208
+ #do filtering here
209
+ if filtering == 'strict':
210
+ uncased_ab = abstract.lower()
211
+ for term in searchterm_list:
212
+ if term.lower() in uncased_ab:
213
+ pmid_abs[pmid] = abstract
214
+ break
215
+ elif filtering =='none':
216
+ pmid_abs[pmid] = abstract
217
+ #Default filtering is 'lenient'.
218
+ else:
219
+ #Else and if are separated for readability and to better understand logical flow.
220
+ if set(filter_terms).intersection(set(nltk_tokenize.word_tokenize(abstract))):
221
+ pmid_abs[pmid] = abstract
222
+ abstracts_bar.progress(min(round(len(pmid_abs)*percent_by_step,1),1.0))
223
+ abstracts_bar.empty()
224
+ found = len(pmids)
225
+ relevant = len(pmid_abs)
226
+ st.success('Found '+str(found)+' PMIDs. Gathered '+str(relevant)+' Relevant Abstracts. Classifying and extracting epidemiology information...')
227
+
228
+ return pmid_abs, (found, relevant)
229
+
230
+ ## Section: LSTM RNN Epi Classification Model (EpiClassify4GARD)
231
+ import os
232
+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
233
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
234
+ import tensorflow as tf
235
+ import numpy as np
236
+ import spacy
237
+
238
+ class Classify_Pipeline:
239
+ def __init__(self,model:str='LSTM_RNN_Model'):
240
+ #Load spaCy models
241
+ self.nlp = spacy.load('en_core_web_lg')
242
+ self.nlpSci = spacy.load("en_ner_bc5cdr_md")
243
+ self.nlpSci2 = spacy.load('en_ner_bionlp13cg_md')
244
+ # load the tokenizer
245
+ with open('tokenizer.pickle', 'rb') as handle:
246
+ import pickle
247
+ self.classify_tokenizer = pickle.load(handle)
248
+ # Defaults to load my_model_orphanet_final, the most up-to-date version of the classification model,
249
+ # but can also be run on any other tf.keras model
250
+
251
+ # load the model
252
+ self.classify_model = tf.keras.models.load_model(model)
253
+ # for preprocessing
254
+ from nltk.corpus import stopwords
255
+ self.STOPWORDS = set(stopwords.words('english'))
256
+ # Modes
257
+ self.max_length = 300
258
+ self.trunc_type = 'post'
259
+ self.padding_type = 'post'
260
+
261
+ def __str__(self) -> str:
262
+ return "Instantiation: epi_classify = Classify_Pipeline({})".format(model) +"\n Calling: prob, isEpi = epi_classify(text) \n PubMed ID Predictions: abstracts, prob, isEpi = epi_classify.getPMIDPredictions(pmid)"
263
+
264
+ def __call__(self, abstract:str) -> Tuple[float,bool]:
265
+ return self.getTextPredictions(abstract)
266
+
267
+ def getTextPredictions(self, abstract:str) -> Tuple[float,bool]:
268
+ if len(abstract)>5:
269
+ # remove stopwords
270
+ for word in self.STOPWORDS:
271
+ token = ' ' + word + ' '
272
+ abstract = abstract.replace(token, ' ')
273
+ abstract = abstract.replace(' ', ' ')
274
+
275
+ # preprocess abstract
276
+ abstract_standard = [self.standardizeAbstract(self.standardizeSciTerms(abstract))]
277
+ sequence = self.classify_tokenizer.texts_to_sequences(abstract_standard)
278
+ padded = pad_sequences(sequence, maxlen=self.max_length, padding=self.padding_type, truncating=self.trunc_type)
279
+
280
+ y_pred1 = self.classify_model.predict(padded) # generate prediction
281
+ y_pred = np.argmax(y_pred1, axis=1) # get binary prediction
282
+
283
+ prob = y_pred1[0][1]
284
+ if y_pred == 1:
285
+ isEpi = True
286
+ else:
287
+ isEpi = False
288
+
289
+ return prob, isEpi
290
+ else:
291
+ return 0.0, False
292
+
293
+ def getPMIDPredictions(self, pmid:Union[str,int]) -> Tuple[str,float,bool]:
294
+ abstract = PMID_getAb(pmid)
295
+ prob, isEpi = self.getTextPredictions(abstract)
296
+ return abstract, prob, isEpi
297
+
298
+ # Standardize the abstract by replacing all named entities with their entity label.
299
+ # Eg. 3 patients reported at a clinic in England --> CARDINAL patients reported at a clinic in GPE
300
+ # expects the spaCy model en_core_web_lg as input
301
+ def standardizeAbstract(self, abstract:str) -> str:
302
+ doc = self.nlp(abstract)
303
+ newAbstract = abstract
304
+ for e in reversed(doc.ents):
305
+ if e.label_ in {'PERCENT','CARDINAL','GPE','LOC','DATE','TIME','QUANTITY','ORDINAL'}:
306
+ start = e.start_char
307
+ end = start + len(e.text)
308
+ newAbstract = newAbstract[:start] + e.label_ + newAbstract[end:]
309
+ return newAbstract
310
+
311
+ # Same as above but replaces biomedical named entities from scispaCy models
312
+ # Expects as input en_ner_bc5cdr_md and en_ner_bionlp13cg_md
313
+ def standardizeSciTerms(self, abstract:str) -> str:
314
+ doc = self.nlpSci(abstract)
315
+ newAbstract = abstract
316
+ for e in reversed(doc.ents):
317
+ start = e.start_char
318
+ end = start + len(e.text)
319
+ newAbstract = newAbstract[:start] + e.label_ + newAbstract[end:]
320
+
321
+ doc = self.nlpSci2(newAbstract)
322
+ for e in reversed(doc.ents):
323
+ start = e.start_char
324
+ end = start + len(e.text)
325
+ newAbstract = newAbstract[:start] + e.label_ + newAbstract[end:]
326
+ return newAbstract
327
+
328
+ ## Section: GARD SEARCH
329
+ # can identify rare diseases in text using the GARD dictionary from neo4j
330
+ # and map a GARD ID, name, or synonym to all of the related synonyms for searching APIs
331
+ from nltk import tokenize as nltk_tokenize
332
+ class GARD_Search:
333
+ def __init__(self):
334
+ import json, codecs
335
+ #These are opened locally so that garbage collection removes them from memory
336
+ with codecs.open('gard-id-name-synonyms.json', 'r', 'utf-8-sig') as f:
337
+ diseases = json.load(f)
338
+ from nltk.corpus import stopwords
339
+ STOPWORDS = set(stopwords.words('english'))
340
+
341
+ #keys are going to be disease names, values are going to be the GARD ID, set up this way bc dictionaries are faster lookup than lists
342
+ GARD_dict = {}
343
+ #Find out what the length of the longest disease name sequence is, of all names and synonyms. This is used by get_diseases
344
+ max_length = -1
345
+ for entry in diseases:
346
+ if entry['name'] not in GARD_dict.keys():
347
+ s = entry['name'].lower().strip()
348
+ if s not in STOPWORDS and len(s)>5:
349
+ GARD_dict[s] = entry['gard_id']
350
+ #compare length
351
+ max_length = max(max_length,len(s.split()))
352
+
353
+ if entry['synonyms']:
354
+ for synonym in entry['synonyms']:
355
+ if synonym not in GARD_dict.keys():
356
+ s = synonym.lower().strip()
357
+ if s not in STOPWORDS and len(s)>5:
358
+ GARD_dict[s] = entry['gard_id']
359
+ max_length = max(max_length,len(s.split()))
360
+
361
+ self.GARD_dict = GARD_dict
362
+ self.max_length = max_length
363
+
364
+ def __str__(self) -> str:
365
+ return '''Instantiation: rd_identify = GARD_Search()
366
+ Calling: diseases, ids = rd_identify(text)
367
+ Autosearch: search_terms = rd_identify.autosearch(searchterm)
368
+ '''
369
+
370
+ def __call__(self, sentence:str) -> Tuple[List[str], List[str]]:
371
+ return self.get_diseases(sentence)
372
+
373
+ #Works much faster if broken down into sentences.
374
+ #compares every phrase in a sentence to see if it matches anything in the GARD dictionary of diseases.
375
+ def get_diseases(self, sentence:str) -> Tuple[List[str], List[str]]:
376
+ tokens = [s.lower().strip() for s in nltk_tokenize.word_tokenize(sentence)]
377
+ diseases = []
378
+ ids = []
379
+ i=0
380
+ #Iterates through every word, builds string that is max_length or less to compare.
381
+ while i <len(tokens):
382
+ #Find out the length of the comparison string, either max_length or less. This brings algorithm from O(n^2) to O(n) time
383
+ compare_length = min(len(tokens)-i, self.max_length)
384
+
385
+ #Compares longest sequences first and goes down until there is a match
386
+ #print('(start compare_length)',compare_length)
387
+ while compare_length>0:
388
+ s = ' '.join(tokens[i:i+compare_length])
389
+ if s.lower() in self.GARD_dict.keys():
390
+ diseases.append(s)
391
+ ids.append(self.GARD_dict[s.lower()])
392
+ #Need to skip over the next few indexes
393
+ i+=compare_length-1
394
+ break
395
+ else:
396
+ compare_length-=1
397
+ i+=1
398
+ return diseases,ids
399
+
400
+ #Can search by 7-digit GARD_ID, 12-digit "GARD:{GARD_ID}", matched search term, or arbitrary search term
401
+ #Returns list of terms to search by
402
+ # search_term_list = autosearch(search_term, GARD_dict)
403
+ def autosearch(self, searchterm:Union[str,int], matching=2) -> List[str]:
404
+ #comparisons below only handly strings, allows int input
405
+ if type(searchterm) is not str:
406
+ searchterm = str(searchterm)
407
+
408
+ #for the disease names to match
409
+ searchterm = searchterm.lower()
410
+
411
+ while matching>=1:
412
+ #search in form of 'GARD:0000001'
413
+ if 'gard:' in searchterm and len(searchterm)==12:
414
+ searchterm = searchterm.replace('gard:','GARD:')
415
+ l = [k for k,v in self.GARD_dict.items() if v==searchterm]
416
+ l.sort(reverse=True, key=lambda x:len(x))
417
+ if len(l)>0:
418
+ print("SEARCH TERM MATCHED TO GARD DICTIONARY. SEARCHING FOR: ",l)
419
+ return l
420
+
421
+ #can take int or str of digits of variable input
422
+ #search in form of 777 or '777' or '00777' or '0000777'
423
+ elif searchterm[0].isdigit() and searchterm[-1].isdigit():
424
+ if len(searchterm)>7:
425
+ raise ValueError('GARD ID IS NOT VALID. RE-ENTER SEARCH TERM')
426
+ searchterm = 'GARD:'+'0'*(7-len(str(searchterm)))+str(searchterm)
427
+ l = [k for k,v in self.GARD_dict.items() if v==searchterm]
428
+ l.sort(reverse=True, key=lambda x:len(x))
429
+ if len(l)>0:
430
+ print("SEARCH TERM MATCHED TO GARD DICTIONARY. SEARCHING FOR: ",l)
431
+ return l
432
+
433
+ #search in form of 'mackay shek carr syndrome' and returns all synonyms ('retinal degeneration with nanophthalmos, cystic macular degeneration, and angle closure glaucoma', 'retinal degeneration, nanophthalmos, glaucoma', 'mackay shek carr syndrome')
434
+ #considers the GARD ID as the lemma, and the search term as one form. maps the form to the lemma and then uses that lemma to find all related forms in the GARD dict.
435
+ elif searchterm in self.GARD_dict.keys():
436
+ l = [k for k,v in self.GARD_dict.items() if v==self.GARD_dict[searchterm]]
437
+ l.sort(reverse=True, key=lambda x:len(x))
438
+ print("SEARCH TERM MATCHED TO GARD DICTIONARY. SEARCHING FOR: ",l)
439
+ return l
440
+
441
+ else:
442
+ #This can be replaced with some other common error in user input that is easily fixed
443
+ searchterm = searchterm.replace(' ','-')
444
+ searchterm = searchterm.replace("'s","")
445
+ return autosearch(self, searchterm, matching-1)
446
+ print("SEARCH TERM DID NOT MATCH TO GARD DICTIONARY. SEARCHING BY USER INPUT")
447
+ return [searchterm]
448
+
449
+ ## Section: BioBERT-based epidemiology NER Model (EpiExtract4GARD)
450
+ from nltk import tokenize as nltk_tokenize
451
+ from dataclasses import dataclass
452
+ from torch.utils.data.dataset import Dataset
453
+ from torch import nn
454
+ import numpy as np
455
+ from unidecode import unidecode
456
+ import re
457
+ from transformers import BertConfig, AutoModelForTokenClassification, BertTokenizer, Trainer
458
+ from unidecode import unidecode
459
+ from collections import OrderedDict
460
+ from more_itertools import pairwise
461
+ import json
462
+ import pandas as pd
463
+
464
+ # Subsection: Processing the abstracts into the correct data format
465
+ @dataclass
466
+ class NERInput:
467
+ """
468
+ A single training/test example for token classification.
469
+
470
+ Args:
471
+ guid: Unique id for the example.
472
+ words: list. The words of the sequence.
473
+ labels: (Optional) list. The labels for each word of the sequence. This should be
474
+ specified for train and dev examples, but not for test examples.
475
+ """
476
+ guid: str
477
+ words: List[str]
478
+ labels: Optional[List[str]]
479
+
480
+
481
+ @dataclass
482
+ class InputFeatures:
483
+ """
484
+ A single set of features of data.
485
+ Property names are the same names as the corresponding inputs to a model.
486
+ """
487
+ input_ids: List[int]
488
+ attention_mask: List[int]
489
+ token_type_ids: Optional[List[int]] = None
490
+ label_ids: Optional[List[int]] = None
491
+
492
+ class NerDataset(Dataset):
493
+ features: List[InputFeatures]
494
+ pad_token_label_id: int = nn.CrossEntropyLoss().ignore_index
495
+ # Use cross entropy ignore_index as padding label id so that only
496
+ # real label ids contribute to the loss later.
497
+
498
+ def __init__(
499
+ self,
500
+ abstract: str,
501
+ tokenizer: BertTokenizer,
502
+ config: BertConfig,
503
+ ):
504
+ # TODO clean up all this to leverage built-in features of tokenizers
505
+ ner_inputs = self.abstract2NERinputs(abstract)
506
+
507
+ self.features = self.convert_NERinputs_to_features(
508
+ ner_inputs,
509
+ config,
510
+ tokenizer,
511
+ cls_token_at_end=bool(config.model_type in ["xlnet"]),
512
+ # xlnet has a cls token at the end
513
+ cls_token=tokenizer.cls_token,
514
+ cls_token_segment_id=2 if config.model_type in ["xlnet"] else 0,
515
+ sep_token=tokenizer.sep_token,
516
+ sep_token_extra=False,
517
+ # roberta uses an extra separator b/w pairs of sentences, cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805
518
+ pad_on_left=bool(tokenizer.padding_side == "left"),
519
+ pad_token_segment_id=tokenizer.pad_token_type_id,
520
+ pad_token_label_id=self.pad_token_label_id,
521
+ )
522
+ self.ner_inputs = ner_inputs
523
+
524
+ def __len__(self):
525
+ return len(self.features)
526
+
527
+ def __getitem__(self, i) -> InputFeatures:
528
+ return self.features[i]
529
+
530
+ #Preprocessing function, turns abstracts into sentences
531
+ def str2sents(self, string:str) -> List[str]:
532
+ superscripts = re.findall('<sup>.</sup>', string)
533
+ for i in range(len(superscripts)):
534
+ string = re.sub('<sup>.</sup>', '^'+superscripts[i][5], string)
535
+ string = re.sub("<.{1,4}>| *| ", " ", string)
536
+ string = re.sub("^ |$|™|®|•|…", "" , string)
537
+ string = re.sub("♀", "female" , string)
538
+ string = re.sub("♂", "male" , string)
539
+ string = unidecode(string)
540
+ string = string.strip()
541
+ sentences = nltk_tokenize.sent_tokenize(string)
542
+ return sentences
543
+
544
+
545
+ def abstract2NERinputs(self, abstract:str) -> List[NERInput]:
546
+ guid_index = 0
547
+ sentences = self.str2sents(abstract)
548
+ ner_inputs = [NERInput(str(guid), nltk_tokenize.word_tokenize(sent), ["O" for i in range(len(nltk_tokenize.word_tokenize(sent)))]) for guid, sent in enumerate(sentences)]
549
+ return ner_inputs
550
+
551
+ def convert_NERinputs_to_features(self,
552
+ ner_inputs: List[NERInput],
553
+ model_config: BertConfig,
554
+ bert_tokenizer: BertTokenizer,
555
+ cls_token_at_end=False,
556
+ cls_token="[CLS]",
557
+ cls_token_segment_id=1,
558
+ sep_token="[SEP]",
559
+ sep_token_extra=False,
560
+ pad_on_left=False,
561
+ pad_token_segment_id=0,
562
+ pad_token_label_id=-100,
563
+ sequence_a_segment_id=0,
564
+ mask_padding_with_zero=True,
565
+ ) -> List[InputFeatures]:
566
+
567
+ label2id = model_config.label2id
568
+ pad_token = model_config.pad_token_id
569
+ max_seq_length = model_config.max_position_embeddings
570
+
571
+ features = []
572
+
573
+ for (input_index, ner_input) in enumerate(ner_inputs):
574
+ tokens = []
575
+ label_ids = []
576
+ for word, label in zip(ner_input.words, ner_input.labels):
577
+ word_tokens = bert_tokenizer.tokenize(word)
578
+
579
+ # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
580
+ if len(word_tokens) > 0:
581
+ tokens.extend(word_tokens)
582
+ # Use the real label id for the first token of the word, and padding ids for the remaining tokens
583
+ label_ids.extend([label2id[label]] + [pad_token_label_id] * (len(word_tokens) - 1))
584
+
585
+ # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
586
+ special_tokens_count = bert_tokenizer.num_special_tokens_to_add()
587
+ if len(tokens) > max_seq_length - special_tokens_count:
588
+ tokens = tokens[: (max_seq_length - special_tokens_count)]
589
+ label_ids = label_ids[: (max_seq_length - special_tokens_count)]
590
+
591
+ # The convention in BERT is:
592
+ # (a) For sequence pairs:
593
+ # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
594
+ # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
595
+ # (b) For single sequences:
596
+ # tokens: [CLS] the dog is hairy . [SEP]
597
+ # type_ids: 0 0 0 0 0 0 0
598
+ #
599
+ # Where "type_ids" are used to indicate whether this is the first
600
+ # sequence or the second sequence. The embedding vectors for `type=0` and
601
+ # `type=1` were learned during pre-training and are added to the wordpiece
602
+ # embedding vector (and position vector). This is not *strictly* necessary
603
+ # since the [SEP] token unambiguously separates the sequences, but it makes
604
+ # it easier for the model to learn the concept of sequences.
605
+ #
606
+ # For classification tasks, the first vector (corresponding to [CLS]) is
607
+ # used as as the "sentence vector". Note that this only makes sense because
608
+ # the entire model is fine-tuned.
609
+ tokens += [sep_token]
610
+ label_ids += [pad_token_label_id]
611
+ if sep_token_extra:
612
+ # roberta uses an extra separator b/w pairs of sentences
613
+ tokens += [sep_token]
614
+ label_ids += [pad_token_label_id]
615
+ segment_ids = [sequence_a_segment_id] * len(tokens)
616
+
617
+ if cls_token_at_end:
618
+ tokens += [cls_token]
619
+ label_ids += [pad_token_label_id]
620
+ segment_ids += [cls_token_segment_id]
621
+ else:
622
+ tokens = [cls_token] + tokens
623
+ label_ids = [pad_token_label_id] + label_ids
624
+ segment_ids = [cls_token_segment_id] + segment_ids
625
+
626
+ input_ids = bert_tokenizer.convert_tokens_to_ids(tokens)
627
+
628
+ # The mask has 1 for real tokens and 0 for padding tokens. Only real
629
+ # tokens are attended to.
630
+ input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
631
+
632
+ # Zero-pad up to the sequence length.
633
+ padding_length = max_seq_length - len(input_ids)
634
+ if pad_on_left:
635
+ input_ids = ([pad_token] * padding_length) + input_ids
636
+ input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
637
+ segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids
638
+ label_ids = ([pad_token_label_id] * padding_length) + label_ids
639
+ else:
640
+ input_ids += [pad_token] * padding_length
641
+ input_mask += [0 if mask_padding_with_zero else 1] * padding_length
642
+ segment_ids += [pad_token_segment_id] * padding_length
643
+ label_ids += [pad_token_label_id] * padding_length
644
+
645
+ assert len(input_ids) == max_seq_length
646
+ assert len(input_mask) == max_seq_length
647
+ assert len(segment_ids) == max_seq_length
648
+ assert len(label_ids) == max_seq_length
649
+
650
+ if "token_type_ids" not in bert_tokenizer.model_input_names:
651
+ segment_ids = None
652
+
653
+ features.append(
654
+ InputFeatures(
655
+ input_ids=input_ids, attention_mask=input_mask, token_type_ids=segment_ids, label_ids=label_ids
656
+ )
657
+ )
658
+ return features
659
+
660
+ # Subsection: Actual NER Pipeline
661
+ class NER_Pipeline:
662
+ def __init__(self, name_or_path_to_model_folder:str = "ncats/EpiExtract4GARD-v2"):
663
+ self.bert_tokenizer = BertTokenizer.from_pretrained(name_or_path_to_model_folder)
664
+ #model = AutoModelForTokenClassification.from_pretrained(name_or_path_to_model_folder)
665
+ self.config = BertConfig.from_pretrained(name_or_path_to_model_folder)
666
+ self.labels = {re.sub(".-","",label) for label in self.config.label2id.keys() if label != "O"}
667
+ self.trainer = Trainer(model=AutoModelForTokenClassification.from_pretrained(name_or_path_to_model_folder))
668
+
669
+ def __str__(self):
670
+ return "Instantiation: pipe = NER_Pipeline({})".format(name_or_path_to_model_folder) +"\n Calling: output_dict = pipe(text)"
671
+
672
+ def __call__(self, text:str, rd_identify:Union[GARD_Search,None] = None):
673
+ output_dict = {label:[] for label in self.labels}
674
+
675
+ dataset = NerDataset(text, self.bert_tokenizer, self.config)
676
+ predictions, label_ids, _ = self.trainer.predict(dataset)
677
+ preds_list, _ = self.align_predictions(predictions, label_ids)
678
+ #dataset.ner_inputs.labels = preds_list
679
+ for ner_input, sent_pred_list in zip(dataset.ner_inputs, preds_list):
680
+ ner_input.labels = sent_pred_list
681
+
682
+ for sentence in dataset.ner_inputs:
683
+ entity = []
684
+ for idx, (current, nxt) in enumerate(pairwise(sentence.labels)):
685
+ #Main concatenation algorithm
686
+ '''
687
+ Accounts for all variations of
688
+ current = ['O','B-Tag`','I-Tag`']
689
+ nxt = ["O","B-Tag`","I-Tag`","B-Tag``","I-Tag``"]
690
+ and accounts for the final case
691
+ '''
692
+ if current != "O":
693
+ current_ib, current_tag = self.get_tag(current)
694
+ if nxt =="O":
695
+ #add word at idx
696
+ entity.append(sentence.words[idx])
697
+ output_dict[current_tag].append(' '.join(entity))
698
+ entity.clear()
699
+ else:
700
+ nxt_ib, nxt_tag = self.get_tag(nxt)
701
+ if nxt_tag == current_tag:
702
+ if nxt_ib =="B":
703
+ entity.append(sentence.words[idx])
704
+ output_dict[current_tag].append(' '.join(entity))
705
+ entity.clear()
706
+ #Continued "I"
707
+ else:
708
+ entity.append(sentence.words[idx])
709
+ else:
710
+ entity.append(sentence.words[idx])
711
+ output_dict[current_tag].append(' '.join(entity))
712
+ entity.clear()
713
+
714
+ #last case
715
+ if idx==len(sentence.labels)-2 and nxt!="O":
716
+ _, nxt_tag = self.get_tag(nxt)
717
+ entity.append(sentence.words[idx+1])
718
+ output_dict[nxt_tag].append(' '.join(entity))
719
+ entity.clear()
720
+
721
+ if 'DIS' not in output_dict.keys() and rd_identify:
722
+ output_dict['DIS'] = []
723
+ output_dict['IDS'] = []
724
+ for sentence in dataset.ner_inputs:
725
+ diseases,ids = rd_identify(' '.join(sentence.words))
726
+ output_dict['DIS']+=diseases
727
+ output_dict['IDS']+=ids
728
+
729
+ #Clean up Output Dict
730
+ for entity, output in output_dict.items():
731
+ if not output:
732
+ output_dict[entity] = None
733
+ elif entity !='STAT':
734
+ #remove duplicates from list but keep ordering instead of using sets
735
+ output = list(OrderedDict.fromkeys(output))
736
+ output_dict[entity] = output
737
+
738
+ if output_dict['EPI'] and (output_dict['STAT'] or output_dict['LOC'] or output_dict['DATE']):
739
+ return output_dict
740
+
741
+ def align_predictions(self, predictions: np.ndarray, label_ids: np.ndarray) -> Tuple[List[int], List[int]]:
742
+ preds = np.argmax(predictions, axis=2)
743
+ batch_size, seq_len = preds.shape
744
+ out_label_list = [[] for _ in range(batch_size)]
745
+ preds_list = [[] for _ in range(batch_size)]
746
+ for i in range(batch_size):
747
+ for j in range(seq_len):
748
+ if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index:
749
+ out_label_list[i].append(self.config.id2label[label_ids[i][j]])
750
+ preds_list[i].append(self.config.id2label[preds[i][j]])
751
+
752
+ return preds_list, out_label_list
753
+
754
+ def get_tag(self, entity_name: str) -> Tuple[str, str]:
755
+ if entity_name.startswith("B-"):
756
+ bi = "B"
757
+ tag = entity_name[2:]
758
+ elif entity_name.startswith("I-"):
759
+ bi = "I"
760
+ tag = entity_name[2:]
761
+ else:
762
+ # It's not in B-, I- format
763
+ # Default to I- for continuation.
764
+ bi = "I"
765
+ tag = entity_name
766
+ return bi, tag
767
+
768
+
769
+ #This ensures that there is a standardized ordering of df columns while ensuring dynamics with multiple models. This is used by search_term_extraction.
770
+ def order_labels(entity_classes:Union[Set[str],List[str]]) -> List[str]:
771
+ ordered_labels = []
772
+ label_order = ['DIS','ABRV','EPI','STAT','LOC','DATE','SEX','ETHN']
773
+ ordered_labels = [label for label in label_order if label in entity_classes]
774
+ #This adds any extra entities (from yet-to-be-created models) to the end of the ordered list of labels
775
+ for entity in entity_classes:
776
+ if entity not in label_order:
777
+ ordered_labels.append(entity)
778
+ return ordered_labels
779
+
780
+ # Given a search term and max results to return, this will acquire PubMed IDs and Title+Abstracts and Classify them as epidemiological.
781
+ # It then extracts Epidemiologic Information[Disease GARD ID, Disease Name, Location, Epidemiologic Identifier, Epidemiologic Statistic] for each abstract
782
+ # results = search_term_extraction(search_term, maxResults, filering, NER_pipeline, labels, extract_diseases, GARD_dict, max_length, classify_model_vars)
783
+ #Returns a Pandas dataframe
784
+ def search_term_extraction(search_term:Union[int,str], maxResults:int, filtering:str, #for abstract search
785
+ epi_ner:NER_Pipeline, #for biobert extraction
786
+ GARD_Search:GARD_Search, extract_diseases:bool, #for disease extraction
787
+ epi_classify:Classify_Pipeline) -> pd.DataFrame: #for classification
788
+
789
+
790
+ #Format of Output
791
+ ordered_labels = order_labels(epi_ner.labels)
792
+ if extract_diseases:
793
+ columns = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi','IDS','DIS']+ordered_labels
794
+ else:
795
+ columns = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi']+ordered_labels
796
+
797
+ results = pd.DataFrame(columns=columns)
798
+
799
+ ##Check to see if search term maps to anything in the GARD dictionary, if so it pulls up all synonyms for the search
800
+ search_term_list = GARD_Search.autosearch(search_term)
801
+
802
+ #Gather title+abstracts into a dictionary {pmid:abstract}
803
+ pmid_abs = search_getAbs(search_term_list, maxResults, filtering)
804
+
805
+ for pmid, abstract in pmid_abs.items():
806
+ epi_prob, isEpi = epi_classify(abstract)
807
+ if isEpi:
808
+ if extract_diseases:
809
+ extraction = epi_ner(abstract, GARD_Search)
810
+ else:
811
+ extraction = epi_ner(abstract)
812
+
813
+ if extraction:
814
+ extraction.update({'PMID':pmid, 'ABSTRACT':abstract, 'EPI_PROB':epi_prob, 'IsEpi':isEpi})
815
+ #Slow dataframe update
816
+ results = results.append(extraction, ignore_index=True)
817
+
818
+ print(len(results),'abstracts classified as epidemiological.')
819
+ return results.sort_values('EPI_PROB', ascending=False)
820
+
821
+ #Returns a Pandas dataframe
822
+ def streamlit_extraction(search_term:Union[int,str], maxResults:int, filtering:str, #for abstract search
823
+ epi_ner:NER_Pipeline, #for biobert extraction
824
+ GARD_Search:GARD_Search, extract_diseases:bool, #for disease extraction
825
+ epi_classify:Classify_Pipeline) -> pd.DataFrame: #for classification
826
+
827
+
828
+ #Format of Output
829
+ ordered_labels = order_labels(epi_ner.labels)
830
+ if extract_diseases:
831
+ columns = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi','IDS','DIS']+ordered_labels
832
+ else:
833
+ columns = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi']+ordered_labels
834
+
835
+ results = pd.DataFrame(columns=columns)
836
+
837
+ ##Check to see if search term maps to anything in the GARD dictionary, if so it pulls up all synonyms for the search
838
+ search_term_list = GARD_Search.autosearch(search_term)
839
+ if len(search_term_list)>1:
840
+ st.write("SEARCH TERM MATCHED TO GARD DICTIONARY. SEARCHING FOR: "+ str(search_term_list))
841
+ else:
842
+ st.write("SEARCHING FOR: "+ str(search_term_list))
843
+
844
+ #Gather title+abstracts into a dictionary {pmid:abstract}
845
+ pmid_abs, sankey_initial = streamlit_getAbs(search_term_list, maxResults, filtering)
846
+
847
+ if len(pmid_abs)==0:
848
+ st.error('No results were gathered. Enter a new search term.')
849
+ return None, None, None
850
+ else:
851
+ found, relevant = sankey_initial
852
+ epidemiologic = 0
853
+ i = 0
854
+ my_bar = st.progress(i)
855
+ percent_at_step = 100/len(pmid_abs)
856
+ for pmid, abstract in pmid_abs.items():
857
+ epi_prob, isEpi = epi_classify(abstract)
858
+ if isEpi:
859
+ if extract_diseases:
860
+ extraction = epi_ner(abstract, GARD_Search)
861
+ else:
862
+ extraction = epi_ner(abstract)
863
+
864
+ if extraction:
865
+ extraction.update({'PMID':pmid, 'ABSTRACT':abstract, 'EPI_PROB':epi_prob, 'IsEpi':isEpi})
866
+ #Slow dataframe update
867
+ results = results.append(extraction, ignore_index=True)
868
+ epidemiologic+=1
869
+ i+=1
870
+ my_bar.progress(min(round(i*percent_at_step/100,1),1.0))
871
+
872
+ st.write(len(results),'abstracts classified as epidemiological.')
873
+
874
+ sankey_data = (found, relevant, epidemiologic)
875
+ #Export the name and GARD ID to the ap for better integration on page.
876
+ name = search_term_list[-1].capitalize()
877
+ name_gardID = (name, GARD_dict[search_term_list[-1]])
878
+
879
+ return results.sort_values('PROB_OF_EPI', ascending=False), sankey_data, name_gardID
880
+
881
+ #Identical to search_term_extraction, except it returns a JSON object instead of a df
882
+ def API_extraction(search_term:Union[int,str], maxResults:int, filtering:str, #for abstract search
883
+ epi_ner:NER_Pipeline, #for biobert extraction
884
+ GARD_Search:GARD_Search, extract_diseases:bool, #for disease extraction
885
+ epi_classify:Classify_Pipeline) -> json: #for classification
886
+
887
+ #Format of Output
888
+ ordered_labels = order_labels(epi_ner.labels)
889
+ if extract_diseases:
890
+ json_output = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi','IDS','DIS']+ordered_labels
891
+ else:
892
+ json_output = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi']+ordered_labels
893
+
894
+ results = {'entries':[]}
895
+
896
+ ##Check to see if search term maps to anything in the GARD dictionary, if so it pulls up all synonyms for the search
897
+ search_term_list = GARD_Search.autosearch(search_term)
898
+
899
+ #Gather title+abstracts into a dictionary {pmid:abstract}
900
+ pmid_abs = search_getAbs(search_term_list, maxResults, filtering)
901
+
902
+ for pmid, abstract in pmid_abs.items():
903
+ epi_prob, isEpi = epi_classify(abstract)
904
+ if isEpi:
905
+ if extract_diseases:
906
+ extraction = epi_ner(abstract, GARD_Search)
907
+ else:
908
+ extraction = epi_ner(abstract)
909
+ if extraction:
910
+ extraction.update({'PMID':pmid, 'ABSTRACT':abstract, 'EPI_PROB':epi_prob})
911
+ extraction = OrderedDict([(term, extraction[term]) for term in json_output if term in extraction.keys()])
912
+ results['entries'].append(extraction)
913
+
914
+ #sort
915
+ results['entries'].sort(reverse=True, key=lambda x:x['EPI_PROB'])
916
+
917
+ # float is not JSON serializable, so must convert all epi_probs to str
918
+ # This returns a map object, which is not JSON serializable
919
+ # results['entries'] = map(lambda entry:str(entry['EPI_PROB']),results['entries'])
920
+
921
+ for entry in results['entries']:
922
+ entry['EPI_PROB'] = str(entry['EPI_PROB'])
923
+
924
+ return json.dumps(results)
925
+
926
+ ## Section: Deprecated Functions
927
+ import requests
928
+ import xml.etree.ElementTree as ET
929
+
930
+ def search_Pubmed_API(searchterm_list:Union[List[str],str], maxResults:int) -> Dict[str,str]: #returns a dictionary of {pmids:abstracts}
931
+ print('search_Pubmed_API is DEPRECATED. UTILIZE search_NCBI_API for NCBI ENTREZ API results. Utilize search_getAbs for most comprehensive results.')
932
+ return search_NCBI_API(searchterm_list, maxResults)
933
+
934
+ def search_NCBI_API(searchterm_list:Union[List[str],str], maxResults:int) -> Dict[str,str]: #returns a dictionary of {pmids:abstracts}
935
+ print('search_NCBI_API is DEPRECATED. Utilize search_getAbs for most comprehensive results.')
936
+ pmid_to_abs = {}
937
+ i = 0
938
+
939
+ #type validation, allows string or list input
940
+ if type(searchterm_list)!=list:
941
+ if type(searchterm_list)==str:
942
+ searchterm_list = [searchterm_list]
943
+ else:
944
+ searchterm_list = list(searchterm_list)
945
+
946
+ #gathers pmids into a set first
947
+ for dz in searchterm_list:
948
+ # get results from searching for disease name through PubMed API
949
+ term = ''
950
+ dz_words = dz.split()
951
+ for word in dz_words:
952
+ term += word + '%20'
953
+ query = term[:-3]
954
+ url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term='+query
955
+ r = requests.get(url)
956
+ root = ET.fromstring(r.content)
957
+
958
+ # loop over resulting articles
959
+ for result in root.iter('IdList'):
960
+ pmids = [pmid.text for pmid in result.iter('Id')]
961
+ if i >= maxResults:
962
+ break
963
+ for pmid in pmids:
964
+ if pmid not in pmid_to_abs.keys():
965
+ abstract = PMID_getAb(pmid)
966
+ if len(abstract)>5:
967
+ pmid_to_abs[pmid]=abstract
968
+ i+=1
969
+
970
+ return pmid_to_abs
971
+
972
+ def search_EBI_API(searchterm_list:Union[List[str],str], maxResults:int) -> Dict[str,str]: #returns a dictionary of {pmids:abstracts}
973
+ print('DEPRECATED. Utilize search_getAbs for most comprehensive results.')
974
+ pmids_abs = {}
975
+ i = 0
976
+
977
+ #type validation, allows string or list input
978
+ if type(searchterm_list)!=list:
979
+ if type(searchterm_list)==str:
980
+ searchterm_list = [searchterm_list]
981
+ else:
982
+ searchterm_list = list(searchterm_list)
983
+
984
+ #gathers pmids into a set first
985
+ for dz in searchterm_list:
986
+ if i >= maxResults:
987
+ break
988
+ term = ''
989
+ dz_words = dz.split()
990
+ for word in dz_words:
991
+ term += word + '%20'
992
+ query = term[:-3]
993
+ url = 'https://www.ebi.ac.uk/europepmc/webservices/rest/search?query='+query+'&resulttype=core'
994
+ r = requests.get(url)
995
+ root = ET.fromstring(r.content)
996
+
997
+ # loop over resulting articles
998
+ for result in root.iter('result'):
999
+ if i >= maxResults:
1000
+ break
1001
+ pmids = [pmid.text for pmid in result.iter('id')]
1002
+ if len(pmids) > 0:
1003
+ pmid = pmids[0]
1004
+ if pmid[0].isdigit():
1005
+ abstracts = [abstract.text for abstract in result.iter('abstractText')]
1006
+ titles = [title.text for title in result.iter('title')]
1007
+ if len(abstracts) > 0:# and len(abstracts[0])>5:
1008
+ pmids_abs[pmid] = titles[0]+' '+abstracts[0]
1009
+ i+=1
1010
+
1011
+ return pmids_abs