noelsinghsr commited on
Commit
76dfc1a
1 Parent(s): 2594d09

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 # this will create our feature extractor
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
+ # Create model and transforms
17
+ effnetb2, effnetb2_transforms = create_effnetb2_model(num_classes=101)
18
+
19
+ # Load the saved weights
20
+ effnetb2.load_state_dict(
21
+ torch.load(f="09_pretrained_effnetb2_feature_extractor_food101_20pct.pth",
22
+ map_location=torch.device("cpu")) # it's important to map to cpu if trained on gpu or it will default to gpu
23
+ )
24
+
25
+ ### 3. Predict function ###
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 to add batch dimension
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 probabilities
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 = "Test ML title"
53
+ description = "this is a test description"
54
+ article = "this is a test article"
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=5, 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()