foodClassifier / app.py
jflo's picture
Create app.py
4e80033
raw history blame
No virus
1.61 kB
import gradio as gr
import torch
import torch.nn.functional as F
from torchvision import transforms
# load model
model = torch.jit.load("food_classifier.ptl")
# Transformations that will be applied
the_transform = transforms.Compose([
transforms.Resize((224,224)),
transforms.CenterCrop((224,224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485,0.456,0.406],std=[0.229,0.224,0.225])
])
# Classes
class_names = ['Apple Pie','Bibimbap','Cannoli','Edamame','Falafel','French Toast','Ice Cream','Ramen','Sushi','Tiramisu']
# Returns transformed image
def transform_img(img):
return the_transform(img)
# Returns string with class and probability
def classify_img(img):
# Applying transformation to the image
model_img = transform_img(img)
model_img = model_img.view(1,3,224,224)
# Running image through the model
model.eval()
with torch.no_grad():
result = model(model_img)
# Converting values to softmax values
result = F.softmax(result,dim=1)
probability = round(result[0][result.argmax()].item() * 100, 2)
# Returning class name and probability
return f'{class_names[result.argmax()]} : {probability}% confident'
demo = gr.Interface(classify_img,
inputs = gr.inputs.Image(type="pil"),
outputs = "text",
description="Insert food image you would like to classify! <br> Categories: Apple Pie, Bibimbap, Cannoli, Edamame, Falafel, French Toast, Ice Cream, Ramen, Sushi, Tiramisu")
demo.launch(inline=False)