Shriharsh commited on
Commit
07270f5
ยท
1 Parent(s): 985217d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -41
app.py CHANGED
@@ -8,64 +8,78 @@ 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=101)
 
 
 
17
 
18
  # Load saved weights
19
  effnetb2.load_state_dict(
20
- torch.load(f="09_pretrained_effnetb2_feature_extractor_food101.pth",
21
- map_location=torch.device("cpu")) # load to CPU
 
 
22
  )
23
 
24
  ### 3. Predict function ###
25
 
 
26
  def predict(img) -> Tuple[Dict, float]:
27
- # Start a timer
28
- start_time = timer()
 
 
 
 
 
29
 
30
- # Transform the input image for use with EffNetB2
31
- img = effnetb2_transforms(img).unsqueeze(0) # unsqueeze = add batch dimension on 0th index
 
 
 
32
 
33
- # Put model into eval mode, make prediction
34
- effnetb2.eval()
35
- with torch.inference_mode():
36
- # Pass transformed image through the model and turn the prediction logits into probaiblities
37
- pred_probs = torch.softmax(effnetb2(img), dim=1)
38
 
39
- # Create a prediction label and prediction probability dictionary
40
- pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
41
 
42
- # Calculate pred time
43
- end_time = timer()
44
- pred_time = round(end_time - start_time, 4)
45
 
46
- # Return pred dict and pred time
47
- return pred_labels_and_probs, pred_time
48
 
49
  ### 4. Gradio app ###
50
 
51
- # Create title, description and article
52
- title = "FoodVision BIG ๐Ÿ”๐Ÿ‘๐Ÿ’ช"
53
- description = "An [EfficientNetB2 feature extractor]"
54
- #(https://pytorch.org/vision/stable/models/generated/torchvision.models.efficientnet_b2.html#torchvision.models.efficientnet_b2) computer vision model to classify images [101 classes of food from the Food101 dataset](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/food101_class_names.txt)."
55
- #article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/#11-turning-our-foodvision-big-model-into-a-deployable-app)."
56
 
57
- # Create example list
58
  example_list = [["examples/" + example] for example in os.listdir("examples")]
59
 
60
- # Create the Gradio demo
61
- demo = gr.Interface(fn=predict, # maps inputs to outputs
62
- inputs=gr.Image(type="pil"),
63
- outputs=[gr.Label(num_top_classes=5, label="Predictions"),
64
- gr.Number(label="Prediction time (s)")],
65
- examples=example_list,
66
- title=title,
67
- description=description,
68
- article=article)
69
-
70
- # Launch the demo!
71
- demo.launch()
 
 
 
 
 
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 = {
49
+ class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))
50
+ }
 
51
 
52
+ # Calculate the prediction time
53
+ pred_time = round(timer() - start_time, 5)
54
 
55
+ # Return the prediction dictionary and prediction time
56
+ return pred_labels_and_probs, pred_time
 
57
 
 
 
58
 
59
  ### 4. Gradio app ###
60
 
61
+ # Create title, description and article strings
62
+ title = "FoodVision 101 ๐Ÿ”๐Ÿ‘"
63
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food into [101 different classes]"
64
+ #(https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/food101_class_names.txt)."
65
+ #article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
66
 
67
+ # Create examples list from "examples/" directory
68
  example_list = [["examples/" + example] for example in os.listdir("examples")]
69
 
70
+ # Create Gradio interface
71
+ demo = gr.Interface(
72
+ fn=predict,
73
+ inputs=gr.Image(type="pil"),
74
+ outputs=[
75
+ gr.Label(num_top_classes=5, label="Predictions"),
76
+ gr.Number(label="Prediction time (s)"),
77
+ ],
78
+ examples=example_list,
79
+ title=title,
80
+ description=description,
81
+ article=article,
82
+ )
83
+
84
+ # Launch the app!
85
+ demo.launch()