File size: 9,427 Bytes
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
import numpy as np
import gradio as gr
import pandas as pd
import torch
import random

from model import MimicTransformer
from utils import load_rule, get_attribution, get_drg_link, 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'][:10000].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)
    row = rule_df[rule_df['DRG_CODE'] == drg_code]
    drg_description = row['DESCRIPTION'].values[0]
    model_results['class_dsc'] = drg_description
    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 generate_similar_summeries():
    if random.random() > 0.5:
        return [[ex1], [ex3]]
    else:
        return [[ex2], [ex4]]

def remove_info(c1, c2):
    return gr.ClearButton.update(visible=False)

def prettify_text(nested_list):
    idx = 1
    string = ''
    for li in nested_list:
        string += f'({idx})\n{li[0]}\n\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:
            with gr.Column(scale=2) as col:
                input = gr.Textbox(label="Input Discharge Summary Here", placeholder='sample discharge summary')
                btn = gr.Button(value="Submit")
            with gr.Column(scale=3) as col:
                gr.Examples(examples, [input])
        with gr.Row() as row:
            with gr.Column() as col:
                attn_viz = gr.HTML() 
                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:
            with gr.Column(scale=4) as col:
                input_related = gr.TextArea(label="Input up to 3 Related Discharge Summary/Summaries Here", visible=False)
                rmv_related_btn = gr.Button(value='Remove Related Summary', visible=False)
            with gr.Column(scale=4) as col:
                related = gr.Dataset(samples=[], components=[input_related], visible=False, type='index')
                sbm_btn = gr.Button(value="Submit Related Summaries", components=[input_related], visible=False)                              

        # 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()