import torch import numpy as np from PIL import Image import gradio as gr from torchvision import transforms from transformers import ViTForImageClassification # ───────────────────────────────────── # Device # ───────────────────────────────────── device = "cuda" if torch.cuda.is_available() else "cpu" # ───────────────────────────────────── # Classes (MUST match training order) # ───────────────────────────────────── classes = [ "Damaged_Infrastructure", "Fire_Disaster", "Human_Damage", "Land_Disaster", "Non_Damage", "Water_Disaster" ] # ───────────────────────────────────── # Load Model # ───────────────────────────────────── model = ViTForImageClassification.from_pretrained( "google/vit-base-patch16-224", num_labels=len(classes), ignore_mismatched_sizes=True ) # Load trained weights state_dict = torch.load("best_model.pth", map_location=device) model.load_state_dict(state_dict) model.to(device) model.eval() print("✅ Model loaded successfully") # ───────────────────────────────────── # Image Transform (same as validation) # ───────────────────────────────────── transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) # ───────────────────────────────────── # Prediction Function # ───────────────────────────────────── def predict(image): if image is None: return "⚠️ Please upload an image" # Ensure RGB image = image.convert("RGB") img = transform(image).unsqueeze(0).to(device) with torch.no_grad(): logits = model(img).logits probs = torch.softmax(logits, dim=1)[0] conf, pred = torch.max(probs, dim=0) conf_val = conf.item() pred_class = classes[pred] # ───────────────────────────── # Case 1: Uncertain prediction # ───────────────────────────── if conf_val < 0.70: return ( "Uncertain / Unknown\n" f"Confidence: {conf_val*100:.2f}%\n" "Severity: None" ) # ───────────────────────────── # Case 2: Non-Damage # ───────────────────────────── if pred_class == "Non_Damage": return ( f"✅ {pred_class}\n" f"Confidence: {conf_val*100:.2f}%\n" "Severity: None" ) # ───────────────────────────── # Case 3: Disaster → Severity # ───────────────────────────── severity = conf_val * 100 if severity >= 90: level = "High" elif severity >= 75: level = "Medium" else: level = "Low" return ( f"🔥 {pred_class}\n" f"Confidence: {conf_val*100:.2f}%\n" f"Severity: {severity:.2f}% ({level})" ) # ───────────────────────────────────── # Gradio UI # ───────────────────────────────────── interface = gr.Interface( fn=predict, inputs=gr.Image(type="pil", label="Upload Image"), outputs=gr.Textbox(label="Prediction Result"), title="🔥 Disaster Classification AI", description=( "Upload an image to classify disaster type.\n\n" "Severity is estimated based on model confidence.\n" "Low-confidence predictions are marked as uncertain." ), theme="soft" ) # ───────────────────────────────────── # Launch # ───────────────────────────────────── if __name__ == "__main__": interface.launch()