|
|
import gradio as gr |
|
|
import torch |
|
|
from torchvision import transforms |
|
|
from PIL import Image |
|
|
|
|
|
|
|
|
from model import SimpleCNN |
|
|
|
|
|
|
|
|
|
|
|
MODEL_PATH = "air_analyzer_cnn_iden_7m.pth" |
|
|
NUM_CLASSES = 3 |
|
|
|
|
|
class_names = ["Cat", "Dog", "Bird"] |
|
|
|
|
|
|
|
|
|
|
|
model = SimpleCNN(num_classes=NUM_CLASSES) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
model.load_state_dict(torch.load(MODEL_PATH, map_location=torch.device('cpu'))) |
|
|
|
|
|
|
|
|
model.eval() |
|
|
|
|
|
|
|
|
|
|
|
transform = transforms.Compose([ |
|
|
transforms.Resize((224, 224)), |
|
|
transforms.ToTensor(), |
|
|
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
|
|
]) |
|
|
|
|
|
|
|
|
def predict(input_image: Image.Image): |
|
|
""" |
|
|
Takes a PIL image, processes it, and returns a dictionary of class probabilities. |
|
|
""" |
|
|
|
|
|
image_tensor = transform(input_image).unsqueeze(0) |
|
|
|
|
|
|
|
|
with torch.no_grad(): |
|
|
outputs = model(image_tensor) |
|
|
|
|
|
|
|
|
probabilities = torch.nn.functional.softmax(outputs[0], dim=0) |
|
|
|
|
|
|
|
|
confidences = {class_names[i]: float(prob) for i, prob in enumerate(probabilities)} |
|
|
|
|
|
return confidences |
|
|
|
|
|
|
|
|
|
|
|
image_input = gr.Image(type="pil", label="Upload an Image") |
|
|
label_output = gr.Label(num_top_classes=3, label="Predictions") |
|
|
|
|
|
|
|
|
|
|
|
example_images = [ |
|
|
"sample_cat.jpg", |
|
|
"sample_dog.jpg", |
|
|
"sample_bird.jpg" |
|
|
] |
|
|
|
|
|
|
|
|
iface = gr.Interface( |
|
|
fn=predict, |
|
|
inputs=image_input, |
|
|
outputs=label_output, |
|
|
title="Image Classifier", |
|
|
description="Upload an image of a cat, dog, or bird to see the model's prediction.", |
|
|
examples=example_images |
|
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
|
iface.launch() |