carlosabadia commited on
Commit
57a938e
·
1 Parent(s): 087a267

Upload 5 files

Browse files
Files changed (5) hide show
  1. app.py +83 -0
  2. class_names.txt +101 -0
  3. model.py +34 -0
  4. model_food101_20_percent.pth +3 -0
  5. requirements.txt +3 -0
app.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Imports and class names setup ###
2
+ import gradio as gr
3
+ import os
4
+ import torch
5
+
6
+ from model import create_vit16_model
7
+ 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: # 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
+ vit16, vit16_transforms = create_vit16_model(
18
+ num_classes=101, # could also use len(class_names)
19
+ )
20
+
21
+
22
+ vit16.load_state_dict(
23
+ torch.load(
24
+ f="model_food101_20_percent.pth",
25
+ map_location=torch.device("cpu"), # load to CPU
26
+ )
27
+ )
28
+
29
+
30
+
31
+ ### 3. Predict function ###
32
+
33
+ # Create predict function
34
+ def predict(img) -> Tuple[Dict, float]:
35
+ """Transforms and performs a prediction on img and returns prediction and time taken.
36
+ """
37
+ # Start the timer
38
+ start_time = timer()
39
+
40
+ # Transform the target image and add a batch dimension
41
+ img = vit16_transforms(img).unsqueeze(0)
42
+
43
+ # Put model into evaluation mode and turn on inference mode
44
+ vit16.eval()
45
+ with torch.inference_mode():
46
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
47
+ pred_probs = torch.softmax(vit16(img), dim=1)
48
+
49
+ # Create a prediction label and prediction probability dictionary for each prediction class (this is the required format for Gradio's output parameter)
50
+ pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
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
+ ### 4. Gradio app ###
59
+
60
+ # Create title, description and article strings
61
+ title = "FoodVision ViT 🍔👁"
62
+ description = "A ViT_B_16 feature extractor computer vision model to classify images of food into 101 different classes using 20% of the data."
63
+ article = ""
64
+
65
+ # Create examples list from "examples/" directory
66
+ example_list = [["examples/" + example] for example in os.listdir("examples")]
67
+
68
+ # Create Gradio interface
69
+ demo = gr.Interface(
70
+ fn=predict,
71
+ inputs=gr.Image(type="pil"),
72
+ outputs=[
73
+ gr.Label(num_top_classes=5, label="Predictions"),
74
+ gr.Number(label="Prediction time (s)"),
75
+ ],
76
+ examples=example_list,
77
+ title=title,
78
+ description=description,
79
+ article=article,
80
+ )
81
+
82
+ # Launch the app!
83
+ demo.launch()
class_names.txt ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ apple_pie
2
+ baby_back_ribs
3
+ baklava
4
+ beef_carpaccio
5
+ beef_tartare
6
+ beet_salad
7
+ beignets
8
+ bibimbap
9
+ bread_pudding
10
+ breakfast_burrito
11
+ bruschetta
12
+ caesar_salad
13
+ cannoli
14
+ caprese_salad
15
+ carrot_cake
16
+ ceviche
17
+ cheese_plate
18
+ cheesecake
19
+ chicken_curry
20
+ chicken_quesadilla
21
+ chicken_wings
22
+ chocolate_cake
23
+ chocolate_mousse
24
+ churros
25
+ clam_chowder
26
+ club_sandwich
27
+ crab_cakes
28
+ creme_brulee
29
+ croque_madame
30
+ cup_cakes
31
+ deviled_eggs
32
+ donuts
33
+ dumplings
34
+ edamame
35
+ eggs_benedict
36
+ escargots
37
+ falafel
38
+ filet_mignon
39
+ fish_and_chips
40
+ foie_gras
41
+ french_fries
42
+ french_onion_soup
43
+ french_toast
44
+ fried_calamari
45
+ fried_rice
46
+ frozen_yogurt
47
+ garlic_bread
48
+ gnocchi
49
+ greek_salad
50
+ grilled_cheese_sandwich
51
+ grilled_salmon
52
+ guacamole
53
+ gyoza
54
+ hamburger
55
+ hot_and_sour_soup
56
+ hot_dog
57
+ huevos_rancheros
58
+ hummus
59
+ ice_cream
60
+ lasagna
61
+ lobster_bisque
62
+ lobster_roll_sandwich
63
+ macaroni_and_cheese
64
+ macarons
65
+ miso_soup
66
+ mussels
67
+ nachos
68
+ omelette
69
+ onion_rings
70
+ oysters
71
+ pad_thai
72
+ paella
73
+ pancakes
74
+ panna_cotta
75
+ peking_duck
76
+ pho
77
+ pizza
78
+ pork_chop
79
+ poutine
80
+ prime_rib
81
+ pulled_pork_sandwich
82
+ ramen
83
+ ravioli
84
+ red_velvet_cake
85
+ risotto
86
+ samosa
87
+ sashimi
88
+ scallops
89
+ seaweed_salad
90
+ shrimp_and_grits
91
+ spaghetti_bolognese
92
+ spaghetti_carbonara
93
+ spring_rolls
94
+ steak
95
+ strawberry_shortcake
96
+ sushi
97
+ tacos
98
+ takoyaki
99
+ tiramisu
100
+ tuna_tartare
101
+ waffles
model.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+
4
+ from torch import nn
5
+
6
+
7
+ def create_vit16_model(num_classes:int=101,
8
+ seed:int=42):
9
+ """Creates an vit16 feature extractor model and transforms.
10
+
11
+ Args:
12
+ num_classes (int, optional): number of classes in the classifier head.
13
+ Defaults to 3.
14
+ seed (int, optional): random seed value. Defaults to 42.
15
+
16
+ Returns:
17
+ model (torch.nn.Module): vit feature extractor model.
18
+ transforms (torchvision.transforms): vit image transforms.
19
+ """
20
+ # Create vit pretrained weights, transforms and model
21
+ weights = torchvision.models.ViT_B_16_Weights.DEFAULT;
22
+ transforms = weights.transforms()
23
+ model = torchvision.models.vit_b_16(weights=weights)
24
+
25
+ # Freeze all layers in base model
26
+ for param in model.parameters():
27
+ param.requires_grad = False
28
+
29
+ # Change classifier head with random seed for reproducibility
30
+ torch.manual_seed(seed)
31
+ model.heads = nn.Sequential(nn.Linear(in_features=768, # keep this the same as original model
32
+ out_features=num_classes)) # update to reflect target number of classes
33
+
34
+ return model, transforms
model_food101_20_percent.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4357a334ed5737baacaf7a99b0ba491ef88c61580790277acec9ef877cd77c9
3
+ size 343564561
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==1.12.1
2
+ torchvision==0.13.1
3
+ gradio==3.1.4