Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216import torchimport torch.nn.functional as Fimport timmimport gradio as grfrom PIL import Imagefrom torchvision import transforms
# -----------------------------# Class labels for OCTMNIST# -----------------------------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# Must match your notebook preprocessing# -----------------------------transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.Grayscale(num_output_channels=3), transforms.ToTensor(),])
# -----------------------------# Load model# Must match your notebook model# -----------------------------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: return None, "Please upload an OCT image first.", {}
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""" <div class="result-card"> <h2>Prediction Result</h2> <p><b>Predicted Class ID:</b> {pred_idx}</p> <p><b>Predicted Class Name:</b> {pred_name}</p> <p><b>Confidence:</b> {confidence:.4f}</p> </div> """
return image, result_text, label_scores
# -----------------------------# Example description# -----------------------------description = """Upload a retinal OCT image and the model will classify it into one of the OCTMNIST disease categories.
Classes:0 = Choroidal Neovascularization 1 = Diabetic Macular Edema 2 = Drusen 3 = Normal"""
# -----------------------------# Custom CSS for beautiful UI# -----------------------------custom_css = """body { background: linear-gradient(135deg, #f7fbff 0%, #eef5ff 50%, #ffffff 100%);}
.gradio-container { max-width: 1150px !important; margin: auto !important;}
.main-title { text-align: center; font-size: 42px; font-weight: 800; color: #17324d; margin-bottom: 8px;}
.subtitle { text-align: center; font-size: 18px; color: #4c6275; margin-bottom: 28px;}
.result-card { background: linear-gradient(135deg, #ffffff, #f4f8ff); border: 1px solid #dbe8ff; border-radius: 18px; padding: 22px; box-shadow: 0 8px 28px rgba(23, 50, 77, 0.10);}
.result-card h2 { color: #17324d; margin-top: 0px;}
.result-card p { font-size: 17px; color: #263849;}
.footer-note { text-align: center; color: #68798a; font-size: 14px; margin-top: 25px;}"""
# -----------------------------# Gradio Interface# -----------------------------with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo:
gr.HTML(""" <div class="main-title">OCTMNIST Retinal Disease Classifier</div> <div class="subtitle"> EfficientNetV2-S based OCT image classification demo </div> """)
with gr.Row(): with gr.Column(scale=1): input_image = gr.Image( label="Upload OCT Image", type="pil", height=360 )
predict_button = gr.Button( "Classify Image", variant="primary" )
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" )
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(""" <div class="footer-note"> Note: This is a research/educational demo and should not be used as a clinical diagnostic tool. </div> """)
if __name__ == "__main__": demo.launch()app.pyAdded+216