bhuvann13's picture
Update app.py
b4d39e8 verified
import gradio as gr
import tensorflow as tf
import numpy as np
from PIL import Image, ImageOps
import socket
def find_free_port():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('', 0))
return s.getsockname()[1]
free_port = find_free_port()
print(f"Launching Gradio on free port: {free_port}")
# Make sure this filename is correct!
model = tf.keras.models.load_model('best_cnnmodelf&n.h5')
class_names = ['glioma_tumor', 'meningioma_tumor', 'no_tumor', 'pituitary_tumor']
def preprocess(image):
size = (150, 150)
image = ImageOps.fit(image, size, Image.ANTIALIAS)
image = np.array(image) / 255.0
image = np.expand_dims(image, axis=0)
return image
def classify(image):
img = preprocess(image)
preds = model.predict(img)
scores = tf.nn.softmax(preds[0]).numpy()
top_idx = np.argmax(scores)
predicted_class = class_names[top_idx]
confidence = scores[top_idx] * 100
return f"Prediction: {predicted_class}", f"Confidence: {confidence:.2f}%"
iface = gr.Interface(
fn=classify,
inputs=gr.Image(type="pil", label="Upload MRI scan"),
outputs=[gr.Textbox(label="Prediction"), gr.Textbox(label="Confidence")],
title="Brain Tumor Classification",
description="""
Upload a brain MRI scan image (jpg or png). The model will classify the tumor type as:
- Glioma Tumor
- Meningioma Tumor
- No Tumor
- Pituitary Tumor
""",
allow_flagging="never",
)
if __name__ == "__main__":
iface.launch(server_port=free_port)