import gradio as gr from transformers import AutoImageProcessor, AutoModelForImageClassification from PIL import Image, ImageDraw, ImageFont import torch import numpy as np model_name = "Hemgg/brain-tumor-classification" processor = AutoImageProcessor.from_pretrained(model_name) model = AutoModelForImageClassification.from_pretrained(model_name) class_names = ["🧠Glioma", "🎯 Meningioma", "✅ No Tumor", "⚡ Pituitary"] custom_css = """ .gradio-container {background-color: #050505 !important; color: #ffffff !important;} .md, .md p, .md h1, .md h2, .md h3, span, label {color: #ffffff !important;} #result-box { background-color: #1a1a1a !important; border: 2px solid #3b82f6 !important; border-radius: 12px; padding: 20px; color: #ffffff !important; } .gr-button-primary { background: linear-gradient(135deg, #1e40af, #7e22ce) !important; border: none !important; font-weight: bold !important; } #result-text * { color: #ffffff !important; } footer {display: none !important;} """ def get_medical_info(tumor_type): info = { "🧠Glioma": { "desc": "Gliomas originate in the glial cells that support neurons. They can be fast-growing and may involve surrounding brain tissue.", "next": "Urgent consultation with a neuro-oncologist. An MRI with contrast or a biopsy is typically the next diagnostic step." }, "🎯 Meningioma": { "desc": "These tumors arise from the meninges, the layers covering the brain. Most are slow-growing and benign but can cause pressure.", "next": "Consult a neurosurgeon to evaluate the mass effect. Treatment ranges from 'watchful waiting' to surgical resection." }, "⚡ Pituitary": { "desc": "Pituitary adenomas occur in the master gland at the base of the brain. They often affect hormone regulation and vision.", "next": "An endocrine workup (blood tests) and a visual field test are recommended to assess hormonal and optic nerve impact." }, "✅ No Tumor": { "desc": "The neural network did not detect significant signs of the three primary tumor types in this scan.", "next": "If symptoms (headaches, seizures, vision loss) persist, please consult a neurologist for a comprehensive evaluation." } } return info.get(tumor_type, {"desc": "", "next": ""}) def classify_tumor(image): if image is None: return "
Please upload a scan.
", None inputs = processor(images=image, return_tensors="pt") with torch.no_grad(): outputs = model(**inputs) probs = torch.nn.functional.softmax(outputs.logits, dim=-1) idx = probs.argmax(-1).item() conf = probs[0][idx].item() name = class_names[idx] med = get_medical_info(name) overlay = create_overlay(image, idx, conf) html_res = f"""Confidence Score: {conf:.1%}
Clinical Overview:
{med['desc']}
Recommended Next Steps:
{med['next']}
Probabilities: {", ".join([f"{class_names[i]}: {probs[0][i]:.1%}" for i in range(4)])}