import torch import torch.nn.functional as F import timm import gradio as gr from PIL import Image from torchvision import transforms # ----------------------------- # OCTMNIST class labels # ----------------------------- CLASS_NAMES = { 0: "Choroidal Neovascularization", 1: "Diabetic Macular Edema", 2: "Drusen", 3: "Normal" } # ----------------------------- # Device # ----------------------------- device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # ----------------------------- # Image preprocessing # This should match your notebook preprocessing # ----------------------------- transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.Grayscale(num_output_channels=3), transforms.ToTensor(), ]) # ----------------------------- # Load EfficientNetV2-S model # This must match the architecture used during training # ----------------------------- model = timm.create_model( "efficientnetv2_s", pretrained=False, num_classes=4 ) state_dict = torch.load("efficient.pth", map_location=device) model.load_state_dict(state_dict) model = model.to(device) model.eval() # ----------------------------- # Prediction function # ----------------------------- def predict_oct(image): if image is None: empty_probs = { CLASS_NAMES[i]: 0.0 for i in range(len(CLASS_NAMES)) } message = """

No image uploaded

Please upload an OCT image first.

""" return None, message, empty_probs image = image.convert("RGB") input_tensor = transform(image).unsqueeze(0).to(device) with torch.no_grad(): outputs = model(input_tensor) probs = F.softmax(outputs, dim=1)[0] pred_idx = int(torch.argmax(probs).item()) pred_name = CLASS_NAMES[pred_idx] confidence = float(probs[pred_idx].item()) label_scores = { CLASS_NAMES[i]: float(probs[i].item()) for i in range(len(CLASS_NAMES)) } result_text = f"""

Prediction Result

{pred_name}

Predicted Class ID: {pred_idx}

Predicted Class Name: {pred_name}

Confidence: {confidence:.4f}

""" return image, result_text, label_scores # ----------------------------- # Description text # ----------------------------- description = """ ### About this demo Upload a retinal OCT image and the model will classify it into one of the OCTMNIST categories. **Classes:** - `0` — Choroidal Neovascularization - `1` — Diabetic Macular Edema - `2` — Drusen - `3` — Normal This app uses an EfficientNetV2-S model trained on OCTMNIST. """ # ----------------------------- # Custom CSS # ----------------------------- custom_css = """ body { background: linear-gradient(135deg, #f7fbff 0%, #eef5ff 45%, #ffffff 100%); } .gradio-container { max-width: 1180px !important; margin: auto !important; } .main-wrapper { background: linear-gradient(135deg, #ffffff, #f4f8ff); border: 1px solid #dbe8ff; border-radius: 28px; padding: 32px; box-shadow: 0 14px 40px rgba(23, 50, 77, 0.10); margin-bottom: 25px; } .main-title { text-align: center; font-size: 44px; font-weight: 900; color: #17324d; margin-bottom: 8px; letter-spacing: -0.5px; } .subtitle { text-align: center; font-size: 18px; color: #4c6275; margin-bottom: 10px; } .badge-row { text-align: center; margin-top: 18px; } .badge { display: inline-block; background: #e9f2ff; color: #25527a; border: 1px solid #cfe2ff; border-radius: 999px; padding: 8px 14px; font-weight: 600; font-size: 14px; margin: 4px; } .result-card { background: linear-gradient(135deg, #ffffff, #f4f8ff); border: 1px solid #dbe8ff; border-radius: 22px; padding: 24px; box-shadow: 0 10px 30px rgba(23, 50, 77, 0.10); } .result-card h2 { color: #17324d; margin-top: 0px; margin-bottom: 16px; } .result-card p { font-size: 17px; color: #263849; margin: 10px 0px; } .prediction-main { background: linear-gradient(135deg, #e9f2ff, #ffffff); border: 1px solid #cfe2ff; border-radius: 18px; padding: 18px; margin-bottom: 18px; text-align: center; } .prediction-label { font-size: 25px; font-weight: 900; color: #17324d; } .footer-note { text-align: center; color: #68798a; font-size: 14px; margin-top: 24px; } .upload-note { background: #f8fbff; border-left: 4px solid #7aaef7; padding: 14px 16px; border-radius: 12px; color: #41576b; font-size: 15px; } """ # ----------------------------- # Gradio UI # In Gradio 6, css and theme go inside launch() # ----------------------------- with gr.Blocks() as demo: gr.HTML("""
OCTMNIST Retinal Disease Classifier
Upload an OCT image and get the predicted disease class using EfficientNetV2-S
EfficientNetV2-S OCTMNIST 4-Class Classification PyTorch + Gradio
""") with gr.Row(): with gr.Column(scale=1): input_image = gr.Image( label="Upload OCT Image", type="pil", height=380 ) predict_button = gr.Button( "Classify Image", variant="primary", size="lg" ) gr.HTML("""
Upload a retinal OCT image. The app will return both the class ID and the medical class name.
""") gr.Markdown(description) with gr.Column(scale=1): output_image = gr.Image( label="Input Preview", type="pil", height=300 ) output_text = gr.HTML( label="Prediction Result" ) output_label = gr.Label( label="Class Probabilities", num_top_classes=4 ) predict_button.click( fn=predict_oct, inputs=input_image, outputs=[output_image, output_text, output_label] ) gr.HTML(""" """) # ----------------------------- # Launch app # For Hugging Face Spaces, do not need share=True # ----------------------------- if __name__ == "__main__": demo.launch( theme=gr.themes.Soft(), css=custom_css )