|
|
import os |
|
|
|
|
|
os.environ["TF_USE_LEGACY_KERAS"] = "1" |
|
|
|
|
|
import gradio as gr |
|
|
import tensorflow as tf |
|
|
import tf_keras as keras |
|
|
import numpy as np |
|
|
from PIL import Image |
|
|
from huggingface_hub import hf_hub_download |
|
|
|
|
|
|
|
|
|
|
|
REPO_ID = "mediaportal/Braintumor-MRI-detection" |
|
|
MODEL_FILENAME = "BraintumorMRI99.h5" |
|
|
|
|
|
|
|
|
hf_token = os.getenv("HF_TOKEN") |
|
|
|
|
|
model = None |
|
|
|
|
|
def load_model_with_progress(progress=gr.Progress(track_tqdm=True)): |
|
|
global model |
|
|
try: |
|
|
progress(0, desc="Downloading model from Hugging Face...") |
|
|
path = hf_hub_download( |
|
|
repo_id=REPO_ID, |
|
|
filename=MODEL_FILENAME, |
|
|
token=hf_token |
|
|
) |
|
|
|
|
|
progress(0.7, desc="Loading weights into Xception architecture...") |
|
|
|
|
|
model = keras.models.load_model(path, compile=False) |
|
|
|
|
|
progress(1.0, desc="✅ Model Ready!") |
|
|
return "Model Loaded Successfully." |
|
|
except Exception as e: |
|
|
return f"❌ Error: {str(e)}" |
|
|
|
|
|
def predict(img): |
|
|
if model is None: |
|
|
return "System is still initializing. Please wait." |
|
|
|
|
|
if img is None: |
|
|
return "No image provided." |
|
|
|
|
|
|
|
|
img = Image.fromarray(img.astype('uint8'), 'RGB').resize((299, 299)) |
|
|
|
|
|
|
|
|
img_array = np.array(img).astype('float32') / 255.0 |
|
|
img_array = np.expand_dims(img_array, axis=0) |
|
|
|
|
|
prediction = model.predict(img_array)[0] |
|
|
|
|
|
|
|
|
|
|
|
labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"] |
|
|
|
|
|
return {labels[i]: float(prediction[i]) for i in range(len(labels))} |
|
|
|
|
|
|
|
|
with gr.Blocks(theme=gr.themes.Soft()) as demo: |
|
|
gr.Markdown("# 🧠 Brain Tumor MRI Classification") |
|
|
gr.Markdown("Identify Glioma, Meningioma, Pituitary tumors, or Healthy scans.") |
|
|
|
|
|
status_box = gr.Markdown("⏳ Initializing... Checking access to " + REPO_ID) |
|
|
|
|
|
with gr.Row(): |
|
|
with gr.Column(): |
|
|
input_img = gr.Image(label="Upload MRI Scan") |
|
|
btn = gr.Button("Run Diagnosis", variant="primary") |
|
|
with gr.Column(): |
|
|
output_label = gr.Label(num_top_classes=4, label="Prediction Result") |
|
|
|
|
|
|
|
|
demo.load(load_model_with_progress, outputs=status_box) |
|
|
btn.click(fn=predict, inputs=input_img, outputs=output_label) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
demo.queue().launch() |