rdkulkarni commited on
Commit
b1e4c54
β€’
1 Parent(s): 940c671

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -0
app.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+
4
+ from model import create_effnetb2_model
5
+ from timeit import default_timer as timer
6
+
7
+ # Setup class names
8
+ with open("class_names.txt", "r") as f:
9
+ class_names = [food_name.strip() for food_name in f.readlines()]
10
+
11
+ # Create model
12
+ model, transforms = create_effnetb2_model(
13
+ num_classes=101,
14
+ )
15
+
16
+ # Load saved weights
17
+ model.load_state_dict(
18
+ torch.load(
19
+ f="09_pretrained_effnetb2_feature_extractor_food101_20_percent.pth",
20
+ map_location=torch.device("cpu"), # load to CPU
21
+ )
22
+ )
23
+
24
+ # Create prediction code
25
+ def predict(img):
26
+ start_time = timer()
27
+ img = transforms(img).unsqueeze(0)
28
+ model.eval()
29
+ with torch.inference_mode():
30
+ pred_probs = torch.softmax(model(img), dim=1)
31
+ pred_labels_and_probs = {
32
+ class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))
33
+ }
34
+ pred_time = round(timer() - start_time, 5)
35
+ return pred_labels_and_probs, pred_time
36
+
37
+
38
+ # Create Gradio app
39
+ title = "FoodVision Big πŸ”πŸ‘"
40
+ description = "An EfficientNetB2 feature extractor computer vision model to classify images of food into 101 different classes."
41
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
42
+
43
+ demo = gr.Interface(
44
+ fn=predict,
45
+ inputs=gr.Image(type="pil"),
46
+ outputs=[
47
+ gr.Label(num_top_classes=5, label="Predictions"),
48
+ gr.Number(label="Prediction time (s)"),
49
+ ],
50
+ examples=[["examples/04-pizza-dad.jpeg"]],
51
+ interpretation="default",
52
+ title=title,
53
+ description=description,
54
+ article=article,
55
+ )
56
+
57
+ demo.launch()