Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import numpy as np
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import tensorflow as tf
|
| 5 |
+
from tensorflow.keras.models import load_model
|
| 6 |
+
from tensorflow.keras import backend as K
|
| 7 |
+
|
| 8 |
+
# ---- Custom metrics/loss required to load your model ---- #
|
| 9 |
+
def dice_coef(y_true, y_pred):
|
| 10 |
+
y_true = K.cast(y_true, 'float32')
|
| 11 |
+
y_pred = K.cast(y_pred, 'float32')
|
| 12 |
+
y_true_f = K.flatten(y_true)
|
| 13 |
+
y_pred_f = K.flatten(y_pred)
|
| 14 |
+
intersect = K.sum(y_true_f * y_pred_f)
|
| 15 |
+
return (2. * intersect + K.epsilon()) / (K.sum(y_true_f) + K.sum(y_pred_f) + K.epsilon())
|
| 16 |
+
|
| 17 |
+
# ---- Load model from Hugging Face model repo ---- #
|
| 18 |
+
model_path = "yaraa11/brain-tumor-segmentation" # <-- Replace with your HF model ID
|
| 19 |
+
model = load_model(model_path, custom_objects={'dice_coef': dice_coef}, compile=False)
|
| 20 |
+
|
| 21 |
+
IMG_SIZE = (224, 224)
|
| 22 |
+
|
| 23 |
+
# ---- Prediction function for Gradio ---- #
|
| 24 |
+
def predict(img):
|
| 25 |
+
# Convert to grayscale if not already
|
| 26 |
+
img = img.convert("L")
|
| 27 |
+
|
| 28 |
+
# Resize
|
| 29 |
+
img_resized = img.resize(IMG_SIZE)
|
| 30 |
+
x = np.array(img_resized) / 255.0
|
| 31 |
+
x = np.expand_dims(x, axis=(0, -1)) # shape: (1, 224, 224, 1)
|
| 32 |
+
|
| 33 |
+
# Predict mask
|
| 34 |
+
pred = model.predict(x)[0]
|
| 35 |
+
mask = (pred > 0.5).astype(np.uint8) * 255 # Convert to binary mask
|
| 36 |
+
|
| 37 |
+
# Convert numpy mask to image
|
| 38 |
+
mask_img = Image.fromarray(mask.squeeze(), mode="L")
|
| 39 |
+
return mask_img
|
| 40 |
+
|
| 41 |
+
# ---- Gradio Interface ---- #
|
| 42 |
+
interface = gr.Interface(
|
| 43 |
+
fn=predict,
|
| 44 |
+
inputs=gr.Image(type="pil", label="Upload Brain MRI Image"),
|
| 45 |
+
outputs=gr.Image(type="pil", label="Predicted Tumor Mask"),
|
| 46 |
+
title="Brain Tumor Segmentation",
|
| 47 |
+
description="Upload a brain MRI image to generate a tumor segmentation mask."
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
interface.launch()
|