File size: 9,198 Bytes
a297be3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70be421
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90f10bf
a297be3
 
90f10bf
 
 
 
 
 
 
 
a297be3
 
70be421
 
 
 
 
 
 
 
 
 
 
a297be3
90f10bf
 
 
 
 
 
 
 
 
 
70be421
90f10bf
 
 
 
 
 
 
 
70be421
90f10bf
 
 
 
 
 
 
 
70be421
90f10bf
 
 
 
70be421
 
a297be3
 
70be421
 
 
 
 
 
a297be3
70be421
a297be3
90f10bf
 
70be421
90f10bf
 
 
 
 
 
 
 
 
70be421
 
 
90f10bf
 
a297be3
70be421
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
# import streamlit as st
# import torch
# from transformers import LongformerTokenizer, LongformerForSequenceClassification

# # Load the fine-tuned model and tokenizer
# model_path = "./clinical_longformer"
# tokenizer = LongformerTokenizer.from_pretrained(model_path)
# model = LongformerForSequenceClassification.from_pretrained(model_path)
# model.eval()  # Set the model to evaluation mode

# # ICD-9 code columns used during training
# icd9_columns = [
#     '038.9', '244.9', '250.00', '272.0', '272.4', '276.1', '276.2', '285.1', '285.9',
#     '287.5', '305.1', '311', '36.15', '37.22', '37.23', '38.91', '38.93', '39.61',
#     '39.95', '401.9', '403.90', '410.71', '412', '414.01', '424.0', '427.31', '428.0',
#     '486', '496', '507.0', '511.9', '518.81', '530.81', '584.9', '585.9', '599.0',
#     '88.56', '88.72', '93.90', '96.04', '96.6', '96.71', '96.72', '99.04', '99.15',
#     '995.92', 'V15.82', 'V45.81', 'V45.82', 'V58.61'
# ]

# # Function for making predictions
# def predict_icd9(texts, tokenizer, model, threshold=0.5):
#     inputs = tokenizer(
#         texts,
#         padding="max_length",
#         truncation=True,
#         max_length=512,
#         return_tensors="pt"
#     )
    
#     with torch.no_grad():
#         outputs = model(
#             input_ids=inputs["input_ids"],
#             attention_mask=inputs["attention_mask"]
#         )
#         logits = outputs.logits
#         probabilities = torch.sigmoid(logits)
#         predictions = (probabilities > threshold).int()
    
#     predicted_icd9 = []
#     for pred in predictions:
#         codes = [icd9_columns[i] for i, val in enumerate(pred) if val == 1]
#         predicted_icd9.append(codes)
    
#     return predicted_icd9

# # Streamlit UI
# st.title("ICD-9 Code Prediction")
# st.sidebar.header("Model Options")
# model_option = st.sidebar.selectbox("Select Model", [ "ClinicalLongformer"])
# threshold = st.sidebar.slider("Prediction Threshold", 0.0, 1.0, 0.5, 0.01)

# st.write("### Enter Medical Summary")
# input_text = st.text_area("Medical Summary", placeholder="Enter clinical notes here...")

# if st.button("Predict"):
#     if input_text.strip():
#         predictions = predict_icd9([input_text], tokenizer, model, threshold)
#         st.write("### Predicted ICD-9 Codes")
#         for code in predictions[0]:
#             st.write(f"- {code}")
#     else:
#         st.error("Please enter a medical summary.")

# import torch
# import pandas as pd
# import streamlit as st
# from transformers import LongformerTokenizer, LongformerForSequenceClassification

# # Load the fine-tuned model and tokenizer
# model_path = "./clinical_longformer"
# tokenizer = LongformerTokenizer.from_pretrained(model_path)
# model = LongformerForSequenceClassification.from_pretrained(model_path)
# model.eval()  # Set the model to evaluation mode

# # Load the ICD-9 descriptions from CSV into a dictionary
# icd9_desc_df = pd.read_csv("D_ICD_DIAGNOSES.csv")  # Adjust the path to your CSV file
# icd9_desc_df['ICD9_CODE'] = icd9_desc_df['ICD9_CODE'].astype(str)  # Ensure ICD9_CODE is string type for matching
# icd9_descriptions = dict(zip(icd9_desc_df['ICD9_CODE'].str.replace('.', ''), icd9_desc_df['LONG_TITLE']))  # Remove decimals in ICD9 code for matching

# # ICD-9 code columns used during training
# icd9_columns = [
#     '038.9', '244.9', '250.00', '272.0', '272.4', '276.1', '276.2', '285.1', '285.9',
#     '287.5', '305.1', '311', '36.15', '37.22', '37.23', '38.91', '38.93', '39.61',
#     '39.95', '401.9', '403.90', '410.71', '412', '414.01', '424.0', '427.31', '428.0',
#     '486', '496', '507.0', '511.9', '518.81', '530.81', '584.9', '585.9', '599.0',
#     '88.56', '88.72', '93.90', '96.04', '96.6', '96.71', '96.72', '99.04', '99.15',
#     '995.92', 'V15.82', 'V45.81', 'V45.82', 'V58.61'
# ]

# # Function for making predictions
# def predict_icd9(texts, tokenizer, model, threshold=0.5):
#     inputs = tokenizer(
#         texts,
#         padding="max_length",
#         truncation=True,
#         max_length=512,
#         return_tensors="pt"
#     )
    
