Signorpopo commited on
Commit
353451f
β€’
1 Parent(s): 175aa05

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +70 -0
app.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ### 1. Imports and class names setup ###
3
+ import gradio as gr
4
+ import os
5
+ import torch
6
+
7
+ from model import create_effnetb2_model
8
+ from timeit import default_timer as timer
9
+ from typing import Tuple, Dict
10
+
11
+ # Setup class names
12
+ with open("class_names.txt", "r") as f:
13
+ class_names = [food_name.strip() for food_name in f.readlines()]
14
+
15
+ ### 2. Model and transforms preparation
16
+ effnetb2, effnetb2_transforms = create_effnetb2_model(
17
+ num_classes=101)
18
+
19
+ # Load saved weights
20
+ effnetb2.load_state_dict(
21
+ torch.load(
22
+ f="09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth",
23
+ map_location=torch.device("cpu") # load the model to the CPU
24
+ )
25
+ )
26
+
27
+ ### 3. Predict function ###
28
+ def predict(img) -> Tuple[Dict, float]:
29
+ # Start a timer
30
+ start_time = timer()
31
+
32
+ # Transform the input image for use with EffNetB2
33
+ img = effnetb2_transforms(img).unsqueeze(0) # unsqueeze = add batch dimension on 0th index
34
+
35
+ # Put model into eval mode, make prediction
36
+ effnetb2.eval()
37
+ with torch.inference_mode():
38
+ pred_probs = torch.softmax(effnetb2(img), dim=1)
39
+
40
+ # Create a prediction label and prediction probability dictionary
41
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
42
+
43
+ # Calculate pred time
44
+ end_time = timer()
45
+ pred_time = round(end_time-start_time, 4)
46
+
47
+ # Return pred dict and pred time
48
+ return pred_labels_and_probs, pred_time
49
+
50
+ ### 4. Gradio app ###
51
+ # Create a title, description, article
52
+ title = "FoodVision Big πŸœπŸ”πŸ₯©"
53
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food into [101 different classes](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/food101_class_names.txt)."
54
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
55
+
56
+ # Create example list
57
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
58
+
59
+ # Create the Gradio demo
60
+ demo = gr.Interface(fn=predict, # maps inputs to outputs
61
+ inputs=gr.Image(type="pil"),
62
+ outputs=[gr.Label(num_top_classes=3, label="Predictions"),
63
+ gr.Number(label="Prediction time (s)")],
64
+ examples=example_list,
65
+ title=title,
66
+ description=description,
67
+ article=article)
68
+
69
+ # Launch the demo!
70
+ demo.launch()