AI_doctor / breast_cancer_classifer.py
Ruchir456's picture
Rename breast_cancer_classifer (2).py to breast_cancer_classifer.py
b43704a verified
raw
history blame
3.57 kB
import os
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from huggingface_hub import hf_hub_download
import zipfile
# Step 1: Download the model directly from your Hugging Face repo
MODEL_REPO = "Ruchir456/breast-cancer-densenet"
MODEL_FILENAME = "best_model_savedmodel.zip"
EXTRACT_DIR = "best_model_savedmodel"
if not os.path.exists(EXTRACT_DIR):
print("Downloading model from Hugging Face repo...")
model_zip_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILENAME)
print("βœ… Model downloaded successfully!")
# Extract the zip
with zipfile.ZipFile(model_zip_path, 'r') as zip_ref:
zip_ref.extractall(EXTRACT_DIR)
print("βœ… Model extracted successfully!")
# Step 2: Detect the actual SavedModel folder (with saved_model.pb inside)
saved_model_dir = None
for root, dirs, files in os.walk(EXTRACT_DIR):
if "saved_model.pb" in files:
saved_model_dir = root
break
# Step 3: Load model once globally
try:
if saved_model_dir:
model = tf.keras.models.load_model(saved_model_dir, compile=False)
print(f"βœ… Model loaded successfully from {saved_model_dir}")
else:
model = None
print("❌ Could not find saved_model.pb inside extracted folder.")
except Exception as e:
model = None
print(f"❌ Failed to load the model: {e}")
# Step 4: Internal mapping from model index to class label
class_labels = {0: 'benign', 1: 'malignant', 2: 'normal'}
# Step 5: Mapping from class label to detailed medical interpretation
class_descriptions = {
'normal': (
"*Normal:* Cells appear healthy and show no signs of cancer. "
"There is no indication of abnormal tissue structure or cellular activity. "
"No further investigation is typically required, but periodic screenings help ensure continued health."
),
'benign': (
"*Benign:* Cells may appear abnormal but are *non-cancerous* and do not spread to other tissues. "
"These growths are usually slow-growing and not life-threatening. "
"Monitoring for changes in size or behavior is common, and removal may be considered if symptoms develop."
),
'malignant': (
"*Malignant:* Cells are *cancerous*, showing uncontrolled growth, abnormal structure, and potential to invade nearby tissues or spread to distant organs. "
"Further diagnostic evaluation and staging are important to determine the extent. "
"Management may involve treatment plans such as surgery, chemotherapy, or radiation depending on the progression."
)
}
# Step 6: Main prediction function
def breast_cancer_detection_model(image_path):
try:
if model is None:
return "❌ Model is not loaded. Please check logs."
# Load and preprocess the image
img = load_img(image_path, target_size=(256, 256))
img_array = img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0
# Make prediction
prediction = model.predict(img_array)
predicted_index = np.argmax(prediction)
predicted_class = class_labels[predicted_index]
confidence = prediction[0][predicted_index] * 100
# Format and return interpretation
result = class_descriptions[predicted_class]
# Optional: add model confidence
# result += f"\nπŸ“Š *Model Confidence:* {confidence:.2f}%"
return result
except Exception as e:
return f"❌ Error processing the image: {str(e)}"