Spaces:
Runtime error
Runtime error
File size: 5,075 Bytes
2d10123 |
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 |
import os
import traceback
import numpy as np
import streamlit as st
from PIL import Image
from transformers import pipeline
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skimage.filters import threshold_otsu
# =======================
# Configuration and Setup
# =======================
# Streamlit Page Configuration
st.set_page_config(
page_title="AI Cancer Detection Platform",
page_icon="๐ฉบ",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
"About": "### AI Cancer Detection Platform\n"
"Developed to classify cancer images and provide research insights."
}
)
# =======================
# Helper Functions
# =======================
@st.cache_resource
def load_pipeline():
"""
Load the pre-trained image classification pipeline using PyTorch as the backend.
"""
try:
model_pipeline = pipeline(
"image-classification",
model="Anwarkh1/Skin_Cancer-Image_Classification",
framework="pt" # Force PyTorch backend
)
return model_pipeline
except Exception as e:
st.error(f"Error loading model: {e}")
traceback.print_exc()
st.stop()
def process_image(image):
"""
Perform image processing to extract features for better visualization.
"""
try:
# Convert image to grayscale
gray_image = rgb2gray(np.array(image))
# Apply Otsu's threshold
thresh = threshold_otsu(gray_image)
binary = gray_image > thresh
# Calculate edge pixel percentage
edge_pixels = np.sum(binary)
total_pixels = binary.size
edge_percentage = (edge_pixels / total_pixels) * 100
# Generate plots
fig, ax = plt.subplots(1, 2, figsize=(10, 5))
ax[0].imshow(gray_image, cmap="gray")
ax[0].set_title("Grayscale Image")
ax[0].axis("off")
ax[1].imshow(binary, cmap="gray")
ax[1].set_title("Binary Image (Thresholded)")
ax[1].axis("off")
plt.tight_layout()
st.pyplot(fig)
# Feature description
return f"{edge_percentage:.2f}% of the image contains edge pixels after thresholding."
except Exception as e:
st.error(f"Error processing image: {e}")
traceback.print_exc()
return "No significant features extracted."
def classify_image(image, model_pipeline):
"""
Classify the uploaded image using the pre-trained model pipeline.
"""
try:
# Resize image to 224x224 as required by the model
image_resized = image.resize((224, 224))
predictions = model_pipeline(image_resized)
if predictions:
top_prediction = predictions[0]
label = top_prediction["label"]
score = top_prediction["score"]
return label, score
else:
st.warning("No predictions were made.")
return None, None
except Exception as e:
st.error(f"Error during classification: {e}")
traceback.print_exc()
return None, None
# =======================
# Streamlit Main Content
# =======================
st.title("๐ฉบ AI-Powered Cancer Detection")
# Image Upload Section
st.subheader("๐ค Upload a Cancer Image")
uploaded_image = st.file_uploader("Choose an image file...", type=["png", "jpg", "jpeg"])
if uploaded_image is not None:
try:
# Open the uploaded image
image = Image.open(uploaded_image).convert("RGB")
# Display the uploaded image
st.image(image, caption="Uploaded Image", use_column_width=True)
# Process the image
st.markdown("### ๐ ๏ธ Image Processing")
processed_features = process_image(image)
# Load the model pipeline
st.markdown("### ๐ Classifying the Image")
model_pipeline = load_pipeline()
# Classify the image
with st.spinner("Classifying..."):
label, confidence = classify_image(image, model_pipeline)
if label and confidence:
st.write(f"**Prediction:** {label}")
st.write(f"**Confidence:** {confidence:.2%}")
# Highlight prediction confidence
if confidence > 0.80:
st.success("High confidence in the prediction.")
elif confidence > 0.50:
st.warning("Moderate confidence in the prediction.")
else:
st.error("Low confidence in the prediction.")
except Exception as e:
st.error(f"An unexpected error occurred: {e}")
traceback.print_exc()
else:
st.info("Upload an image to start the classification.")
# =======================
# Footer
# =======================
st.markdown("""
---
**AI Cancer Detection Platform** | This application is for informational purposes only and is not intended for medical diagnosis.
""")
|