import os import urllib.request import numpy as np import tensorflow as tf from tensorflow.keras.applications import EfficientNetB0 from tensorflow.keras.layers import Dense, GlobalAveragePooling2D, Dropout, BatchNormalization from tensorflow.keras.models import Model import gradio as gr import cv2 import spaces # <--- ต้องมี import นี้ MODEL_PATH = "efficientnetb0_finetuned_brain_mri.keras" MODEL_URL = "https://huggingface.co/starpreeda/BrainTumorTest/resolve/main/efficientnetb0_finetuned_brain_mri.keras" def load_brain_mri_model(): if not os.path.exists(MODEL_PATH): print("Downloading model weights from Hugging Face Repository...") try: urllib.request.urlretrieve(MODEL_URL, MODEL_PATH) print("Model downloaded successfully!") except Exception as e: raise RuntimeError(f"ไม่สามารถดาวน์โหลดโมเดลได้: {e}") from e base_model = EfficientNetB0(weights=None, include_top=False, input_shape=(224, 224, 3)) x = base_model.output x = GlobalAveragePooling2D()(x) x = BatchNormalization()(x) x = Dense(256, activation='relu')(x) x = Dropout(0.4)(x) outputs = Dense(4, activation='softmax')(x) model = Model(inputs=base_model.input, outputs=outputs) model.load_weights(MODEL_PATH) return model model = load_brain_mri_model() CLASS_MAPPING = { 'glioma': {'name': 'Glioma Tumor', 'desc': 'A type of tumor that originates in the glial cells.'}, 'meningioma': {'name': 'Meningioma Tumor', 'desc': 'A tumor arising from the meninges.'}, 'notumor': {'name': 'No Tumor Detected', 'desc': 'No clear evidence of brain tumor tissue.'}, 'pituitary': {'name': 'Pituitary Tumor', 'desc': 'An abnormal growth located in the pituitary gland.'} } CLASS_NAMES = ['glioma', 'meningioma', 'notumor', 'pituitary'] # ใส่ @spaces.GPU กลับเข้ามาเพื่อรองรับ ZeroGPU environment @spaces.GPU def predict_mri(input_img): if input_img is None: return "
Predicted Class: {info['name']}
Confidence Score: {top_confidence:.2f}%
Clinical Note: {info['desc']}