madrigal1 commited on
Commit
e792d28
1 Parent(s): 64077c2

Create new file

Browse files
Files changed (1) hide show
  1. app.py +275 -0
app.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import sys
4
+ import json
5
+ import tempfile
6
+ import gradio as gr
7
+
8
+ from transformers import (
9
+ TrainingArguments,
10
+ HfArgumentParser,
11
+ )
12
+
13
+ from robust_deid.ner_datasets import DatasetCreator
14
+ from robust_deid.sequence_tagging import SequenceTagger
15
+ from robust_deid.sequence_tagging.arguments import (
16
+ ModelArguments,
17
+ DataTrainingArguments,
18
+ EvaluationArguments,
19
+ )
20
+ from robust_deid.deid import TextDeid
21
+
22
+ class App(object):
23
+
24
+ def __init__(
25
+ self,
26
+ model,
27
+ threshold,
28
+ span_constraint='super_strict',
29
+ sentencizer='en_core_sci_sm',
30
+ tokenizer='clinical',
31
+ max_tokens=128,
32
+ max_prev_sentence_token=32,
33
+ max_next_sentence_token=32,
34
+ default_chunk_size=32,
35
+ ignore_label='NA'
36
+ ):
37
+ # Create the dataset creator object
38
+ self._dataset_creator = DatasetCreator(
39
+ sentencizer=sentencizer,
40
+ tokenizer=tokenizer,
41
+ max_tokens=max_tokens,
42
+ max_prev_sentence_token=max_prev_sentence_token,
43
+ max_next_sentence_token=max_next_sentence_token,
44
+ default_chunk_size=default_chunk_size,
45
+ ignore_label=ignore_label
46
+ )
47
+ parser = HfArgumentParser((
48
+ ModelArguments,
49
+ DataTrainingArguments,
50
+ EvaluationArguments,
51
+ TrainingArguments
52
+ ))
53
+ model_config = App._get_model_config()
54
+ model_config['model_name_or_path'] = App._get_model_map()[model]
55
+ if threshold == 'No threshold':
56
+ model_config['post_process'] = 'argmax'
57
+ model_config['threshold'] = None
58
+ else:
59
+ model_config['post_process'] = 'threshold_max'
60
+ model_config['threshold'] = \
61
+ App._get_threshold_map()[model_config['model_name_or_path']][threshold]
62
+ print(model_config)
63
+ #sys.exit(0)
64
+ with tempfile.NamedTemporaryFile("w+", delete=False) as tmp:
65
+ tmp.write(json.dumps(model_config) + '\n')
66
+ tmp.seek(0)
67
+ # If we pass only one argument to the script and it's the path to a json file,
68
+ # let's parse it to get our arguments.
69
+ self._model_args, self._data_args, self._evaluation_args, self._training_args = \
70
+ parser.parse_json_file(json_file=tmp.name)
71
+ # Initialize the text deid object
72
+ self._text_deid = TextDeid(notation=self._data_args.notation, span_constraint=span_constraint)
73
+ # Initialize the sequence tagger
74
+ self._sequence_tagger = SequenceTagger(
75
+ task_name=self._data_args.task_name,
76
+ notation=self._data_args.notation,
77
+ ner_types=self._data_args.ner_types,
78
+ model_name_or_path=self._model_args.model_name_or_path,
79
+ config_name=self._model_args.config_name,
80
+ tokenizer_name=self._model_args.tokenizer_name,
81
+ post_process=self._model_args.post_process,
82
+ cache_dir=self._model_args.cache_dir,
83
+ model_revision=self._model_args.model_revision,
84
+ use_auth_token=self._model_args.use_auth_token,
85
+ threshold=self._model_args.threshold,
86
+ do_lower_case=self._data_args.do_lower_case,
87
+ fp16=self._training_args.fp16,
88
+ seed=self._training_args.seed,
89
+ local_rank=self._training_args.local_rank
90
+ )
91
+ # Load the required functions of the sequence tagger
92
+ self._sequence_tagger.load()
93
+
94
+
95
+ def get_ner_dataset(self, notes_file):
96
+ ner_notes = self._dataset_creator.create(
97
+ input_file=notes_file,
98
+ mode='predict',
99
+ notation=self._data_args.notation,
100
+ token_text_key='text',
101
+ metadata_key='meta',
102
+ note_id_key='note_id',
103
+ label_key='label',
104
+ span_text_key='spans'
105
+ )
106
+ return ner_notes
107
+
108
+ def get_predictions(self, ner_notes_file):
109
+ # Set the required data and predictions of the sequence tagger
110
+ # Can also use self._data_args.test_file instead of ner_dataset_file (make sure it matches ner_dataset_file)
111
+ self._sequence_tagger.set_predict(
112
+ test_file=ner_notes_file,
113
+ max_test_samples=self._data_args.max_predict_samples,
114
+ preprocessing_num_workers=self._data_args.preprocessing_num_workers,
115
+ overwrite_cache=self._data_args.overwrite_cache
116
+ )
117
+ # Initialize the huggingface trainer
118
+ self._sequence_tagger.setup_trainer(training_args=self._training_args)
119
+ # Store predictions in the specified file
120
+ predictions = self._sequence_tagger.predict()
121
+ return predictions
122
+
123
+ def get_deid_text_removed(self, notes_file, predictions_file):
124
+ deid_notes = self._text_deid.run_deid(
125
+ input_file=notes_file,
126
+ predictions_file=predictions_file,
127
+ deid_strategy='remove',
128
+ keep_age=False,
129
+ metadata_key='meta',
130
+ note_id_key='note_id',
131
+ tokens_key='tokens',
132
+ predictions_key='predictions',
133
+ text_key='text',
134
+ )
135
+ return deid_notes
136
+
137
+ def get_deid_text_replaced(self, notes_file, predictions_file):
138
+ deid_notes = self._text_deid.run_deid(
139
+ input_file=notes_file,
140
+ predictions_file=predictions_file,
141
+ deid_strategy='replace_informative',
142
+ keep_age=False,
143
+ metadata_key='meta',
144
+ note_id_key='note_id',
145
+ tokens_key='tokens',
146
+ predictions_key='predictions',
147
+ text_key='text',
148
+ )
149
+ return deid_notes
150
+
151
+
152
+ @staticmethod
153
+ def _get_highlights(deid_text):
154
+ pattern = re.compile('<<(PATIENT|STAFF|AGE|DATE|LOCATION|PHONE|ID|EMAIL|PATORG|HOSPITAL|OTHERPHI):(.)*?>>')
155
+ tag_pattern = re.compile('<<(PATIENT|STAFF|AGE|DATE|LOCATION|PHONE|ID|EMAIL|PATORG|HOSPITAL|OTHERPHI):')
156
+ text_list = []
157
+ current_start = 0
158
+ current_end = 0
159
+ for match in re.finditer(pattern, deid_text):
160
+ full_start, full_end = match.span()
161
+ sub_text = deid_text[full_start:full_end]
162
+ sub_match = re.search(tag_pattern, sub_text)
163
+ sub_span = sub_match.span()
164
+ tag_length = sub_match.span()[1] - sub_match.span()[0]
165
+ yield (deid_text[current_start:full_start], None)
166
+ yield (deid_text[full_start+sub_span[1]:full_end-2], sub_match.string[sub_span[0]+2:sub_span[1]-1])
167
+ current_start = full_end
168
+ yield (deid_text[full_end:], None)
169
+
170
+ @staticmethod
171
+ def _get_model_map():
172
+ return {
173
+ 'OBI-RoBERTa De-ID':'obi/deid_roberta_i2b2',
174
+ 'OBI-ClinicalBERT De-ID':'obi/deid_bert_i2b2'
175
+ }
176
+
177
+ @staticmethod
178
+ def _get_threshold_map():
179
+ return {
180
+ 'obi/deid_bert_i2b2':{"99.5": 4.656325975101986e-06, "99.7":1.8982457699258832e-06},
181
+ 'obi/deid_roberta_i2b2':{"99.5": 2.4362972672812125e-05, "99.7":2.396420546444644e-06}
182
+ }
183
+
184
+ @staticmethod
185
+ def _get_model_config():
186
+ return {
187
+ "post_process":None,
188
+ "threshold": None,
189
+ "model_name_or_path":None,
190
+ "task_name":"ner",
191
+ "notation":"BILOU",
192
+ "ner_types":["PATIENT", "STAFF", "AGE", "DATE", "PHONE", "ID", "EMAIL", "PATORG", "LOC", "HOSP", "OTHERPHI"],
193
+ "truncation":True,
194
+ "max_length":512,
195
+ "label_all_tokens":False,
196
+ "return_entity_level_metrics":True,
197
+ "text_column_name":"tokens",
198
+ "label_column_name":"labels",
199
+ "output_dir":"./run/models",
200
+ "logging_dir":"./run/logs",
201
+ "overwrite_output_dir":False,
202
+ "do_train":False,
203
+ "do_eval":False,
204
+ "do_predict":True,
205
+ "report_to":["tensorboard"],
206
+ "per_device_train_batch_size":0,
207
+ "per_device_eval_batch_size":16,
208
+ "logging_steps":1000
209
+ }
210
+
211
+ def deid(text, model, threshold):
212
+ notes = [{"text": text, "meta": {"note_id": "note_1", "patient_id": "patient_1"}, "spans": []}]
213
+ app = App(model, threshold)
214
+ # Create temp notes file
215
+ with tempfile.NamedTemporaryFile("w+", delete=False) as tmp:
216
+ for note in notes:
217
+ tmp.write(json.dumps(note) + '\n')
218
+ tmp.seek(0)
219
+ ner_notes = app.get_ner_dataset(tmp.name)
220
+ # Create temp ner_notes file
221
+ with tempfile.NamedTemporaryFile("w+", delete=False) as tmp:
222
+ for ner_sentence in ner_notes:
223
+ tmp.write(json.dumps(ner_sentence) + '\n')
224
+ tmp.seek(0)
225
+ predictions = app.get_predictions(tmp.name)
226
+ # Get deid text
227
+ with tempfile.NamedTemporaryFile("w+", delete=False) as tmp,\
228
+ tempfile.NamedTemporaryFile("w+", delete=False) as tmp_1:
229
+ for note in notes:
230
+ tmp.write(json.dumps(note) + '\n')
231
+ for note_prediction in predictions:
232
+ tmp_1.write(json.dumps(note_prediction) + '\n')
233
+ tmp.seek(0)
234
+ tmp_1.seek(0)
235
+ deid_text = list(app.get_deid_text_replaced(tmp.name, tmp_1.name))[0]['deid_text']
236
+ deid_text_remove = list(app.get_deid_text_removed(tmp.name, tmp_1.name))[0]['deid_text']
237
+ return [highlight_text for highlight_text in App._get_highlights(deid_text)], deid_text_remove
238
+
239
+ recall_choices = ["No threshold", "99.5", "99.7"]
240
+ recall_radio_input = gr.inputs.Radio(recall_choices, type="value", default=None, label='RECALL THRESHOLD')
241
+
242
+ model_choices = list(App._get_model_map().keys())
243
+ model_radio_input = gr.inputs.Radio(model_choices, type="value", default=None, label='DE-ID MODEL')
244
+
245
+ title = 'DE-IDENTIFICATION OF ELECTRONIC HEALTH RECORDS'
246
+ description = 'Models to remove private information (PHI/PII) from raw medical notes. The recall threshold (bias) can be used to remove PHI more aggressively.'
247
+
248
+ gradio_input = gr.inputs.Textbox(
249
+ lines=10,
250
+ placeholder='Enter text with PHI',
251
+ label='RAW MEDICAL NOTE'
252
+ )
253
+
254
+ gradio_highlight_output = gr.outputs.HighlightedText(
255
+ label='LABELED DE-IDENTIFIED MEDICAL NOTE',
256
+ )
257
+
258
+ gradio_text_output = gr.outputs.Textbox(
259
+ label='DE-IDENTIFIED MEDICAL NOTE'
260
+ )
261
+
262
+ examples = [["Physician Discharge Summary Admit date: 10/12/1982 Discharge date: 10/22/1982 Patient Information Jack Reacher, 54 y.o. male (DOB = 1/21/1928). Home Address: 123 Park Drive, San Diego, CA, 03245. Home Phone: 202-555-0199 (home). Hospital Care Team Service: Orthopedics Inpatient Attending: Roger C Kelly, MD Attending phys phone: (634)743-5135 Discharge Unit: HCS843 Primary Care Physician: Hassan V Kim, MD 512-832-5025.", "OBI-RoBERTa De-ID", "No threshold"], ["Consult NotePt: Ulysses Ogrady MC #0937884Date: 07/01/19 Williams Ct M OSCAR, JOHNNY Hyderabad, WI 62297\n\nHISTORY OF PRESENT ILLNESS: The patient is a 77-year-old-woman with long standing hypertension who presented as a Walk-in to me at the Brigham Health Center on Friday. Recently had been started q.o.d. on Clonidine since 01/15/19 to taper off of the drug. Was told to start Zestril 20 mg. q.d. again. The patient was sent to the Unit for direct admission for cardioversion and anticoagulation, with the Cardiologist, Dr. Wilson to follow.\nSOCIAL HISTORY: Lives alone, has one daughter living in Nantucket. Is a non-smoker, and does not drink alcohol.\nHOSPITAL COURSE AND TREATMENT: During admission, the patient was seen by Cardiology, Dr. Wilson, was started on IV Heparin, Sotalol 40 mg PO b.i.d. increased to 80 mg b.i.d., and had an echocardiogram. By 07-22-19 the patient had better rate control and blood pressure control but remained in atrial fibrillation. On 08.03.19, the patient was felt to be medically stable.", "OBI-RoBERTa De-ID", "99.5"], ["Consult NotePt: Ulysses Ogrady MC #0937884Date: 07/01/19 Williams Ct M OSCAR, JOHNNY Hyderabad, WI 62297\n\nHISTORY OF PRESENT ILLNESS: The patient is a 77-year-old-woman with long standing hypertension who presented as a Walk-in to me at the Brigham Health Center on Friday. Recently had been started q.o.d. on Clonidine since 01/15/19 to taper off of the drug. Was told to start Zestril 20 mg. q.d. again. The patient was sent to the Unit for direct admission for cardioversion and anticoagulation, with the Cardiologist, Dr. Wilson to follow.\nSOCIAL HISTORY: Lives alone, has one daughter living in Nantucket. Is a non-smoker, and does not drink alcohol.\nHOSPITAL COURSE AND TREATMENT: During admission, the patient was seen by Cardiology, Dr. Wilson, was started on IV Heparin, Sotalol 40 mg PO b.i.d. increased to 80 mg b.i.d., and had an echocardiogram. By 07-22-19 the patient had better rate control and blood pressure control but remained in atrial fibrillation. On 08.03.19, the patient was felt to be medically stable.", "OBI-ClinicalBERT De-ID", "99.5"], ['HPI: Pt is a 59 yo Khazakhstani male, with who was admitted to San Rafael Mount Hospital following a syncopal nauseas and was brought to Rafael Mount ED. Five weeks ago prior Anemia: On admission to Rafael Hospital, Hb/Hct: 11.6/35.5. Tobacco: Quit at 38 y/o; ETOH: 1-2 beers/week; Caffeine:\nDD:05/05/2022 DT:05/05/2022 WK:65255 :4653\nNO GROWTH TO DATE Specimen: 38:Z8912708G Collected\n\n2nd set biomarkers (WPH): Creatine Kinase Isoenzymes Hospitalized 2115 TCH for ROMI 2120 TCH new onset\n\nLab Tests Amador: the lab results show good levels of 10MG PO qd : 04/10/2021 - 05/15/2021 ACT : rosenberg 128\n placed 3/22 for bradycardia. P/G model #5435, serial # 4712198. \n\nSocial history: Married, glazier, 3 grown adult children. Has VNA. Former civil engineer, supervisor, consultant. She is looking forward to a good Christmas. She is here today',
263
+ "OBI-ClinicalBERT De-ID", 'No threshold']]
264
+
265
+ iface = gr.Interface(
266
+ title=title,
267
+ description=description,
268
+ theme='huggingface',
269
+ layout='horizontal',
270
+ examples=examples,
271
+ fn=deid,
272
+ inputs=[gradio_input, model_radio_input, recall_radio_input],
273
+ outputs=[gradio_highlight_output, gradio_text_output],
274
+ )
275
+ iface.launch()