File size: 1,892 Bytes
69beb24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61

import gradio as gr
import os
import torch

from model import create_effnet_b2_instance
from timeit import default_timer as timer
from typing import Tuple, Dict

# Setup class names
with open("class_names.txt", "r") as f: 
  class_names = [food_name.strip() for food_name in  f.readlines()]

# Create Food101 compatible EffNetB2 instance
effnet_transforms,effnetb2_food_101 = create_effnet_b2_instance(num_classes = len(class_names))

# Load the saved model's state_dict()
effnetb2_food_101.load_state_dict(torch.load("effnetb2_food101_dict.pth",map_location = torch.device("cpu")))


def predict(img, model = effnetb2_food_101, transforms = effnet_transforms) -> Tuple[Dict,float]:
  # start a timer
  start_timer = timer()
  # transform the image to be used by the model
  prepreocpressed_image = transforms(img).unsqueeze(0)
  # turn off regularization and parameters
  model.eval()
  with torch.inference_mode():
    prediction = model(prepreocpressed_image)
    probabilities = torch.softmax(prediction,dim = 1)
  prob_dict = {class_names[i]: float(probabilities[0][i]) for i in range(len(class_names))}
  # calculate the time
  end_timer = timer()
  total_time = end_timer - start_timer
  return prob_dict,total_time


# create the gradio app
title = "FoodVision Big Classifier"
description = "An EfficientNetB2 feature extractor trained on the Food101 Dataset to classify across 101 possible classes of food."
article = "Model created using pytorch"

example_list = [["examples/" + example] for example in os.listdir("examples")]

# Create Gradio interface 
demo = gr.Interface(
    fn=predict,
    inputs=gr.Image(type="pil"),
    outputs=[
        gr.Label(num_top_classes=5, label="Predictions"),
        gr.Number(label="Prediction time (s)"),
    ],
    examples=example_list,
    title=title,
    description=description,
    article=article,
)

# Launch the app!
demo.launch()