pratham / app.py
Primus11's picture
link added
e98e28c
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
)