ninjals commited on
Commit
ff9fea8
Β·
verified Β·
1 Parent(s): 66180ab

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +76 -0
app.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # # The 'app.py' file will have four major parts:
2
+ # # 1. Imports and class names setup
3
+ # # 2. Model and transforms preparation
4
+ # # 3. Predict function ('Predict()')
5
+ # # 4. Gradio app - our Gradio interface + launch command
6
+ #
7
+ # # # 1. Imports and class names setup
8
+ import gradio as gr
9
+ import os
10
+ import torch
11
+
12
+ from model import create_vit_model
13
+ from timeit import default_timer as timer
14
+ from typing import Tuple, Dict
15
+ # Setup class names
16
+ class_names = ["pizza", "steak", "sushi"]
17
+
18
+ # # # 2. Model and transforms preparation
19
+ # Create vit model
20
+ vit_b_16, vit_b_16_transforms = create_vit_model(
21
+ num_classes=len(class_names),
22
+ )
23
+ # Load saved weights
24
+ vit_b_16.load_state_dict(
25
+ torch.load(
26
+ f="09_pretrained_vit_b_16_feature_extractor_foodvision_mini_v2.pth",
27
+ map_location=torch.device("cpu"), # load to CPU
28
+ )
29
+ )
30
+ # # # 3. Predict function
31
+ def predict(img) -> Tuple[Dict, float]:
32
+ """
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 = vit_b_16_transforms(img).unsqueeze(0)
40
+
41
+ # Put model into evaluation mode and turn on inference mode
42
+ vit_b_16.eval()
43
+
44
+ with torch.inference_mode():
45
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
46
+ pred_probs = torch.softmax(vit_b_16(img), dim=1)
47
+
48
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
49
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
50
+ # Calculate the prediction time
51
+ pred_time = round(timer() - start_time, 5)
52
+ # Return the prediction dictionary and prediction time
53
+ return pred_labels_and_probs, pred_time
54
+
55
+ # # # 4. Gradio app ###
56
+
57
+ # # # Create title, description and article strings
58
+ title = "FoodVision Mini V2 πŸ•πŸ₯©πŸ£"
59
+ description = "An ViT Base 16 feature extractor computer vision model to classify images of food as pizza, steak or sushi."
60
+ article = "Created at [09. PyTorch Model Deployment](https://www.learnpytorch.io/09_pytorch_model_deployment/)."
61
+
62
+ # Create examples list from "examples"/ directory
63
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
64
+
65
+ # # # Create the Gradio demo
66
+ demo = gr.Interface(fn=predict, # mapping function from input to output
67
+ inputs=gr.Image(type="pil"), # what are the inputs?
68
+ outputs=[gr.Label(num_top_classes=3, label="Predictions"),
69
+ gr.Number(label="Prediction time (s)")], # our fn has two outputs, therefore we have two outputs
70
+ # Create the Gradio demo
71
+ examples=example_list,
72
+ title=title,
73
+ description=description,
74
+ article=article)
75
+ # Launch the demo!
76
+ demo.launch()