prajwal967 commited on
Commit
5ee65f8
1 Parent(s): 6e2eae6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +218 -0
app.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import json
4
+ import tempfile
5
+ import gradio as gr
6
+ from transformers import (
7
+ TrainingArguments,
8
+ HfArgumentParser,
9
+ )
10
+
11
+ from ehr_deidentification.ner_datasets import DatasetCreator
12
+ from ehr_deidentification.sequence_tagging import SequenceTagger
13
+ from ehr_deidentification.sequence_tagging.arguments import (
14
+ ModelArguments,
15
+ DataTrainingArguments,
16
+ EvaluationArguments,
17
+ )
18
+ from ehr_deidentification.deid import TextDeid
19
+
20
+ model_details = {
21
+ "post_process":"argmax",
22
+ "threshold": None,
23
+ "model_name_or_path":"obi/deid_bert_i2b2",
24
+ "task_name":"ner",
25
+ "notation":"BILOU",
26
+ "ner_types":["PATIENT", "STAFF", "AGE", "DATE", "PHONE", "ID", "EMAIL", "PATORG", "LOC", "HOSP", "OTHERPHI"],
27
+ "test_file":"./data/ner_datasets/test.jsonl",
28
+ "output_predictions_file": "./data/predictions/predictions.jsonl",
29
+ "truncation":True,
30
+ "max_length":512,
31
+ "label_all_tokens":False,
32
+ "return_entity_level_metrics":True,
33
+ "text_column_name":"tokens",
34
+ "label_column_name":"labels",
35
+ "output_dir":"./run/models",
36
+ "logging_dir":"./run/logs",
37
+ "overwrite_output_dir":False,
38
+ "do_train":False,
39
+ "do_eval":False,
40
+ "do_predict":True,
41
+ "report_to":["tensorboard"],
42
+ "per_device_train_batch_size":0,
43
+ "per_device_eval_batch_size":16,
44
+ "logging_steps":1000
45
+ }
46
+
47
+ threshold_map = {
48
+ "99.5":4.656325975101986e-06,
49
+ "99.6":2.971213699798517e-06,
50
+ "99.7":1.8982457699258832e-06,
51
+ "99.8":1.5751602444631296e-06,
52
+ "99.9":1.148090024407608e-06,
53
+ }
54
+
55
+ def get_highlights(deid_text):
56
+ pattern = re.compile('<<(PATIENT|STAFF|AGE|DATE|LOCATION|PHONE|ID|EMAIL|PATORG|HOSPITAL|OTHERPHI):(.)*?>>')
57
+ tag_pattern = re.compile('<<(PATIENT|STAFF|AGE|DATE|LOCATION|PHONE|ID|EMAIL|PATORG|HOSPITAL|OTHERPHI):')
58
+ text_list = []
59
+ current_start = 0
60
+ current_end = 0
61
+ for match in re.finditer(pattern, deid_text):
62
+ full_start, full_end = match.span()
63
+ sub_text = deid_text[full_start:full_end]
64
+ sub_match = re.search(tag_pattern, sub_text)
65
+ sub_span = sub_match.span()
66
+ tag_length = sub_match.span()[1] - sub_match.span()[0]
67
+ yield (deid_text[current_start:full_start], None)
68
+ yield (deid_text[full_start+sub_span[1]:full_end-2], sub_match.string[sub_span[0]+2:sub_span[1]-1])
69
+ current_start = full_end
70
+ yield (deid_text[full_end:], None)
71
+
72
+ def deid(text, threshold):
73
+
74
+ if threshold in ["99.5"]:
75
+ model_details['post_process'] = 'threshold'
76
+ model_details['threshold'] = threshold_map[threshold]
77
+ else:
78
+ model_details['post_process'] = 'argmax'
79
+ model_details['threshold'] = None
80
+
81
+ note = {"text": text, "meta": {"note_id": "note_1", "patient_id": "patient_1"}, "spans": []}
82
+
83
+ dataset_creator = DatasetCreator(
84
+ sentencizer='en_core_sci_lg',
85
+ tokenizer='clinical',
86
+ abbreviations=None,
87
+ max_tokens=128,
88
+ max_prev_sentence_token=32,
89
+ max_next_sentence_token=32,
90
+ default_chunk_size=32,
91
+ ignore_label='NA'
92
+ )
93
+
94
+ parser = HfArgumentParser((
95
+ ModelArguments,
96
+ DataTrainingArguments,
97
+ EvaluationArguments,
98
+ TrainingArguments
99
+ ))
100
+
101
+ text_deid = TextDeid(notation='BILOU', span_constraint='super_strict')
102
+
103
+ with tempfile.NamedTemporaryFile("w+", delete=False) as tmp:
104
+ tmp.write(json.dumps(model_details) + '\n')
105
+ tmp.seek(0)
106
+ model_args, data_args, evaluation_args, training_args = \
107
+ parser.parse_json_file(json_file=os.path.abspath(tmp.name))
108
+
109
+ with tempfile.NamedTemporaryFile("w+", delete=False) as tmp:
110
+ tmp.write(json.dumps(note) + '\n')
111
+ tmp.seek(0)
112
+ ner_notes = dataset_creator.create(
113
+ input_file=tmp.name,
114
+ mode='predict',
115
+ notation='BILOU',
116
+ token_text_key='text',
117
+ metadata_key='meta',
118
+ note_id_key='note_id',
119
+ label_key='label',
120
+ span_text_key='spans'
121
+ )
122
+
123
+ with tempfile.NamedTemporaryFile("w+") as tmp:
124
+ for ner_sentence in ner_notes:
125
+ tmp.write(json.dumps(ner_sentence) + '\n')
126
+ tmp.seek(0)
127
+ sequence_tagger = SequenceTagger(
128
+ task_name=data_args.task_name,
129
+ notation=data_args.notation,
130
+ ner_types=data_args.ner_types,
131
+ model_name_or_path=model_args.model_name_or_path,
132
+ config_name=model_args.config_name,
133
+ tokenizer_name=model_args.tokenizer_name,
134
+ post_process=model_args.post_process,
135
+ cache_dir=model_args.cache_dir,
136
+ model_revision=model_args.model_revision,
137
+ use_auth_token=model_args.use_auth_token,
138
+ threshold=model_args.threshold,
139
+ do_lower_case=data_args.do_lower_case,
140
+ fp16=training_args.fp16,
141
+ seed=training_args.seed,
142
+ local_rank=training_args.local_rank
143
+ )
144
+ sequence_tagger.load()
145
+ sequence_tagger.set_predict(
146
+ test_file=tmp.name,
147
+ max_test_samples=data_args.max_predict_samples,
148
+ preprocessing_num_workers=data_args.preprocessing_num_workers,
149
+ overwrite_cache=data_args.overwrite_cache
150
+ )
151
+ sequence_tagger.setup_trainer(training_args=training_args)
152
+
153
+
154
+ sequence_tagger.predict(output_predictions_file='test.jsonl')
155
+
156
+ with tempfile.NamedTemporaryFile("w+", delete=False) as tmp:
157
+ tmp.write(json.dumps(note) + '\n')
158
+ tmp.seek(0)
159
+ deid_notes = text_deid.run_deid(
160
+ input_file=tmp.name,
161
+ predictions_file='test.jsonl',
162
+ deid_strategy='replace_informative',
163
+ keep_age=False,
164
+ metadata_key='meta',
165
+ note_id_key='note_id',
166
+ tokens_key='tokens',
167
+ predictions_key='predictions',
168
+ text_key='text',
169
+ )
170
+ deid_notes_remove = text_deid.run_deid(
171
+ input_file=tmp.name,
172
+ predictions_file='test.jsonl',
173
+ deid_strategy='remove',
174
+ keep_age=False,
175
+ metadata_key='meta',
176
+ note_id_key='note_id',
177
+ tokens_key='tokens',
178
+ predictions_key='predictions',
179
+ text_key='text',
180
+ )
181
+ deid_note = list(deid_notes)[0]
182
+ deid_text = deid_note['deid_text']
183
+ deid_note_remove = list(deid_notes_remove)[0]
184
+ deid_text_remove = deid_note_remove['deid_text']
185
+ return [highlight_text for highlight_text in get_highlights(deid_text)], deid_text_remove
186
+
187
+ 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.", "No bias"], ["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.", "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',
188
+ 'No bias']]
189
+
190
+ choices = ["No bias", "99.5"]
191
+ radio_input = gr.inputs.Radio(choices, type="value", default=None, label='RECALL BIAS')
192
+
193
+ title = 'DE-IDENTIFICATION OF ELECTRONIC HEALTH RECORDS'
194
+ description = 'Model to remove private information (PHI) from raw medical notes. The recall bias can be used to remove PHI more aggressively.'
195
+ gradio_input = gr.inputs.Textbox(
196
+ lines=10,
197
+ placeholder='Enter text with PHI',
198
+ label='RAW MEDICAL NOTE'
199
+ )
200
+ gradio_highlight_output = gr.outputs.HighlightedText(
201
+ label='LABELED DE-IDENTIFIED MEDICAL NOTE',
202
+ )
203
+ gradio_text_output = gr.outputs.Textbox(
204
+ label='DE-IDENTIFIED MEDICAL NOTE'
205
+ )
206
+
207
+ iface = gr.Interface(
208
+ title=title,
209
+ description=description,
210
+ theme='huggingface',
211
+ layout='horizontal',
212
+ examples=examples,
213
+ fn=deid,
214
+ inputs=[gradio_input, radio_input],
215
+ outputs=[gradio_highlight_output, gradio_text_output],
216
+
217
+ )
218
+ iface.launch()