File size: 2,458 Bytes
50f5037
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63d49d2
50f5037
 
 
 
d4c0cb7
50f5037
 
 
 
 
 
 
 
 
 
 
 
 
8427ba8
50f5037
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2142cd1
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

import torch
import torchvision
from torch import nn
from timeit import default_timer as timer
from typing import Tuple,Dict
import os
from model import create_effnetb2

# gettingthe classnames
class_names = ["pizza","steak","sushi"]

#lets verify if we can get list of example
foodvision_mini_examples_path = "examples/"
example_list = ["examples/" + example for example in os.listdir(foodvision_mini_examples_path)]

# getting model and its trasofrm
effnetb2_2, effnetb2_transforms_2 = create_effnetb2() # we dont need "model.craete_effnetb2" as its directly imported by us

# load the saved weigths
effnetb2_2.load_state_dict(
    torch.load(
        f = "09_pretrained_effnetb2_feature_extractor_20_percent.pth",
        map_location= torch.device("cpu")
    )
)

# craeting the predict function
def predict(img) -> Tuple[Dict,float]:
  # start a timer
  start_time = timer()

  # transfomr the input image for use with EffNetB2
  transformed_img = effnetb2_transforms_2(img).unsqueeze(0).to("cpu")

  # put the mdoel to eva; mode and make predictions
  effnetb2_2.eval()
  with torch.inference_mode():
    logits = effnetb2_2(transformed_img)
    pred_probs = torch.softmax(logits, dim = 1)
    # print(pred_probs)
    pred_class = class_names[torch.argmax(pred_probs, dim = 1)]

    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 = round(end_time - start_time, 4)

  # return pred dict AND PRED TIME
  return pred_labels_and_probs, pred_time

# interface zone
import gradio as gr

# craete title , description and article
title = "Food Vision Mini 🍕🥩🍣"
description = "An [EfficientNetB2 Feature Extractor Computer Vision Model](https://pytorch.org/vision/main/models/generated/torchvision.models.efficientnet_b2.html) to classify images as pizza, steak and sushi"
article = "Created at [09 PyTorch model deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)"

# craeting gradio demo
demo = gr.Interface(fn = predict,inputs = gr.Image(type = "pil"),
                    outputs = [gr.Label(num_top_classes=3, label = "predictions") , gr.Number(label = "prediciton time(s)")],
                    examples = example_list,
                    title = title , description = description, article = article)
demo.launch() # to avoid showing of error, we dont need share = true as it cant be handled by higging face spaces