File size: 7,244 Bytes
5056702 64e6f71 5056702 |
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 |
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import torch
import numpy as np
from PIL import Image
from collections import OrderedDict
from Transformer_Explainability.modules.layers_ours import *
from Transformer_Explainability.baselines.ViT.ViT_LRP import vit_base_patch16_224 as vit_LRP
from Transformer_Explainability.baselines.ViT.ViT_explanation_generator import LRP
from Transformer_Explainability.XAI import *
from io import BytesIO
from PIL import Image
import streamlit as st
import pandas as pd
from streamlit_option_menu import option_menu
# import Pages as pg
# mean = [0.485, 0.456, 0.406] # our images have three channels
# std = [0.229, 0.224, 0.225]
# normalize = transforms.Normalize(mean=mean, std=std)
# transform = transforms.Compose([
# transforms.Resize((224,224)),
# transforms.ToTensor(),
# normalize,
# ])
# resizing = transforms.Resize((224,224))
CLS2IDX= {0: "Benign",
1: "Ductal carcinoma",
2: "Lobular carcinoma",
3: "Mucinous carcinoma",
4: "Papillary carcinoma"}
st.set_page_config(
page_title="Breast Cancer Diagnosis",
# page_icon="👨⚕️",
layout="wide",
initial_sidebar_state="expanded", #collapsed
)
# "st.session_state :", st.session_state
if "loop" not in st.session_state:
st.session_state["loop"] = 1
def use_model(upl, mag):
num_classes=5
model = vit_LRP(pretrained=True)
num_ftrs = model.head.in_features
model.head = Linear(num_ftrs, num_classes)
state_dict = torch.load("./Model/V" + mag + ".pth", map_location=torch.device('cpu'))
model.load_state_dict(state_dict)
model.eval()
ag = LRP(model)
model_pred=[]
with st.container():
st.subheader("Result")
for file in upl:
bytes_data = file.read()
img = Image.open(BytesIO(bytes_data))
inputs = tf(img)
outputs = model(inputs.unsqueeze(0))
prob = torch.softmax(outputs, dim=1)
class_indices = outputs.data.topk(5, dim=1)[1][0].tolist()
model_prop = []
for cls_idx in class_indices:
model_prop.append([CLS2IDX[cls_idx], "{:.2f}".format(prob[0, cls_idx]*100)])
img_col1, img_col2, txt_col = st.columns((1, 1, 2))
with img_col1:
st.image(
transforms.Resize((224,224))(img),
output_format="auto",
caption="original image"
)
with img_col2:
st.image(
generate_visualization(inputs, ag),
caption="explainability"
)
with txt_col:
df = pd.DataFrame(
model_prop,
columns=["Class", "Probability"]
)
st.dataframe(
df,
width=600
)
rslt = CLS2IDX[class_indices[0]]
if rslt == "Benign":
tp = "-"
else:
tp = rslt
rslt = "Malignant"
model_pred.append([file.name, rslt, tp])
with st.container():
st.subheader("Conclusion")
df2 = pd.DataFrame(
model_pred, columns=["Name", "Result", "Type"]
)
with st.container():
st.dataframe(
df2,
width=800
)
# --Header--
with st.container():
st.title("Breast cancer diagnosis by transformer model")
st.subheader("Hi :wave:")
st.write("This website will help you to diagnose breast cancer images that collected by surgical open biopsy method(SOB)")
st.write("The data that you will input must same to BREAKHIS dataset [Learn more >](https://docs.google.com/document/d/12NYTJkh2yKdR75XQhD3OwQoYFFwqIK7mkSVbd0-VWok/edit?usp=drivesdk)")
# --Sidebar--
with st.sidebar:
# --Inputs--
with st.container():
st.subheader("Inputs")
maglist = ["--Select--", "40X", "100X", "200X", "400X"]
magnification = st.sidebar.selectbox("Select the Magnification", maglist)
with st.container():
uploaded = st.file_uploader(
"Choose images to diagnose", type=["jpg", "jpeg", "png"], accept_multiple_files = True
)
# with st.container():
# diagnose = st.button("Diagnose")
with st.container():
if uploaded != [] and magnification != "--Select--":
use_model(uploaded, magnification)
st.session_state["loop"]+=1
# "st.session_state obj :", st.session_state
# pass
# selected = option_menu(
# menu_title=None, # required
# options=["Home", "How to use", "Contact"]
# )
# if selected == "Home":
# inputs()
# elif selected == "How to use":
# pg.howtouse()
# elif selected == "Contact":
# pg.contact()
# st.set_page_config(
# page_title="Breast Cancer Diagnosis",
# page_icon="👨⚕️",
# layout="wide",
# initial_sidebar_state="expanded", #collapsed
# )
# st.title("Breast Cancer Diagnosis BY Transformer Model")
# st.sidebar.subheader("Input")
# "st.session_state obj :", st.session_state
# if 'boolean' not in st.session_state:
# st.session_state['boolean'] = False
# "st.session_state obj :", st.session_state
# models_list = ["--Select--", "40X", "100X", "200X", "400X"]
# magnitude = st.sidebar.selectbox("Select the Magnification", models_list)
# uploaded_file = st.sidebar.file_uploader(
# "Choose images to diagnose", type=["jpg", "jpeg", "png"], accept_multiple_files = True
# )
# diagnosis = st.sidebar.button("Diagnose")
# if diagnosis:
# st.session_state['boolean'] = True
# num_classes = 5
# model = vit_LRP(pretrained=True)
# num_ftrs = model.head.in_features
# model.head = Linear(num_ftrs, num_classes)
# if uploaded_file != [] and st.session_state['boolean'] and magnitude != "--Select--":
# state_dict = torch.load("./Model/V" + magnitude + ".pth", map_location=torch.device('cpu'))
# model.load_state_dict(state_dict)
# model.eval()
# ag = LRP(model)
# predictions = []
# xai = []
# for each_file in uploaded_file:
# bytes_data = each_file.read()
# img = Image.open(BytesIO(bytes_data))
# inputs = transform(img)
# outputs = model(inputs.unsqueeze(0))
# model_predicted = CLS2IDX[print_top_classes(outputs)[0]]
# if model_predicted == "benign":
# type = '-'
# else:
# type = model_predicted
# model_predicted = "malignant"
# xai.append(generate_visualization(inputs, ag))
# predictions.append([img, each_file.name, model_predicted, type])
# #st.write(each_file)
# #st.write(each_file.name)
# # st.image(img)
# #st.write(model_predicted)
# def showim():
# df = pd.DataFrame(
# predictions, columns=["Image", "Name", "Result", "Type"]
# )
# st.dataframe(
# df.iloc[:,1:], width=1000
# )
# idx = st.select_slider("Select the index of picture", df.index, on_change=showim)
# st.write(idx)
# # st.image(predictions[index][0])
# st.image(xai[idx])
# showim()
# print(uploaded_file, diagnosis, magnitude) |