Spaces:
Build error
Build error
Commit ·
2046f76
1
Parent(s): 1b8a13f
Update app.py
Browse files104 unmodified lines1051061071081091101113 unmodified lines1151161171181191201212 unmodified lines1241251261271281291307 unmodified lines13813914014114214314414514614714814915015115231 unmodified lines184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323104 unmodified lines# Evaluation Transformseval_transforms = Compose([LoadImage(image_only=True),AsChannelFirst(),ScaleIntensityRangePercentiles(lower=20, upper=80, b_min=0.0, b_max=1.0, clip=False, relative=True),Resize(spatial_size=SPATIAL_SIZE)3 unmodified lines# CAM Transformscam_transforms = Compose([LoadImage(image_only=True),AsChannelFirst(),Resize(spatial_size=SPATIAL_SIZE)]2 unmodified lines# Original Transformsoriginal_transforms = Compose([LoadImage(image_only=True),AsChannelFirst()])7 unmodified lines# if os.path.exists("tempDir"):# shutil.rmtree(os.path.join("tempDir"))def create_dir(dirname: str):if not os.path.exists(dirname):os.makedirs(dirname, exist_ok=True)create_dir("CT_tempDir")create_dir("MRI_tempDir")# Get the current working directorycurrent_directory = os.getcwd()set_determinism(seed=SEED)torch.manual_seed(SEED)31 unmodified linesuploaded_mri_file = st.file_uploader("Upload a candidate MRI DICOM", type=["dcm"])if uploaded_mri_file is not None:# Save the uploaded file to a temporary locationmri_temp_path = os.path.join("MRI_tempDir", uploaded_mri_file.name)with open(mri_temp_path, "wb") as f:f.write(uploaded_mri_file.getbuffer())full_mri_temp_path = current_directory +"\\"+ mri_temp_path# Apply evaluation transforms to the DICOM image for model predictionimage_tensor = eval_transforms(full_mri_temp_path).unsqueeze(0).to(device)# Predictwith torch.no_grad():outputs = mri_model(image_tensor).sigmoid().to("cpu").numpy()prob = outputs[0][0]CLOTS_CLASSIFICATION = Falseif(prob >= MRI_INFERENCE_THRESHOLD):CLOTS_CLASSIFICATION=Truest.header("MRI Classification")st.subheader(f"Ischaemic Stroke : {CLOTS_CLASSIFICATION}")st.subheader(f"Confidence : {prob * 100:.1f}%")# Load the original DICOM image for downloaddownload_image_tensor = original_transforms(full_mri_temp_path).unsqueeze(0).to(device)download_image = download_image_tensor.squeeze()# Transform the download image and apply windowingtransformed_download_image = DICOM_Utils.transform_image_for_display(download_image)windowed_download_image = DICOM_Utils.apply_windowing(transformed_download_image, MRI_WINDOW_CENTER, MRI_WINDOW_WIDTH)# Streamlit button to trigger image downloadimage_data = image_to_bytes(Image.fromarray(windowed_download_image))st.download_button(label="Download MRI Image",data=image_data,file_name="downloaded_mri_image.png",mime="image/png")# Load the original DICOM image for displaydisplay_image_tensor = cam_transforms(full_mri_temp_path).unsqueeze(0).to(device)display_image = display_image_tensor.squeeze()# Transform the image and apply windowingtransformed_image = DICOM_Utils.transform_image_for_display(display_image)windowed_image = DICOM_Utils.apply_windowing(transformed_image, MRI_WINDOW_CENTER, MRI_WINDOW_WIDTH)st.image(Image.fromarray(windowed_image), caption="Original MRI Visualization", use_column_width=True)# Expand to three channelswindowed_image = np.expand_dims(windowed_image, axis=2)windowed_image = np.tile(windowed_image, [1, 1, 3])# Ensure both are of float32 typewindowed_image = windowed_image.astype(np.float32)# Normalize to [0, 1] rangewindowed_image = np.float32(windowed_image) / 255# Build the CAM (Class Activation Map)target_layers = [mri_model.model.norm]cam = GradCAM(model=mri_model, target_layers=target_layers, reshape_transform=reshape_transform, use_cuda=True)grayscale_cam = cam(input_tensor=image_tensor, targets=[ClassifierOutputTarget(CAM_CLASS_ID)])grayscale_cam = grayscale_cam[0, :]# Now you can safely call the show_cam_on_image functionvisualization = show_cam_on_image(windowed_image, grayscale_cam, use_rgb=True)st.image(Image.fromarray(visualization), caption="CAM MRI Visualization", use_column_width=True)uploaded_ct_file = st.file_uploader("Upload a candidate CT DICOM", type=["dcm"])if uploaded_ct_file is not None:# Save the uploaded file to a temporary locationct_temp_path = os.path.join("CT_tempDir", uploaded_ct_file.name)with open(ct_temp_path, "wb") as f:f.write(uploaded_ct_file.getbuffer())full_ct_temp_path = current_directory +"\\"+ ct_temp_path# Apply evaluation transforms to the DICOM image for model predictionimage_tensor = eval_transforms(full_ct_temp_path).unsqueeze(0).to(device)# Predictwith torch.no_grad():outputs = ct_model(image_tensor).sigmoid().to("cpu").numpy()prob = outputs[0][0]CLOTS_CLASSIFICATION = Falseif(prob >= CT_INFERENCE_THRESHOLD):CLOTS_CLASSIFICATION=Truest.header("CT Classification")st.subheader(f"Ischaemic Stroke : {CLOTS_CLASSIFICATION}")st.subheader(f"Confidence : {prob * 100:.1f}%")# Load the original DICOM image for downloaddownload_image_tensor = original_transforms(full_ct_temp_path).unsqueeze(0).to(device)download_image = download_image_tensor.squeeze()# Transform the download image and apply windowingtransformed_download_image = DICOM_Utils.transform_image_for_display(download_image)windowed_download_image = DICOM_Utils.apply_windowing(transformed_download_image, CT_WINDOW_CENTER, CT_WINDOW_WIDTH)# Streamlit button to trigger image downloadimage_data = image_to_bytes(Image.fromarray(windowed_download_image))st.download_button(label="Download CT Image",data=image_data,file_name="downloaded_ct_image.png",mime="image/png")# Load the original DICOM image for displaydisplay_image_tensor = cam_transforms(full_ct_temp_path).unsqueeze(0).to(device)display_image = display_image_tensor.squeeze()# Transform the image and apply windowingtransformed_image = DICOM_Utils.transform_image_for_display(display_image)windowed_image = DICOM_Utils.apply_windowing(transformed_image, CT_WINDOW_CENTER, CT_WINDOW_WIDTH)st.image(Image.fromarray(windowed_image), caption="Original CT Visualization", use_column_width=True)# Expand to three channelswindowed_image = np.expand_dims(windowed_image, axis=2)windowed_image = np.tile(windowed_image, [1, 1, 3])# Ensure both are of float32 typewindowed_image = windowed_image.astype(np.float32)# Normalize to [0, 1] rangewindowed_image = np.float32(windowed_image) / 255# Build the CAM (Class Activation Map)target_layers = [ct_model.model.norm]cam = GradCAM(model=ct_model, target_layers=target_layers, reshape_transform=reshape_transform, use_cuda=True)grayscale_cam = cam(input_tensor=image_tensor, targets=[ClassifierOutputTarget(CAM_CLASS_ID)])grayscale_cam = grayscale_cam[0, :]# Now you can safely call the show_cam_on_image functionvisualization = show_cam_on_image(windowed_image, grayscale_cam, use_rgb=True)st.image(Image.fromarray(visualization), caption="CAM CT Visualization", use_column_width=True)104 unmodified lines1051061071081091101113 unmodified lines1151161171181191201212 unmodified lines1241251261271281291307 unmodified lines13813914014114214314414514614714814915015115231 unmodified lines184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338104 unmodified lines# Evaluation Transformseval_transforms = Compose([# LoadImage(image_only=True),AsChannelFirst(),ScaleIntensityRangePercentiles(lower=20, upper=80, b_min=0.0, b_max=1.0, clip=False, relative=True),Resize(spatial_size=SPATIAL_SIZE)3 unmodified lines# CAM Transformscam_transforms = Compose([# LoadImage(image_only=True),AsChannelFirst(),Resize(spatial_size=SPATIAL_SIZE)]2 unmodified lines# Original Transformsoriginal_transforms = Compose([# LoadImage(image_only=True),AsChannelFirst()])7 unmodified lines# if os.path.exists("tempDir"):# shutil.rmtree(os.path.join("tempDir"))# def create_dir(dirname: str):# if not os.path.exists(dirname):# os.makedirs(dirname, exist_ok=True)# create_dir("CT_tempDir")# create_dir("MRI_tempDir")# # Get the current working directory# current_directory = os.getcwd()set_determinism(seed=SEED)torch.manual_seed(SEED)31 unmodified linesuploaded_mri_file = st.file_uploader("Upload a candidate MRI DICOM", type=["dcm"])if uploaded_mri_file is not None:# To check file detailsfile_details = {"FileName": uploaded_mri_file.name, "FileType": uploaded_mri_file.type, "FileSize": uploaded_mri_file.size}st.write(file_details)import pydicom# Read DICOM file into NumPy arraydicom_data = pydicom.dcmread(uploaded_mri_file)dicom_array = dicom_data.pixel_array# Convert the data type to float32dicom_array = dicom_array.astype(np.float32)# Then add a channel dimensiondicom_array = dicom_array[:, :, np.newaxis]# Check the shape and dtype of dicom_arrayst.write(f"Shape of dicom_array: {dicom_array.shape}")st.write(f"Data type of dicom_array: {dicom_array.dtype}")transformed_array = eval_transforms(dicom_array)# Convert to PyTorch tensor and move to devicedevice = torch.device("cuda" if torch.cuda.is_available() else "cpu")image_tensor = transformed_array.clone().detach().unsqueeze(0).to(device)# Predictwith torch.no_grad():outputs = mri_model(image_tensor).sigmoid().to("cpu").numpy()prob = outputs[0][0]CLOTS_CLASSIFICATION = Falseif(prob >= MRI_INFERENCE_THRESHOLD):CLOTS_CLASSIFICATION=Truest.header("MRI Classification")st.subheader(f"Ischaemic Stroke : {CLOTS_CLASSIFICATION}")st.subheader(f"Confidence : {prob * 100:.1f}%")# Load the original DICOM image for downloaddownload_image_tensor = original_transforms(dicom_array).unsqueeze(0).to(device)download_image = download_image_tensor.squeeze()# Transform the download image and apply windowingtransformed_download_image = DICOM_Utils.transform_image_for_display(download_image)windowed_download_image = DICOM_Utils.apply_windowing(transformed_download_image, MRI_WINDOW_CENTER, MRI_WINDOW_WIDTH)# Streamlit button to trigger image downloadimage_data = image_to_bytes(Image.fromarray(windowed_download_image))st.download_button(label="Download MRI Image",data=image_data,file_name="downloaded_mri_image.png",mime="image/png")# Load the original DICOM image for displaydisplay_image_tensor = cam_transforms(dicom_array).unsqueeze(0).to(device)display_image = display_image_tensor.squeeze()# Transform the image and apply windowingtransformed_image = DICOM_Utils.transform_image_for_display(display_image)windowed_image = DICOM_Utils.apply_windowing(transformed_image, MRI_WINDOW_CENTER, MRI_WINDOW_WIDTH)st.image(Image.fromarray(windowed_image), caption="Original MRI Visualization", use_column_width=True)# Expand to three channelswindowed_image = np.expand_dims(windowed_image, axis=2)windowed_image = np.tile(windowed_image, [1, 1, 3])# Ensure both are of float32 typewindowed_image = windowed_image.astype(np.float32)# Normalize to [0, 1] rangewindowed_image = np.float32(windowed_image) / 255# Build the CAM (Class Activation Map)target_layers = [mri_model.model.norm]cam = GradCAM(model=mri_model, target_layers=target_layers, reshape_transform=reshape_transform, use_cuda=True)grayscale_cam = cam(input_tensor=image_tensor, targets=[ClassifierOutputTarget(CAM_CLASS_ID)])grayscale_cam = grayscale_cam[0, :]# Now you can safely call the show_cam_on_image functionvisualization = show_cam_on_image(windowed_image, grayscale_cam, use_rgb=True)st.image(Image.fromarray(visualization), caption="CAM MRI Visualization", use_column_width=True)# uploaded_ct_file = st.file_uploader("Upload a candidate CT DICOM", type=["dcm"])# if uploaded_ct_file is not None:# # Save the uploaded file to a temporary location# ct_temp_path = os.path.join("CT_tempDir", uploaded_ct_file.name)# with open(ct_temp_path, "wb") as f:# f.write(uploaded_ct_file.getbuffer())# full_ct_temp_path = current_directory +"\\"+ ct_temp_path# # Apply evaluation transforms to the DICOM image for model prediction# image_tensor = eval_transforms(full_ct_temp_path).unsqueeze(0).to(device)# # Predict# with torch.no_grad():# outputs = ct_model(image_tensor).sigmoid().to("cpu").numpy()# prob = outputs[0][0]# CLOTS_CLASSIFICATION = False# if(prob >= CT_INFERENCE_THRESHOLD):# CLOTS_CLASSIFICATION=True# st.header("CT Classification")# st.subheader(f"Ischaemic Stroke : {CLOTS_CLASSIFICATION}")# st.subheader(f"Confidence : {prob * 100:.1f}%")# # Load the original DICOM image for download# download_image_tensor = original_transforms(full_ct_temp_path).unsqueeze(0).to(device)# download_image = download_image_tensor.squeeze()# # Transform the download image and apply windowing# transformed_download_image = DICOM_Utils.transform_image_for_display(download_image)# windowed_download_image = DICOM_Utils.apply_windowing(transformed_download_image, CT_WINDOW_CENTER, CT_WINDOW_WIDTH)# # Streamlit button to trigger image download# image_data = image_to_bytes(Image.fromarray(windowed_download_image))# st.download_button(# label="Download CT Image",# data=image_data,# file_name="downloaded_ct_image.png",# mime="image/png"# )# # Load the original DICOM image for display# display_image_tensor = cam_transforms(full_ct_temp_path).unsqueeze(0).to(device)# display_image = display_image_tensor.squeeze()# # Transform the image and apply windowing# transformed_image = DICOM_Utils.transform_image_for_display(display_image)# windowed_image = DICOM_Utils.apply_windowing(transformed_image, CT_WINDOW_CENTER, CT_WINDOW_WIDTH)# st.image(Image.fromarray(windowed_image), caption="Original CT Visualization", use_column_width=True)# # Expand to three channels# windowed_image = np.expand_dims(windowed_image, axis=2)# windowed_image = np.tile(windowed_image, [1, 1, 3])# # Ensure both are of float32 type# windowed_image = windowed_image.astype(np.float32)# # Normalize to [0, 1] range# windowed_image = np.float32(windowed_image) / 255# # Build the CAM (Class Activation Map)# target_layers = [ct_model.model.norm]# cam = GradCAM(model=ct_model, target_layers=target_layers, reshape_transform=reshape_transform, use_cuda=True)# grayscale_cam = cam(input_tensor=image_tensor, targets=[ClassifierOutputTarget(CAM_CLASS_ID)])# grayscale_cam = grayscale_cam[0, :]# # Now you can safely call the show_cam_on_image function# visualization = show_cam_on_image(windowed_image, grayscale_cam, use_rgb=True)# st.image(Image.fromarray(visualization), caption="CAM CT Visualization", use_column_width=True)
app.py+162-147