import numpy as np import gradio as gr import pandas as pd import torch from model import MimicTransformer from utils import load_rule, get_attribution, get_drg_link, get_icd_annotations, visualize_attn from transformers import set_seed set_seed(42) def read_model(model, path): model.load_state_dict(torch.load(path, map_location=torch.device('cpu')), strict=False) return model model_path = 'checkpoint_0_9113.bin' mimic = MimicTransformer(cutoff=512) related_tensor = torch.load('discharge_embeddings.pt') # get model and results mimic = read_model(model=mimic, path=model_path) all_summaries = pd.read_csv('all_summaries.csv')['SUMMARIES'].to_list() tokenizer = mimic.tokenizer mimic.eval() ex1 = """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.""" ex2 = """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.""" ex3 = """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.""" ex4 = """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] related_summaries = [[ex1]] related_chosen = [] related_attn = [] related_clr_bts = [] 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): inputs = tokenizer(text, return_tensors='pt', padding='max_length', max_length=512, truncation=True) 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()] prob = torch.nn.functional.softmax(out).max() return { 'class': drg_code, 'prob': prob, 'attn': attribution, 'tokens': reconstructed_text, 'logits': logits } def find_related_summaries(raw_embedding): raw_embedding = torch.nn.functional.normalize(raw_embedding) scores = torch.mm(related_tensor, raw_embedding.transpose(1,0)) scores_indices = scores.topk(k=5, dim=0) indices, scores = scores_indices[-1], torch.round(100 * scores_indices[0], decimals=2) summaries = [] for summary_idx, score in zip(indices, scores): corresp_summary = all_summaries[summary_idx] summary = f'{round(score.item(),2)}% Similarity Rate for the following Discharge Summary:\n\n{corresp_summary}' summaries.append([summary]) return summaries def run(text, related_discharges=False): model_results = get_model_results(text=text) drg_code = model_results['class'] 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(model_results['logits']) 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.ClearButton.update(visible=True), gr.TextArea.update(visible=True), gr.Button.update(visible=True), gr.Button.update(visible=True) ) def run_related(): global related_chosen attn_list = [] clr_bts = [] 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)) 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)) return attn_list + clr_bts 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 prettify_text(nested_list): idx = 1 string = '' for li in nested_list: delimiters = 99 * '=' string += f'({idx})\n{li[0]}\n{delimiters}\n' idx += 1 return string 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) 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') 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: attn_clr_btn = gr.ClearButton(value='Remove output', visible=False, components=[attn_viz]) attn_clr_btn.click(clr_btn, outputs=[attn_clr_btn]) # related row 1 with gr.Row() as row: with gr.Column() as col: attn = gr.HTML() related_attn.append(attn) attn_clr = gr.ClearButton(value='Remove output', visible=False, components=[attn]) related_clr_bts.append(attn_clr) attn_clr.click(clr_btn, outputs=[attn_clr]) # related row 2 with gr.Row() as row: with gr.Column() as col: attn = gr.HTML() related_attn.append(attn) attn_clr = gr.ClearButton(value='Remove output', visible=False, components=[attn]) related_clr_bts.append(attn_clr) attn_clr.click(clr_btn, outputs=[attn_clr]) # related row 3 with gr.Row() as row: with gr.Column() as col: attn = gr.HTML() related_attn.append(attn) attn_clr = gr.ClearButton(value='Remove output', visible=False, components=[attn]) related_clr_bts.append(attn_clr) attn_clr.click(clr_btn, outputs=[attn_clr]) # input to related summaries with gr.Row() as row: input_related = gr.TextArea(label="Input up to 3 Related Discharge Summary/Summaries Here", visible=False) 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.Dataset(samples=[], components=[input_related], visible=False, type='index') # initial run btn.click(run, inputs=[input], outputs=[attn_viz, related, attn_clr_btn, input_related, sbm_btn, rmv_related_btn]) # find related summaries related.click(load_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) demo.launch() if __name__ == "__main__": main()