foodvision_mini / app.py
Rick-29's picture
initial commit
53b2f95
raw
history blame
2.36 kB
### 1. Imports and class names setup
import gradio as gr
import torch
import os
from timeit import default_timer as timer
from model import create_effnetb2_model
from typing import Tuple, Dict
# Setup class names
class_names = ["pizza", "steak", "sushi"]
### 2. Model and transforms preparation
effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes = len(class_names))
# Load the saved weights
effnetb2.load_state_dict(torch.load(f="09_pretrained_effnetb2_feature_extractor_20_percent.pth",
map_location=torch.device("cpu")))
### 3. Predict function
def predict(img) -> Tuple[Dict, float]:
# Start a timer
start_time = timer()
# Transform the input image for use with EffNetB2
img = effnetb2_transforms(img).unsqueeze(0)
# Put model into eval mode to make prediction
effnetb2.eval()
with torch.inference_mode():
# Pass transformed image through the model
pred_probs = torch.softmax(effnetb2(img), dim=1).squeeze()
# Create a prediction label and prediction probability dictionary
pred_labels_and_probs = {food: float(pred_probs[i]) for i, food in enumerate(class_names)}
# Calculate pred time
pred_time = round(timer() - start_time, 4)
# Return pred dict and pred time
return pred_labels_and_probs, pred_time
### 4. Create the Gradio app
title = "FoodVision Mini🍕🥩🍣"
description = "An [EfficientNetB2 Feature Extractor](https://pytorch.org/vision/main/models/efficientnet.html#efficientnet_b2) computer vision model to classify images as pizza, steak and sushi."
article = "Created at [09. Pytorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment)"
# Create example list
example_list = [["examples/" + example] for example in os.listdir("examples")]
# Create the gradio demo
demo = gr.Interface(fn=predict,
inputs=gr.Image(type="pil"),
outputs=[gr.Label(num_top_classes=3, label="Predictions"),
gr.Number(label="Prediction time (s)")],
examples=example_list,
title=title,
description=description,
article=article)
# Launch the demo
demo.launch(debug=False, # Print errors locally?
share=True) # generate a publically available URL