File size: 10,302 Bytes
f73dc21
 
 
 
 
 
4067c90
 
f73dc21
4067c90
bc31c45
4067c90
 
 
 
 
f73dc21
 
 
 
 
 
 
 
 
 
4067c90
 
 
 
 
 
 
 
 
 
 
f73dc21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4067c90
 
 
 
 
 
 
 
bc31c45
f73dc21
 
bc31c45
f73dc21
bc31c45
 
 
f73dc21
bc31c45
 
 
f73dc21
bc31c45
f73dc21
 
 
 
 
4067c90
f73dc21
 
4067c90
 
 
 
f73dc21
6a4a8e0
f73dc21
 
 
6a4a8e0
 
f73dc21
 
4067c90
f73dc21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a4a8e0
 
f73dc21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3e501a
f73dc21
b3e501a
 
 
 
 
 
 
 
f73dc21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc31c45
 
 
 
b3e501a
 
 
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
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_diseases, get_drg_link, get_icd_annotations, visualize_attn
from transformers import AutoTokenizer, AutoModel, set_seed, pipeline
set_seed(42)
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')), 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")

# 

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 = []

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(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)
    summaries = []
    score_set = set()
    for summary_idx, score in zip(indices, scores):
        score = score.item()
        if len(summaries) == 5:
            break
        corresp_summary = all_summaries[summary_idx]
        if score in score_set:
            continue
        summary = f'{round(score,2)}% Similarity Rate for the following Discharge Summary:\n\n{corresp_summary}'
        summaries.append([summary])
        score_set.add(score)
    return summaries



def run(text, related_discharges=False):
    # 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.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()