File size: 8,752 Bytes
783f62a e98e28c 783f62a |
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 |
import gradio as gr
import numpy as np
from PIL import Image
import tensorflow as tf
import os
# Load only brain tumor model for now
def load_brain_model():
try:
brain_model = tf.keras.models.load_model('models/brain_best.keras')
print("β
Brain tumor model loaded successfully!")
return brain_model
except Exception as e:
print(f"β Error loading brain tumor model: {e}")
return None
brain_model = load_brain_model()
def preprocess_image(image):
if image is None:
return None
# Convert to RGB if needed
if image.mode != 'RGB':
image = image.convert('RGB')
# Resize to model input size
image = image.resize((224, 224))
img_array = np.array(image) / 255.0
img_array = np.expand_dims(img_array, axis=0)
return img_array
def predict_cancer(cancer_type, image):
# This function will only be called for brain tumor detection
# since the button is hidden for other cancer types
if brain_model is None:
return "β Brain tumor model not loaded properly. Please check model files."
if image is None:
return "β οΈ Please upload an MRI scan first."
if cancer_type == "Brain Tumor Detection":
try:
processed_image = preprocess_image(image)
if processed_image is None:
return "β Error processing image."
prediction = brain_model.predict(processed_image, verbose=0)[0][0]
confidence = prediction * 100
if prediction > 0.5:
result = f"π΄ **Brain Tumor Detected**\nConfidence: {confidence:.2f}%"
else:
result = f"π’ **No Brain Tumor Detected**\nConfidence: {100 - confidence:.2f}%"
return result
except Exception as e:
return f"β Error during prediction: {str(e)}"
else:
return "β This function should only be called for brain tumor detection."
def update_info(cancer_type):
info_text = {
"Brain Tumor Detection":
"""π§ **Brain Tumor Detection**
**What to upload:** MRI scan images of the brain
**Supported formats:** JPG, PNG, JPEG
**Model type:** Binary classification (Tumor/No Tumor)
**Status:** β
Active and ready to use
**Note:** This model detects the presence of brain tumors in MRI scans.
Early detection is crucial for effective treatment.""",
"Breast Cancer Detection":
"""ποΈ **Breast Cancer Detection**
**Status:** π§ Under Development
**What it will do:** Analyze mammography or histopathology images
**Future features:** Binary classification (Malignant/Benign)
**Note:** This feature is currently being developed.
We're working hard to bring you accurate breast cancer detection soon!
For now, please use the Brain Tumor Detection feature.""",
"Skin Cancer Detection":
"""π **Skin Cancer Detection**
**Status:** π§ Under Development
**What it will do:** Analyze dermoscopy or clinical images of skin lesions
**Future features:** Multi-class classification for various skin conditions
**Note:** This feature is currently being developed.
We're working on accurate skin cancer detection capabilities!
For now, please use the Brain Tumor Detection feature."""
}
return info_text.get(cancer_type, "Please select a cancer type.")
def update_interface_visibility(cancer_type):
"""Update visibility of upload components based on cancer type"""
if cancer_type == "Brain Tumor Detection":
return [
gr.update(visible=True), # image_input
gr.update(visible=True), # predict_btn
gr.update(value="Upload an MRI scan and click 'Analyze Image' to detect brain tumors.") # result_output
]
else:
development_message = f"π§ **{cancer_type}**\n\nπ§ This feature is currently under development.\nWe're working hard to bring you this functionality soon!\n\nFor now, please use the Brain Tumor Detection feature."
return [
gr.update(visible=False), # image_input
gr.update(visible=False), # predict_btn
gr.update(value=development_message) # result_output
]
def create_interface():
with gr.Blocks(
theme=gr.themes.Soft(),
title="π©Ί Cancer Detection System"
) as app:
gr.HTML("""
<div style="text-align: center; padding: 20px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px; margin-bottom: 20px;">
<h1>π©Ί AI-Powered Cancer Detection System</h1>
<p><em>"Early Detection Saves Lives"</em></p>
</div>
""")
gr.HTML("""
<div style="background-color: #fff3cd; border: 1px solid #ffeaa7; border-radius: 5px; padding: 15px; margin: 10px 0; color: #856404;">
<strong>β οΈ Medical Disclaimer:</strong> This tool is for educational and research purposes only.
It should NOT be used as a substitute for professional medical diagnosis.
Always consult with qualified healthcare professionals for medical decisions.
</div>
""")
with gr.Row():
with gr.Column(scale=1):
cancer_type = gr.Radio(
choices=["Brain Tumor Detection", "Breast Cancer Detection", "Skin Cancer Detection"],
label="π― Select Cancer Type",
value="Brain Tumor Detection"
)
image_input = gr.Image(
label="π· Upload Medical Image",
type="pil",
height=300,
visible=True
)
predict_btn = gr.Button(
"π Analyze Image",
variant="primary",
size="lg",
visible=True
)
info_panel = gr.Markdown(
value=update_info("Brain Tumor Detection"),
label="βΉοΈ Information"
)
with gr.Column(scale=1):
result_output = gr.Markdown(
label="π Analysis Results",
value="Upload an MRI scan and click 'Analyze Image' to detect brain tumors.",
height=200
)
gr.Markdown("""
### π¬ How it works:
1. **Select** the type of cancer detection
2. **Upload** a medical image (MRI, mammography, or dermoscopy)
3. **Click** "Analyze Image" to get AI-powered analysis
4. **Review** the results and confidence scores
### π― Model Information:
- **Brain Tumor**: β
MobileNet-based binary classifier (Active)
- **Breast Cancer**: π§ Under development
- **Skin Cancer**: π§ Under development
### π Current Status:
Only Brain Tumor Detection is currently available.
Other features are being developed for future releases.
""")
# Event handlers
cancer_type.change(
fn=lambda ct: [update_info(ct)] + update_interface_visibility(ct),
inputs=[cancer_type],
outputs=[info_panel, image_input, predict_btn, result_output]
)
predict_btn.click(
fn=predict_cancer,
inputs=[cancer_type, image_input],
outputs=[result_output]
)
gr.HTML("""
<div style="text-align: center; margin-top: 30px; padding: 20px; background-color: #f8f9fa; border-radius: 10px;">
<p><strong>π¨ Remember:</strong> This is an AI assistant for educational purposes.
For actual medical concerns, please consult healthcare professionals.</p>
<p><em>Built with β€οΈ using Gradio and TensorFlow</em></p>
</div>
""")
return app
if __name__ == "__main__":
if brain_model is None:
print("β Cannot start application - brain tumor model failed to load")
print("Please ensure the following file exists in the 'models/' directory:")
print("- brain_best.keras")
else:
print("π Starting Cancer Detection System...")
app = create_interface()
app.launch(
share=True,
server_name="127.0.0.1",
server_port=7862,
show_error=True,
quiet=False
) |