Spaces:
Running
Running
File size: 14,870 Bytes
adc6c07 f73dc21 1841ebe 4067c90 eca4ff8 1841ebe 4067c90 bc31c45 4067c90 f73dc21 1841ebe f73dc21 4067c90 adc6c07 4067c90 f73dc21 173edcf f73dc21 1841ebe f73dc21 1841ebe f73dc21 eca4ff8 f73dc21 4067c90 bc31c45 f73dc21 adc6c07 bc31c45 f73dc21 bc31c45 adc6c07 bc31c45 f73dc21 acc1c3e bc31c45 adc6c07 bc31c45 adc6c07 f73dc21 1841ebe 4067c90 1841ebe f73dc21 4067c90 f73dc21 6a4a8e0 f73dc21 6a4a8e0 f73dc21 4067c90 f73dc21 adc6c07 f73dc21 173edcf f73dc21 173edcf f73dc21 173edcf f73dc21 173edcf f73dc21 adc6c07 173edcf fa32459 173edcf f73dc21 adc6c07 6a4a8e0 adc6c07 f73dc21 173edcf f73dc21 adc6c07 f73dc21 b3e501a 173edcf fa32459 173edcf fa32459 173edcf f73dc21 173edcf fa32459 173edcf f73dc21 173edcf fa32459 173edcf f73dc21 173edcf fa32459 173edcf f73dc21 173edcf fa32459 173edcf f73dc21 173edcf fa32459 173edcf f73dc21 173edcf fa32459 173edcf f73dc21 adc6c07 bc31c45 b3e501a adc6c07 f73dc21 173edcf f73dc21 adc6c07 f73dc21 173edcf f73dc21 a8118cc f73dc21 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 |
import re
import gradio as gr
import pandas as pd
import torch
from model import MimicTransformer
from utils import load_rule, get_attribution, get_diseases, get_drg_link, get_icd_annotations, visualize_attn, clean_text
from transformers import AutoTokenizer, AutoModel, set_seed, pipeline
torch.manual_seed(0)
set_seed(34)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
model_path = 'checkpoint_0_9113.bin'
related_tensor = torch.load('discharge_embeddings.pt')
all_summaries = pd.read_csv('all_summaries.csv')['SUMMARIES'].to_list()
similarity_tokenizer = AutoTokenizer.from_pretrained('kamalkraj/BioSimCSE-BioLinkBERT-BASE')
similarity_model = AutoModel.from_pretrained('kamalkraj/BioSimCSE-BioLinkBERT-BASE')
similarity_model.eval()
def read_model(model, path):
# model.load_state_dict(torch.load(path, map_location=torch.device('cpu')))
state_dict = torch.load(path, map_location='cpu')
model.load_state_dict({"model."+k: v for k, v in state_dict.items()}, strict=False)
return model
mimic = MimicTransformer(cutoff=512)
mimic = read_model(model=mimic, path=model_path)
tokenizer = mimic.tokenizer
mimic.eval()
# disease ner model
pipe = pipeline("token-classification", model="alvaroalon2/biobert_diseases_ner")
# default DRG summary examples
ex1 = """HEAD CT: Head CT showed no intracranial hemorrhage or mass effect, but old infarction consistent with past medical history."""
ex2 = """Radiologic studies also included a chest CT, which confirmed cavitary lesions in the left lung apex consistent with infectious tuberculosis. This also moderate-sized left pleural effusion."""
ex3 = """We have discharged Mrs Smith on regular oral Furosemide (40mg OD) and we have requested an outpatient ultrasound of her renal tract which will be performed in the next few weeks. We will review Mrs Smith in the Cardiology Outpatient Clinic in 6 weeks time."""
ex4 = """Blood tests revealed a raised BNP. An ECG showed evidence of left-ventricular hypertrophy and echocardiography revealed grossly impaired ventricular function (ejection fraction 35%). A chest X-ray demonstrated bilateral pleural effusions, with evidence of upper lobe diversion."""
ex5 = """Mrs Smith presented to A&E with worsening shortness of breath and ankle swelling. On arrival, she was tachypnoeic and hypoxic (oxygen saturation 82% on air). Clinical examination revealed reduced breath sounds and dullness to percussion in both lung bases. There was also a significant degree of lower limb oedema extending up to the mid-thigh bilaterally."""
examples = [ex1, ex2, ex3, ex4, ex5]
related_summaries = [[ex1]]
related_chosen = []
related_attn = []
related_clr_bts = []
correct_drg_text_list = []
correct_salient_words_list = []
rule_df, drg2idx, i2d, d2mdc, d2w = load_rule('MSDRG_RULE13.csv')
def mean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] #First element of model_output contains all token embeddings
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
def get_model_results(text):
text = clean_text(text)
inputs = tokenizer(text, return_tensors='pt', padding='max_length', max_length=512, truncation=True)
with torch.no_grad():
outputs = mimic(input_ids=inputs.input_ids, attention_mask=inputs.attention_mask, drg_labels=None)
attribution, reconstructed_text = get_attribution(text=text, tokenizer=tokenizer, model_outputs=outputs, inputs=inputs, k=10)
logits = outputs[0][0]
out = logits.detach().cpu()[0]
drg_code = i2d[out.argmax().item()]
print(out.topk(5))
prob = torch.nn.functional.softmax(out).max()
return {
'class': drg_code,
'prob': prob,
'attn': attribution,
'tokens': reconstructed_text,
'logits': logits
}
def find_related_summaries(text):
inputs = similarity_tokenizer(
text, padding='max_length', truncation=True, return_tensors='pt', max_length=512
)
outputs = similarity_model(**inputs)
embedding = mean_pooling(outputs, attention_mask=inputs.attention_mask)
embedding = torch.nn.functional.normalize(embedding)
scores = torch.mm(related_tensor, embedding.transpose(1,0))
scores_indices = scores.topk(k=50, dim=0)
indices, scores = scores_indices[-1], torch.round(100 * scores_indices[0], decimals=2)
summary_score_list = []
score_set = set()
for summary_idx, score in zip(indices, scores):
score = score.item()
if len(summary_score_list) == 5:
break
corresp_summary = all_summaries[summary_idx]
if score in score_set or score >= 99: # potential duplicate
continue
summary_score_list.append(
[round(score,2), corresp_summary])
score_set.add(score)
return summary_score_list
def run(text, related_discharges=False):
torch.manual_seed(0)
set_seed(34)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
# initial drg results
model_results = get_model_results(text=text)
drg_code = model_results['class']
# find diseases
diseases = get_diseases(text=text, pipe=pipe)
model_results['diseases'] = diseases
drg_link = get_drg_link(drg_code=drg_code)
icd_results = get_icd_annotations(text=text)
row = rule_df[rule_df['DRG_CODE'] == drg_code]
drg_description = row['DESCRIPTION'].values[0]
model_results['class_dsc'] = drg_description
model_results['drg_link'] = drg_link
model_results['icd_results'] = icd_results
global related_summaries
# related_summaries = generate_similar_summeries()
related_summaries = find_related_summaries(text=text)
if related_discharges:
return visualize_attn(model_results=model_results)
return (
visualize_attn(model_results=model_results),
# gr.Dataset.update(samples=related_summaries, visible=True, label='Related Discharge Summaries'),
gr.DataFrame.update(value=related_summaries, visible=True),
gr.ClearButton.update(visible=True),
gr.TextArea.update(visible=True),
gr.Button.update(visible=True),
gr.Button.update(visible=True),
gr.TextArea.update(visible=True),
gr.TextArea.update(visible=True)
)
def run_related():
global related_chosen
attn_list = []
clr_bts = []
correct_drg_list = []
correct_salient_list = []
for related in related_chosen:
text = related[0]
attn_html = run(text=text, related_discharges=True)
attn_list.append(gr.HTML.update(value=attn_html))
clr_bts.append(gr.ClearButton.update(visible=True))
correct_drg_list.append(gr.Textbox.update(visible=True))
correct_salient_list.append(gr.Textbox.update(visible=True))
if len(attn_list) != 3:
# find difference
diff = 3 - len(attn_list)
for i in range(diff):
attn_list.append(gr.HTML.update(value=''))
clr_bts.append(gr.ClearButton.update(visible=False))
correct_drg_list.append(gr.Textbox.update(visible=False))
correct_salient_list.append(gr.Textbox.update(visible=False))
return attn_list + clr_bts + correct_drg_list + correct_salient_list
def load_example(example_id):
global related_summaries
global related_chosen
sample = related_summaries[example_id][0]
cleaned_sample = sample.split('% Similarity Rate for the following Discharge Summary:\n\n')[1:]
related_chosen.append(cleaned_sample)
return prettify_text(related_chosen)
# return related_chosen
def load_df_example(df, event: gr.SelectData):
global related_chosen
discharge_summary = event.value
related_chosen.append([discharge_summary])
return prettify_text(related_chosen)
def save_results(text):
return gr.Textbox.update(value='Thank you for your input!')
def prettify_text(nested_list):
string = ''
for li in nested_list:
striped = re.sub(' +', ' ', li[0]).strip()
delimiters = 99 * '='
string += f'{striped}\n{delimiters}\n'
return string.strip()
def remove_most_recent():
global related_chosen
related_chosen = related_chosen[:-1]
if len(related_chosen) == 0:
return ''
return prettify_text(related_chosen)
def clr_btn():
return gr.ClearButton.update(visible=False), gr.Textbox.update(visible=False), gr.Textbox.update(visible=False)
def main():
with gr.Blocks() as demo:
gr.Markdown("""
# DRGCoder
This interface outlines DRGCoder, an explainable clinical coding for the early prediction of diagnostic-related groups (DRGs). Please note all summaries will be truncated to 512 words if longer.
""")
with gr.Row() as row:
input = gr.Textbox(
label="Input Discharge Summary Here", placeholder='sample discharge summary',
text_align='left', interactive=True
)
with gr.Row() as row:
gr.Examples(examples, [input])
with gr.Row() as row:
btn = gr.Button(value="Submit")
with gr.Row() as row:
attn_viz = gr.HTML()
with gr.Row() as row:
with gr.Column() as col:
correct_drg_text = gr.Textbox(visible=False, label="Input Correct DRG", interactive=True)
correct_drg_text.submit(save_results, inputs=correct_drg_text, outputs=correct_drg_text)
with gr.Column() as col:
salient_words_box = gr.Textbox(visible=False, label="Input Salient Words (comma separated)", interactive=True)
salient_words_box.submit(save_results, inputs=salient_words_box, outputs=salient_words_box)
attn_clr_btn = gr.ClearButton(value='Remove DRG Results', visible=False, components=[attn_viz])
attn_clr_btn.click(clr_btn, outputs=[attn_clr_btn, correct_drg_text, salient_words_box])
# related row 1
with gr.Row() as row:
attn_1 = gr.HTML()
related_attn.append(attn_1)
with gr.Row() as row:
with gr.Column() as col:
correct_drg_text_1 = gr.Textbox(visible=False, label="Input Correct DRG", interactive=True)
correct_drg_text_1.submit(save_results, inputs=correct_drg_text_1, outputs=correct_drg_text_1)
correct_drg_text_list.append(correct_drg_text_1)
with gr.Column() as col:
salient_words_box_1 = gr.Textbox(visible=False, label="Input Salient Words (comma separated)", interactive=True)
salient_words_box_1.submit(save_results, inputs=salient_words_box_1, outputs=salient_words_box_1)
correct_salient_words_list.append(salient_words_box_1)
attn_clr_1 = gr.ClearButton(value='Remove DRG Results', visible=False, components=[attn_1])
related_clr_bts.append(attn_clr_1)
attn_clr_1.click(clr_btn, outputs=[attn_clr_1, correct_drg_text_1, salient_words_box_1])
# related row 2
with gr.Row() as row:
attn_2 = gr.HTML()
related_attn.append(attn_2)
with gr.Row() as row:
with gr.Column() as col:
correct_drg_text_2 = gr.Textbox(visible=False, label="Input Correct DRG", interactive=True)
correct_drg_text_2.submit(save_results, inputs=correct_drg_text_2, outputs=correct_drg_text_2)
correct_drg_text_list.append(correct_drg_text_2)
with gr.Column() as col:
salient_words_box_2 = gr.Textbox(visible=False, label="Input Salient Words (comma separated)", interactive=True)
salient_words_box_2.submit(save_results, inputs=salient_words_box_2, outputs=salient_words_box_2)
correct_salient_words_list.append(salient_words_box_2)
attn_clr_2 = gr.ClearButton(value='Remove DRG Results', visible=False, components=[attn_2])
related_clr_bts.append(attn_clr_2)
attn_clr_2.click(clr_btn, outputs=[attn_clr_2, correct_drg_text_2, salient_words_box_2])
# related row 3
with gr.Row() as row:
attn_3 = gr.HTML()
related_attn.append(attn_3)
with gr.Row() as row:
with gr.Column() as col:
correct_drg_text_3 = gr.Textbox(visible=False, label="Input Correct DRG", interactive=True)
correct_drg_text_3.submit(save_results, inputs=correct_drg_text_3, outputs=correct_drg_text_3)
correct_drg_text_list.append(correct_drg_text_3)
with gr.Column() as col:
salient_words_box_3 = gr.Textbox(visible=False, label="Input Salient Words (comma separated)", interactive=True)
salient_words_box_3.submit(save_results, inputs=salient_words_box_3, outputs=salient_words_box_3)
correct_salient_words_list.append(salient_words_box_3)
attn_clr_3 = gr.ClearButton(value='Remove DRG Results', visible=False, components=[attn_3])
related_clr_bts.append(attn_clr_3)
attn_clr_3.click(clr_btn, outputs=[attn_clr_3, correct_drg_text_3, salient_words_box_3])
# input to related summaries
with gr.Row() as row:
input_related = gr.TextArea(label="Input up to 3 Related Discharge Summaries Here", visible=False, text_align='left', min_width=300)
with gr.Row() as row:
rmv_related_btn = gr.Button(value='Remove Related Summary', visible=False)
sbm_btn = gr.Button(value="Submit Related Summaries", components=[input_related], visible=False)
with gr.Row() as row:
related = gr.DataFrame(
value=None, headers=['Similarity Score', 'Related Discharge Summary'], max_rows=5,
datatype=['number', 'str'], col_count=(2, 'fixed'), visible=False
)
# initial run
btn.click(run, inputs=[input], outputs=[
attn_viz, related, attn_clr_btn, input_related,
sbm_btn, rmv_related_btn, correct_drg_text, salient_words_box
])
# find related summaries
# related.click(load_example, inputs=[related], outputs=[input_related])
related.select(load_df_example, inputs=[related], outputs=[input_related])
# remove related summaries
rmv_related_btn.click(remove_most_recent, outputs=[input_related])
# perform attribution on related summaries
sbm_btn.click(run_related, outputs=related_attn + related_clr_bts + correct_drg_text_list + correct_salient_words_list)
demo.launch()
if __name__ == "__main__":
main() |