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

Delete epi_pipeline.py

Browse files
Files changed (1) hide show
  1. epi_pipeline.py +0 -1016
epi_pipeline.py DELETED
@@ -1,1016 +0,0 @@
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#+"&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_Model'):
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('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({})".format(model) +"\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
- from more_itertools import pairwise
463
- import json
464
- import pandas as pd
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: Optional[List[str]]
481
-
482
-
483
- @dataclass
484
- class InputFeatures:
485
- """
486
- A single set of features of data.
487
- Property names are the same names as the corresponding inputs to a model.
488
- """
489
- input_ids: List[int]
490
- attention_mask: List[int]
491
- token_type_ids: Optional[List[int]] = None
492
- label_ids: Optional[List[int]] = None
493
-
494
- class NerDataset(Dataset):
495
- features: List[InputFeatures]
496
- pad_token_label_id: int = nn.CrossEntropyLoss().ignore_index
497
- # Use cross entropy ignore_index as padding label id so that only
498
- # real label ids contribute to the loss later.
499
-
500
- def __init__(
501
- self,
502
- abstract: str,
503
- tokenizer: BertTokenizer,
504
- config: BertConfig,
505
- ):
506
- # TODO clean up all this to leverage built-in features of tokenizers
507
- ner_inputs = self.abstract2NERinputs(abstract)
508
-
509
- self.features = self.convert_NERinputs_to_features(
510
- ner_inputs,
511
- config,
512
- tokenizer,
513
- cls_token_at_end=bool(config.model_type in ["xlnet"]),
514
- # xlnet has a cls token at the end
515
- cls_token=tokenizer.cls_token,
516
- cls_token_segment_id=2 if config.model_type in ["xlnet"] else 0,
517
- sep_token=tokenizer.sep_token,
518
- sep_token_extra=False,
519
- # roberta uses an extra separator b/w pairs of sentences, cf. github.com/pytorch/fairseq/commit/1684e166e3da03f5b600dbb7855cb98ddfcd0805
520
- pad_on_left=bool(tokenizer.padding_side == "left"),
521
- pad_token_segment_id=tokenizer.pad_token_type_id,
522
- pad_token_label_id=self.pad_token_label_id,
523
- )
524
- self.ner_inputs = ner_inputs
525
-
526
- def __len__(self):
527
- return len(self.features)
528
-
529
- def __getitem__(self, i) -> InputFeatures:
530
- return self.features[i]
531
-
532
- #Preprocessing function, turns abstracts into sentences
533
- def str2sents(self, string:str) -> List[str]:
534
- superscripts = re.findall('<sup>.</sup>', string)
535
- for i in range(len(superscripts)):
536
- string = re.sub('<sup>.</sup>', '^'+superscripts[i][5], string)
537
- string = re.sub("<.{1,4}>| *| ", " ", string)
538
- string = re.sub("^ |$|™|®|•|…", "" , string)
539
- string = re.sub("♀", "female" , string)
540
- string = re.sub("♂", "male" , string)
541
- string = unidecode(string)
542
- string = string.strip()
543
- sentences = nltk_tokenize.sent_tokenize(string)
544
- return sentences
545
-
546
-
547
- def abstract2NERinputs(self, abstract:str) -> List[NERInput]:
548
- guid_index = 0
549
- sentences = self.str2sents(abstract)
550
- 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)]
551
- return ner_inputs
552
-
553
- def convert_NERinputs_to_features(self,
554
- ner_inputs: List[NERInput],
555
- model_config: BertConfig,
556
- bert_tokenizer: BertTokenizer,
557
- cls_token_at_end=False,
558
- cls_token="[CLS]",
559
- cls_token_segment_id=1,
560
- sep_token="[SEP]",
561
- sep_token_extra=False,
562
- pad_on_left=False,
563
- pad_token_segment_id=0,
564
- pad_token_label_id=-100,
565
- sequence_a_segment_id=0,
566
- mask_padding_with_zero=True,
567
- ) -> List[InputFeatures]:
568
-
569
- label2id = model_config.label2id
570
- pad_token = model_config.pad_token_id
571
- max_seq_length = model_config.max_position_embeddings
572
-
573
- features = []
574
-
575
- for (input_index, ner_input) in enumerate(ner_inputs):
576
- tokens = []
577
- label_ids = []
578
- for word, label in zip(ner_input.words, ner_input.labels):
579
- word_tokens = bert_tokenizer.tokenize(word)
580
-
581
- # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space.
582
- if len(word_tokens) > 0:
583
- tokens.extend(word_tokens)
584
- # Use the real label id for the first token of the word, and padding ids for the remaining tokens
585
- label_ids.extend([label2id[label]] + [pad_token_label_id] * (len(word_tokens) - 1))
586
-
587
- # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa.
588
- special_tokens_count = bert_tokenizer.num_special_tokens_to_add()
589
- if len(tokens) > max_seq_length - special_tokens_count:
590
- tokens = tokens[: (max_seq_length - special_tokens_count)]
591
- label_ids = label_ids[: (max_seq_length - special_tokens_count)]
592
-
593
- # The convention in BERT is:
594
- # (a) For sequence pairs:
595
- # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
596
- # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
597
- # (b) For single sequences:
598
- # tokens: [CLS] the dog is hairy . [SEP]
599
- # type_ids: 0 0 0 0 0 0 0
600
- #
601
- # Where "type_ids" are used to indicate whether this is the first
602
- # sequence or the second sequence. The embedding vectors for `type=0` and
603
- # `type=1` were learned during pre-training and are added to the wordpiece
604
- # embedding vector (and position vector). This is not *strictly* necessary
605
- # since the [SEP] token unambiguously separates the sequences, but it makes
606
- # it easier for the model to learn the concept of sequences.
607
- #
608
- # For classification tasks, the first vector (corresponding to [CLS]) is
609
- # used as as the "sentence vector". Note that this only makes sense because
610
- # the entire model is fine-tuned.
611
- tokens += [sep_token]
612
- label_ids += [pad_token_label_id]
613
- if sep_token_extra:
614
- # roberta uses an extra separator b/w pairs of sentences
615
- tokens += [sep_token]
616
- label_ids += [pad_token_label_id]
617
- segment_ids = [sequence_a_segment_id] * len(tokens)
618
-
619
- if cls_token_at_end:
620
- tokens += [cls_token]
621
- label_ids += [pad_token_label_id]
622
- segment_ids += [cls_token_segment_id]
623
- else:
624
- tokens = [cls_token] + tokens
625
- label_ids = [pad_token_label_id] + label_ids
626
- segment_ids = [cls_token_segment_id] + segment_ids
627
-
628
- input_ids = bert_tokenizer.convert_tokens_to_ids(tokens)
629
-
630
- # The mask has 1 for real tokens and 0 for padding tokens. Only real
631
- # tokens are attended to.
632
- input_mask = [1 if mask_padding_with_zero else 0] * len(input_ids)
633
-
634
- # Zero-pad up to the sequence length.
635
- padding_length = max_seq_length - len(input_ids)
636
- if pad_on_left:
637
- input_ids = ([pad_token] * padding_length) + input_ids
638
- input_mask = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask
639
- segment_ids = ([pad_token_segment_id] * padding_length) + segment_ids
640
- label_ids = ([pad_token_label_id] * padding_length) + label_ids
641
- else:
642
- input_ids += [pad_token] * padding_length
643
- input_mask += [0 if mask_padding_with_zero else 1] * padding_length
644
- segment_ids += [pad_token_segment_id] * padding_length
645
- label_ids += [pad_token_label_id] * padding_length
646
-
647
- assert len(input_ids) == max_seq_length
648
- assert len(input_mask) == max_seq_length
649
- assert len(segment_ids) == max_seq_length
650
- assert len(label_ids) == max_seq_length
651
-
652
- if "token_type_ids" not in bert_tokenizer.model_input_names:
653
- segment_ids = None
654
-
655
- features.append(
656
- InputFeatures(
657
- input_ids=input_ids, attention_mask=input_mask, token_type_ids=segment_ids, label_ids=label_ids
658
- )
659
- )
660
- return features
661
-
662
- # Subsection: Actual NER Pipeline
663
- class NER_Pipeline:
664
- def __init__(self, name_or_path_to_model_folder:str = "ncats/EpiExtract4GARD-v2"):
665
- self.bert_tokenizer = BertTokenizer.from_pretrained(name_or_path_to_model_folder)
666
- #model = AutoModelForTokenClassification.from_pretrained(name_or_path_to_model_folder)
667
- self.config = BertConfig.from_pretrained(name_or_path_to_model_folder)
668
- self.labels = {re.sub(".-","",label) for label in self.config.label2id.keys() if label != "O"}
669
- self.trainer = Trainer(model=AutoModelForTokenClassification.from_pretrained(name_or_path_to_model_folder))
670
-
671
- def __str__(self):
672
- return "Instantiation: pipe = NER_Pipeline({})".format(name_or_path_to_model_folder) +"\n Calling: output_dict = pipe(text)"
673
-
674
- def __call__(self, text:str, rd_identify:Union[GARD_Search,None] = None):
675
- output_dict = {label:[] for label in self.labels}
676
-
677
- dataset = NerDataset(text, self.bert_tokenizer, self.config)
678
- predictions, label_ids, _ = self.trainer.predict(dataset)
679
- preds_list, _ = self.align_predictions(predictions, label_ids)
680
- #dataset.ner_inputs.labels = preds_list
681
- for ner_input, sent_pred_list in zip(dataset.ner_inputs, preds_list):
682
- ner_input.labels = sent_pred_list
683
-
684
- for sentence in dataset.ner_inputs:
685
- entity = []
686
- for idx, (current, nxt) in enumerate(pairwise(sentence.labels)):
687
- #Main concatenation algorithm
688
- '''
689
- Accounts for all variations of
690
- current = ['O','B-Tag`','I-Tag`']
691
- nxt = ["O","B-Tag`","I-Tag`","B-Tag``","I-Tag``"]
692
- and accounts for the final case
693
- '''
694
- if current != "O":
695
- current_ib, current_tag = self.get_tag(current)
696
- if nxt =="O":
697
- #add word at idx
698
- entity.append(sentence.words[idx])
699
- output_dict[current_tag].append(' '.join(entity))
700
- entity.clear()
701
- else:
702
- nxt_ib, nxt_tag = self.get_tag(nxt)
703
- if nxt_tag == current_tag:
704
- if nxt_ib =="B":
705
- entity.append(sentence.words[idx])
706
- output_dict[current_tag].append(' '.join(entity))
707
- entity.clear()
708
- #Continued "I"
709
- else:
710
- entity.append(sentence.words[idx])
711
- else:
712
- entity.append(sentence.words[idx])
713
- output_dict[current_tag].append(' '.join(entity))
714
- entity.clear()
715
-
716
- #last case
717
- if idx==len(sentence.labels)-2 and nxt!="O":
718
- _, nxt_tag = self.get_tag(nxt)
719
- entity.append(sentence.words[idx+1])
720
- output_dict[nxt_tag].append(' '.join(entity))
721
- entity.clear()
722
-
723
- if 'DIS' not in output_dict.keys() and rd_identify:
724
- output_dict['DIS'] = []
725
- output_dict['IDS'] = []
726
- for sentence in dataset.ner_inputs:
727
- diseases,ids = rd_identify(' '.join(sentence.words))
728
- output_dict['DIS']+=diseases
729
- output_dict['IDS']+=ids
730
-
731
- #Clean up Output Dict
732
- for entity, output in output_dict.items():
733
- if not output:
734
- output_dict[entity] = None
735
- elif entity !='STAT':
736
- #remove duplicates from list but keep ordering instead of using sets
737
- output = list(OrderedDict.fromkeys(output))
738
- output_dict[entity] = output
739
-
740
- if output_dict['EPI'] and output_dict['STAT']:
741
- return output_dict
742
-
743
- def align_predictions(self, predictions: np.ndarray, label_ids: np.ndarray) -> Tuple[List[int], List[int]]:
744
- preds = np.argmax(predictions, axis=2)
745
- batch_size, seq_len = preds.shape
746
- out_label_list = [[] for _ in range(batch_size)]
747
- preds_list = [[] for _ in range(batch_size)]
748
- for i in range(batch_size):
749
- for j in range(seq_len):
750
- if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index:
751
- out_label_list[i].append(self.config.id2label[label_ids[i][j]])
752
- preds_list[i].append(self.config.id2label[preds[i][j]])
753
-
754
- return preds_list, out_label_list
755
-
756
- def get_tag(self, entity_name: str) -> Tuple[str, str]:
757
- if entity_name.startswith("B-"):
758
- bi = "B"
759
- tag = entity_name[2:]
760
- elif entity_name.startswith("I-"):
761
- bi = "I"
762
- tag = entity_name[2:]
763
- else:
764
- # It's not in B-, I- format
765
- # Default to I- for continuation.
766
- bi = "I"
767
- tag = entity_name
768
- return bi, tag
769
-
770
-
771
- #This ensures that there is a standardized ordering of df columns while ensuring dynamics with multiple models. This is used by search_term_extraction.
772
- def order_labels(entity_classes:Union[Set[str],List[str]]) -> List[str]:
773
- ordered_labels = []
774
- label_order = ['DIS','ABRV','EPI','STAT','LOC','DATE','SEX','ETHN']
775
- ordered_labels = [label for label in label_order if label in entity_classes]
776
- #This adds any extra entities (from yet-to-be-created models) to the end of the ordered list of labels
777
- for entity in entity_classes:
778
- if entity not in label_order:
779
- ordered_labels.append(entity)
780
- return ordered_labels
781
-
782
- # Given a search term and max results to return, this will acquire PubMed IDs and Title+Abstracts and Classify them as epidemiological.
783
- # It then extracts Epidemiologic Information[Disease GARD ID, Disease Name, Location, Epidemiologic Identifier, Epidemiologic Statistic] for each abstract
784
- # results = search_term_extraction(search_term, maxResults, filering, NER_pipeline, labels, extract_diseases, GARD_dict, max_length, classify_model_vars)
785
- #Returns a Pandas dataframe
786
- def search_term_extraction(search_term:Union[int,str], maxResults:int, filtering:str, #for abstract search
787
- epi_ner:NER_Pipeline, #for biobert extraction
788
- GARD_Search:GARD_Search, extract_diseases:bool, #for disease extraction
789
- epi_classify:Classify_Pipeline) -> pd.DataFrame: #for classification
790
-
791
-
792
- #Format of Output
793
- ordered_labels = order_labels(epi_ner.labels)
794
- if extract_diseases:
795
- columns = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi','IDS','DIS']+ordered_labels
796
- else:
797
- columns = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi']+ordered_labels
798
-
799
- results = pd.DataFrame(columns=columns)
800
-
801
- ##Check to see if search term maps to anything in the GARD dictionary, if so it pulls up all synonyms for the search
802
- search_term_list = GARD_Search.autosearch(search_term)
803
-
804
- #Gather title+abstracts into a dictionary {pmid:abstract}
805
- pmid_abs = search_getAbs(search_term_list, maxResults, filtering)
806
-
807
- for pmid, abstract in pmid_abs.items():
808
- epi_prob, isEpi = epi_classify(abstract)
809
- if isEpi:
810
- if extract_diseases:
811
- extraction = epi_ner(abstract, GARD_Search)
812
- else:
813
- extraction = epi_ner(abstract)
814
-
815
- if extraction:
816
- extraction.update({'PMID':pmid, 'ABSTRACT':abstract, 'EPI_PROB':epi_prob, 'IsEpi':isEpi})
817
- #Slow dataframe update
818
- results = results.append(extraction, ignore_index=True)
819
-
820
- print(len(results),'abstracts classified as epidemiological.')
821
- return results.sort_values('EPI_PROB', ascending=False)
822
-
823
- #Returns a Pandas dataframe
824
- def streamlit_extraction(search_term:Union[int,str], maxResults:int, filtering:str, #for abstract search
825
- epi_ner:NER_Pipeline, #for biobert extraction
826
- GARD_Search:GARD_Search, extract_diseases:bool, #for disease extraction
827
- epi_classify:Classify_Pipeline) -> pd.DataFrame: #for classification
828
-
829
- #Format of Output
830
- ordered_labels = order_labels(epi_ner.labels)
831
- if extract_diseases:
832
- columns = ['PMID', 'ABSTRACT','PROB_OF_EPI','IsEpi','IDS','DIS']+ordered_labels
833
- else:
834
- columns = ['PMID', 'ABSTRACT','PROB_OF_EPI','IsEpi']+ordered_labels
835
-
836
- results = pd.DataFrame(columns=columns)
837
-
838
- ##Check to see if search term maps to anything in the GARD dictionary, if so it pulls up all synonyms for the search
839
- search_term_list = GARD_Search.autosearch(search_term)
840
- if len(search_term_list)>1:
841
- st.write("SEARCH TERM MATCHED TO GARD DICTIONARY. SEARCHING FOR: "+ str(search_term_list))
842
- else:
843
- st.write("SEARCHING FOR: "+ str(search_term_list))
844
-
845
- #Gather title+abstracts into a dictionary {pmid:abstract}
846
- pmid_abs, sankey_initial = streamlit_getAbs(search_term_list, maxResults, filtering)
847
-
848
- if len(pmid_abs)==0:
849
- st.error('No results were gathered. Enter a new search term.')
850
- return None, None, None
851
- else:
852
- found, relevant = sankey_initial
853
- epidemiologic = 0
854
- i = 0
855
- my_bar = st.progress(i)
856
- percent_at_step = 100/len(pmid_abs)
857
- for pmid, abstract in pmid_abs.items():
858
- epi_prob, isEpi = epi_classify(abstract)
859
- if isEpi:
860
- if extract_diseases:
861
- extraction = epi_ner(abstract, GARD_Search)
862
- else:
863
- extraction = epi_ner(abstract)
864
-
865
- if extraction:
866
- extraction.update({'PMID':pmid, 'ABSTRACT':abstract, 'PROB_OF_EPI':epi_prob, 'IsEpi':isEpi})
867
- #Slow dataframe update
868
- results = results.append(extraction, ignore_index=True)
869
- epidemiologic+=1
870
- i+=1
871
- my_bar.progress(min(round(i*percent_at_step/100,1),1.0))
872
-
873
- st.write(len(results),'abstracts classified as epidemiological.')
874
-
875
- sankey_data = (found, relevant, epidemiologic)
876
- #Export the name and GARD ID to the ap for better integration on page.
877
- name = search_term_list[-1].capitalize()
878
-
879
- if search_term_list[-1] in GARD_Search.GARD_dict.keys():
880
- disease_gardID = (name, GARD_Search.GARD_dict[search_term_list[-1]])
881
- else:
882
- disease_gardID = (name, None)
883
-
884
- return results.sort_values('PROB_OF_EPI', ascending=False), sankey_data, disease_gardID
885
-
886
- #Identical to search_term_extraction, except it returns a JSON object instead of a df
887
- def API_extraction(search_term:Union[int,str], maxResults:int, filtering:str, #for abstract search
888
- epi_ner:NER_Pipeline, #for biobert extraction
889
- GARD_Search:GARD_Search, extract_diseases:bool, #for disease extraction
890
- epi_classify:Classify_Pipeline) -> json: #for classification
891
-
892
- #Format of Output
893
- ordered_labels = order_labels(epi_ner.labels)
894
- if extract_diseases:
895
- json_output = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi','IDS','DIS']+ordered_labels
896
- else:
897
- json_output = ['PMID', 'ABSTRACT','EPI_PROB','IsEpi']+ordered_labels
898
-
899
- results = {'entries':[]}
900
-
901
- ##Check to see if search term maps to anything in the GARD dictionary, if so it pulls up all synonyms for the search
902
- search_term_list = GARD_Search.autosearch(search_term)
903
-
904
- #Gather title+abstracts into a dictionary {pmid:abstract}
905
- pmid_abs = search_getAbs(search_term_list, maxResults, filtering)
906
-
907
- for pmid, abstract in pmid_abs.items():
908
- epi_prob, isEpi = epi_classify(abstract)
909
- if isEpi:
910
- if extract_diseases:
911
- extraction = epi_ner(abstract, GARD_Search)
912
- else:
913
- extraction = epi_ner(abstract)
914
- if extraction:
915
- extraction.update({'PMID':pmid, 'ABSTRACT':abstract, 'EPI_PROB':epi_prob})
916
- extraction = OrderedDict([(term, extraction[term]) for term in json_output if term in extraction.keys()])
917
- results['entries'].append(extraction)
918
-
919
- #sort
920
- results['entries'].sort(reverse=True, key=lambda x:x['EPI_PROB'])
921
-
922
- # float is not JSON serializable, so must convert all epi_probs to str
923
- # This returns a map object, which is not JSON serializable
924
- # results['entries'] = map(lambda entry:str(entry['EPI_PROB']),results['entries'])
925
-
926
- for entry in results['entries']:
927
- entry['EPI_PROB'] = str(entry['EPI_PROB'])
928
-
929
- return json.dumps(results)
930
-
931
- ## Section: Deprecated Functions
932
- import requests
933
- import xml.etree.ElementTree as ET
934
-
935
- def search_Pubmed_API(searchterm_list:Union[List[str],str], maxResults:int) -> Dict[str,str]: #returns a dictionary of {pmids:abstracts}
936
- print('search_Pubmed_API is DEPRECATED. UTILIZE search_NCBI_API for NCBI ENTREZ API results. Utilize search_getAbs for most comprehensive results.')
937
- return search_NCBI_API(searchterm_list, maxResults)
938
-
939
- def search_NCBI_API(searchterm_list:Union[List[str],str], maxResults:int) -> Dict[str,str]: #returns a dictionary of {pmids:abstracts}
940
- print('search_NCBI_API is DEPRECATED. Utilize search_getAbs for most comprehensive results.')
941
- pmid_to_abs = {}
942
- i = 0
943
-
944
- #type validation, allows string or list input
945
- if type(searchterm_list)!=list:
946
- if type(searchterm_list)==str:
947
- searchterm_list = [searchterm_list]
948
- else:
949
- searchterm_list = list(searchterm_list)
950
-
951
- #gathers pmids into a set first
952
- for dz in searchterm_list:
953
- # get results from searching for disease name through PubMed API
954
- term = ''
955
- dz_words = dz.split()
956
- for word in dz_words:
957
- term += word + '%20'
958
- query = term[:-3]
959
- url = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&term='+query
960
- r = requests.get(url)
961
- root = ET.fromstring(r.content)
962
-
963
- # loop over resulting articles
964
- for result in root.iter('IdList'):
965
- pmids = [pmid.text for pmid in result.iter('Id')]
966
- if i >= maxResults:
967
- break
968
- for pmid in pmids:
969
- if pmid not in pmid_to_abs.keys():
970
- abstract = PMID_getAb(pmid)
971
- if len(abstract)>5:
972
- pmid_to_abs[pmid]=abstract
973
- i+=1
974
-
975
- return pmid_to_abs
976
-
977
- def search_EBI_API(searchterm_list:Union[List[str],str], maxResults:int) -> Dict[str,str]: #returns a dictionary of {pmids:abstracts}
978
- print('DEPRECATED. Utilize search_getAbs for most comprehensive results.')
979
- pmids_abs = {}
980
- i = 0
981
-
982
- #type validation, allows string or list input
983
- if type(searchterm_list)!=list:
984
- if type(searchterm_list)==str:
985
- searchterm_list = [searchterm_list]
986
- else:
987
- searchterm_list = list(searchterm_list)
988
-
989
- #gathers pmids into a set first
990
- for dz in searchterm_list:
991
- if i >= maxResults:
992
- break
993
- term = ''
994
- dz_words = dz.split()
995
- for word in dz_words:
996
- term += word + '%20'
997
- query = term[:-3]
998
- url = 'https://www.ebi.ac.uk/europepmc/webservices/rest/search?query='+query+'&resulttype=core'
999
- r = requests.get(url)
1000
- root = ET.fromstring(r.content)
1001
-
1002
- # loop over resulting articles
1003
- for result in root.iter('result'):
1004
- if i >= maxResults:
1005
- break
1006
- pmids = [pmid.text for pmid in result.iter('id')]
1007
- if len(pmids) > 0:
1008
- pmid = pmids[0]
1009
- if pmid[0].isdigit():
1010
- abstracts = [abstract.text for abstract in result.iter('abstractText')]
1011
- titles = [title.text for title in result.iter('title')]
1012
- if len(abstracts) > 0:# and len(abstracts[0])>5:
1013
- pmids_abs[pmid] = titles[0]+' '+abstracts[0]
1014
- i+=1
1015
-
1016
- return pmids_abs