ninjals commited on
Commit
100b411
Β·
verified Β·
1 Parent(s): 32acea1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -35
app.py CHANGED
@@ -1,4 +1,4 @@
1
- # 1. Imports and class names setup
2
  import gradio as gr
3
  import os
4
  import torch
@@ -8,59 +8,74 @@ from timeit import default_timer as timer
8
  from typing import Tuple, Dict
9
 
10
  # Setup class names
11
- with open("class_names.txt", "r") as f:
12
- class_names = [food_name.strip() for food_name in f.readlines()]
 
 
13
 
14
- # 2. Model and transforms preparation
15
- # Create model and transforms
16
- effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=len(class_names))
 
17
 
18
  # Load saved weights
19
  effnetb2.load_state_dict(
20
- torch.load(f="09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth",
21
- map_location=torch.device("cpu")) # Load to CPU
 
 
22
  )
23
- # 3. Predict function
 
 
 
24
  def predict(img) -> Tuple[Dict, float]:
25
- # Start a timer
 
 
26
  start_time = timer()
27
- # Transform the input image for use with EffNetB2
28
- img = effnetb2_transforms(img).unsqueeze(0) # unsqueeze = add batch dimension on 0th index
29
- # Put model into eval mode, make prediction
 
 
30
  effnetb2.eval()
31
  with torch.inference_mode():
32
- # Pass transformed image through the model and turn the prediction logits into probability
33
  pred_probs = torch.softmax(effnetb2(img), dim=1)
34
-
35
- # Create a prediction label and prediction probability dictionary
36
  pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
37
-
38
- # Calculate pred time
39
- end_time = timer()
40
- pred_time = round(end_time-start_time, 4)
41
- # Return pred dict and pred time
42
  return pred_labels_and_probs, pred_time
43
 
44
- #4. Gradio app ###
45
 
46
  # Create title, description and article strings
47
- title = "FoodVision BIG πŸ”πŸ‘"
48
- 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)"
49
  article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
50
 
51
  # Create examples list from "examples/" directory
52
  example_list = [["examples/" + example] for example in os.listdir("examples")]
53
 
54
- # Create the Gradio demo
55
- demo = gr.Interface(fn=predict, # mapping function from input to output
56
- inputs=gr.Image(type="pil"), # what are the inputs?
57
- outputs=[gr.Label(num_top_classes=5, label="Predictions"), # what are the outputs?
58
- gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
59
- # Create examples list from "examples/" directory
60
- examples=example_list,
61
- title=title,
62
- description=description,
63
- article=article)
 
 
 
64
 
65
- # Launch the demo!
66
  demo.launch()
 
1
+ ### 1. Imports and class names setup ###
2
  import gradio as gr
3
  import os
4
  import torch
 
8
  from typing import Tuple, Dict
9
 
10
  # Setup class names
11
+ with open("class_names.txt", "r") as f: # reading them in from class_names.txt
12
+ class_names = [food_name.strip() for food_name in f.readlines()]
13
+
14
+ ### 2. Model and transforms preparation ###
15
 
16
+ # Create model
17
+ effnetb2, effnetb2_transforms = create_effnetb2_model(
18
+ num_classes=101, # could also use len(class_names)
19
+ )
20
 
21
  # Load saved weights
22
  effnetb2.load_state_dict(
23
+ torch.load(
24
+ f="09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth",
25
+ map_location=torch.device("cpu"), # load to CPU
26
+ )
27
  )
28
+
29
+ ### 3. Predict function ###
30
+
31
+ # Create predict function
32
  def predict(img) -> Tuple[Dict, float]:
33
+ """Transforms and performs a prediction on img and returns prediction and time taken.
34
+ """
35
+ # Start the timer
36
  start_time = timer()
37
+
38
+ # Transform the target image and add a batch dimension
39
+ img = effnetb2_transforms(img).unsqueeze(0)
40
+
41
+ # Put model into evaluation mode and turn on inference mode
42
  effnetb2.eval()
43
  with torch.inference_mode():
44
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
45
  pred_probs = torch.softmax(effnetb2(img), dim=1)
46
+
47
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
48
  pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
49
+
50
+ # Calculate the prediction time
51
+ pred_time = round(timer() - start_time, 5)
52
+
53
+ # Return the prediction dictionary and prediction time
54
  return pred_labels_and_probs, pred_time
55
 
56
+ ### 4. Gradio app ###
57
 
58
  # Create title, description and article strings
59
+ title = "FoodVision Big πŸ”πŸ‘"
60
+ 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)."
61
  article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
62
 
63
  # Create examples list from "examples/" directory
64
  example_list = [["examples/" + example] for example in os.listdir("examples")]
65
 
66
+ # Create Gradio interface
67
+ demo = gr.Interface(
68
+ fn=predict,
69
+ inputs=gr.Image(type="pil"),
70
+ outputs=[
71
+ gr.Label(num_top_classes=5, label="Predictions"),
72
+ gr.Number(label="Prediction time (s)"),
73
+ ],
74
+ examples=example_list,
75
+ title=title,
76
+ description=description,
77
+ article=article,
78
+ )
79
 
80
+ # Launch the app!
81
  demo.launch()