#     with torch.no_grad():
#         outputs = model(
#             input_ids=inputs["input_ids"],
#             attention_mask=inputs["attention_mask"]
#         )
#         logits = outputs.logits
#         probabilities = torch.sigmoid(logits)
#         predictions = (probabilities > threshold).int()
    
#     predicted_icd9 = []
#     for pred in predictions:
#         codes = [icd9_columns[i] for i, val in enumerate(pred) if val == 1]
#         predicted_icd9.append(codes)
    
#     # Fetch descriptions for the predicted ICD-9 codes from the pre-loaded descriptions
#     predictions_with_desc = []
#     for codes in predicted_icd9:
#         code_with_desc = [(code, icd9_descriptions.get(code.replace('.', ''), "Description not found")) for code in codes]
#         predictions_with_desc.append(code_with_desc)
    
#     return predictions_with_desc

# # Streamlit UI
# st.title("ICD-9 Code Prediction")
# st.sidebar.header("Model Options")
# threshold = st.sidebar.slider("Prediction Threshold", 0.0, 1.0, 0.5, 0.01)

# st.write("### Enter Medical Summary")
# input_text = st.text_area("Medical Summary", placeholder="Enter clinical notes here...")

# if st.button("Predict"):
#     if input_text.strip():
#         predictions = predict_icd9([input_text], tokenizer, model, threshold)
#         st.write("### Predicted ICD-9 Codes and Descriptions")
#         for code, description in predictions[0]:
#             st.write(f"- {code}: {description}")
#     else:
#         st.error("Please enter a medical summary.")
import torch
import pandas as pd
import streamlit as st
from transformers import LongformerTokenizer, LongformerForSequenceClassification

# Load the fine-tuned model and tokenizer
model_path = "./clinical_longformer"
tokenizer = LongformerTokenizer.from_pretrained(model_path)
model = LongformerForSequenceClassification.from_pretrained(model_path)
model.eval()  # Set the model to evaluation mode

# Load the ICD-9 descriptions from CSV into a dictionary
icd9_desc_df = pd.read_csv("D_ICD_DIAGNOSES.csv")  # Adjust the path to your CSV file
icd9_desc_df['ICD9_CODE'] = icd9_desc_df['ICD9_CODE'].astype(str)  # Ensure ICD9_CODE is string type
icd9_descriptions = dict(zip(icd9_desc_df['ICD9_CODE'].str.replace('.', ''), icd9_desc_df['LONG_TITLE']))  # Remove decimals for matching

# Load the ICD-9 to ICD-10 mapping
icd9_to_icd10 = {}
with open("2015_I9gem.txt", "r") as file:
    for line in file:
        parts = line.strip().split()
        if len(parts) == 3:
            icd9, icd10, _ = parts
            icd9_to_icd10[icd9] = icd10

# ICD-9 code columns used during training
icd9_columns = [
    '038.9', '244.9', '250.00', '272.0', '272.4', '276.1', '276.2', '285.1', '285.9',
    '287.5', '305.1', '311', '36.15', '37.22', '37.23', '38.91', '38.93', '39.61',
    '39.95', '401.9', '403.90', '410.71', '412', '414.01', '424.0', '427.31', '428.0',
    '486', '496', '507.0', '511.9', '518.81', '530.81', '584.9', '585.9', '599.0',
    '88.56', '88.72', '93.90', '96.04', '96.6', '96.71', '96.72', '99.04', '99.15',
    '995.92', 'V15.82', 'V45.81', 'V45.82', 'V58.61'
]

# Function for making predictions and mapping to ICD-10
def predict_icd9(texts, tokenizer, model, threshold=0.5):
    inputs = tokenizer(
        texts,
        padding="max_length",
        truncation=True,
        max_length=512,
        return_tensors="pt"
    )

    with torch.no_grad():
        outputs = model(
            input_ids=inputs["input_ids"],
            attention_mask=inputs["attention_mask"]
        )
        logits = outputs.logits
        probabilities = torch.sigmoid(logits)
        predictions = (probabilities > threshold).int()

    predicted_icd9 = []
    for pred in predictions:
        codes = [icd9_columns[i] for i, val in enumerate(pred) if val == 1]
        predicted_icd9.append(codes)

    # Fetch descriptions and map to ICD-10 codes
    predictions_with_desc = []
    for codes in predicted_icd9:
        code_with_desc = []
        for code in codes:
            icd9_stripped = code.replace('.', '')
            icd10_code = icd9_to_icd10.get(icd9_stripped, "Mapping not found")
            icd9_desc = icd9_descriptions.get(icd9_stripped, "Description not found")
            code_with_desc.append((code, icd9_desc, icd10_code))
        predictions_with_desc.append(code_with_desc)

    return predictions_with_desc

# Streamlit UI
st.title("ICD-9 to ICD-10 Code Prediction")
st.sidebar.header("Model Options")
threshold = st.sidebar.slider("Prediction Threshold", 0.0, 1.0, 0.5, 0.01)

st.write("### Enter Medical Summary")
input_text = st.text_area("Medical Summary", placeholder="Enter clinical notes here...")

if st.button("Predict"):
    if input_text.strip():
        predictions = predict_icd9([input_text], tokenizer, model, threshold)
        st.write("### Predicted ICD-9 and ICD-10 Codes with Descriptions")
        for icd9_code, description, icd10_code in predictions[0]:
            st.write(f"- ICD-9: {icd9_code} ({description}) -> ICD-10: {icd10_code}")
    else:
        st.error("Please enter a medical summary.")