wzkariampuzha commited on
Commit
5454234
·
1 Parent(s): d14bad6

Upload epi_pipeline.py

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