Spaces:
Runtime error
Runtime error
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 | |
# ======================= | |
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. | |
""") | |