Spaces:
Running
Running
File size: 1,479 Bytes
5af6ec6 a7b6188 285d957 a7b6188 285d957 a7b6188 285d957 a7b6188 285d957 9fba7e2 5af6ec6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import gradio as gr
import torch
from torchvision import transforms
from PIL import Image
# 1. Load your model (Ensure this matches your training architecture)
# Change 'models.resnet18' if you used a different one
# --- UPDATED MODEL ARCHITECTURE ---
import torch.nn as nn
from torchvision import models
# 1. Initialize ResNet-50 (matches the 2048 feature size in your error)
model = models.resnet50()
# 2. Recreate the EXACT Sequential head used during your training
# This fixes the "Missing key: fc.0.weight" and "fc.3.weight" errors
model.fc = nn.Sequential(
nn.Linear(2048, 256), # fc.0
nn.ReLU(), # fc.1
nn.Dropout(0.4), # fc.2
nn.Linear(256, 2) # fc.3
)
# 3. Load your weights
model.load_state_dict(torch.load("fine_tuned_model.pt", map_location="cpu"))
model.eval()
# 2. Define labels based on your dataset folders
labels = ["Defect", "Normal"]
def predict(img):
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
])
img = transform(img).unsqueeze(0)
with torch.no_grad():
prediction = torch.nn.functional.softmax(model(img)[0], dim=0)
confidences = {labels[i]: float(prediction[i]) for i in range(2)}
return confidences
# 3. Create the Interface
interface = gr.Interface(
fn=predict,
inputs=gr.Image(type="pil"),
outputs=gr.Label(num_top_classes=2),
title="Wall/Floor Tile Defect Inspector"
)
interface.launch() |