|
|
import torch |
|
|
from torchvision import models, transforms |
|
|
from PIL import Image |
|
|
import gradio as gr |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
device = "cuda" if torch.cuda.is_available() else "cpu" |
|
|
MODEL_PATH = "cattle_breed_efficientnetb3_pytorch.pth" |
|
|
CLASS_NAMES = ["Gir", "Deoni", "Murrah"] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model = models.efficientnet_b3(pretrained=False) |
|
|
model.classifier[1] = torch.nn.Linear(model.classifier[1].in_features, len(CLASS_NAMES)) |
|
|
model.load_state_dict(torch.load(MODEL_PATH, map_location=device)) |
|
|
model.to(device) |
|
|
model.eval() |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
transform = transforms.Compose([ |
|
|
transforms.Resize((300, 300)), |
|
|
transforms.ToTensor(), |
|
|
transforms.Normalize([0.485, 0.456, 0.406], |
|
|
[0.229, 0.224, 0.225]) |
|
|
]) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def predict(image): |
|
|
image = image.convert("RGB") |
|
|
img_tensor = transform(image).unsqueeze(0).to(device) |
|
|
with torch.no_grad(): |
|
|
output = model(img_tensor) |
|
|
pred_idx = torch.argmax(output, dim=1).item() |
|
|
return CLASS_NAMES[pred_idx] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
iface = gr.Interface( |
|
|
fn=predict, |
|
|
inputs=gr.Image(type="pil"), |
|
|
outputs="text", |
|
|
title="Indian Bovine Breed Classifier", |
|
|
description="Upload an image of a cow and the model will predict its breed." |
|
|
) |
|
|
|
|
|
iface.launch() |
|
|
|