File size: 2,066 Bytes
efc2ac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0068cb
 
efc2ac4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e3de5d4
 
efc2ac4
 
 
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

import gradio as gr 
import os 
import torch 

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

#setup class names 
class_names = ['pizza', 'steak', 'sushi']

#model and transforms preparation 
effnetb2, effnetb2_transforms = create_effnet_b2(
    num_classes = 3)

#load saved weights 
effnetb2.load_state_dict(
    torch.load(f = 'pretrained_effnetb2_feature_extractor.pth',
               map_location = torch.device('cpu')) #hardcoding to load state dict onto the cpu
)

#Predict function 

def predict(img) -> Tuple[Dict, float]: 

  #Start a timer
  start_time = timer()

  #transform the input image for use with effnetb2
  transformed_image = effnetb2_transforms(img).unsqueeze(0)

  #put model into deval mode, make preiction 
  effnetb2.eval()
  with torch.inference_mode(): 
    pred_logits = effnetb2(transformed_image) 
    pred_probs = torch.softmax(pred_logits, dim = 1)    

  # create a prediction label and pred prob dictionary 
  pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) 
                           for i in range(len(class_names))}
  
  #calculate pred time
  end_time = timer() 
  pred_time = end_time - start_time

  #return pred dict and pred time 
  print(pred_probs[0])
  return pred_labels_and_probs, pred_time 


# Gradio app 

import gradio as gr 

#Create title, description and article 
title = 'FoodVision Mini'
description = 'An EfficientNetB2 feature extractor to classify food as pizza, steak, and sushi'

#Create example list 
example_list = [['examples/' + example] for example in os.listdir('examples')]


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)

demo.launch(debug = False)