File size: 2,944 Bytes
e3d2890
66d9598
ecd3438
e3d2890
 
 
26172ab
e3d2890
 
 
 
 
66d9598
 
ecd3438
e3d2890
66d9598
26172ab
 
e3d2890
 
 
 
 
66d9598
26172ab
 
 
 
 
e3d2890
66d9598
 
e3d2890
 
 
26172ab
e3d2890
 
 
 
 
66d9598
e3d2890
 
 
 
66d9598
ecd3438
e3d2890
66d9598
e3d2890
 
 
 
 
66d9598
 
e3d2890
 
 
 
ecd3438
e3d2890
66d9598
 
e3d2890
66d9598
e3d2890
 
 
 
66d9598
e3d2890
66d9598
e3d2890
66d9598
e3d2890
 
 
 
 
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
import os
# Forces the use of Keras 2 logic, preventing common 'recursion' errors in new environments
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

# --- CONFIGURATION ---
# Based on your provided link: https://huggingface.co/mediaportal/Braintumor-MRI-detection
REPO_ID = "mediaportal/Braintumor-MRI-detection" 
MODEL_FILENAME = "BraintumorMRI99.h5"

# If your repo is set to PRIVATE, add your token to Space Secrets as 'HF_TOKEN'
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...")
        # compile=False avoids loading the optimizer state from the training session
        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."

    # Preprocessing based on notebook: Xception requires 299x299
    img = Image.fromarray(img.astype('uint8'), 'RGB').resize((299, 299))
    
    # Rescale 1/255 as used in the notebook's ImageDataGenerator
    img_array = np.array(img).astype('float32') / 255.0
    img_array = np.expand_dims(img_array, axis=0)
    
    prediction = model.predict(img_array)[0]
    
    # Class labels identified from tr_df in the notebook
    # Standard order for this dataset: glioma, meningioma, notumor, pituitary
    labels = ["Glioma", "Meningioma", "No Tumor", "Pituitary"]
    
    return {labels[i]: float(prediction[i]) for i in range(len(labels))}

# --- GRADIO INTERFACE ---
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")

    # Load model immediately upon app startup
    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()