sergio-sanz-rodriguez commited on
Commit
c781e06
·
1 Parent(s): bd09324

First upload of the app

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ vitbase16_5.pth filter=lfs diff=lfs merge=lfs -text
app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # 1. Imports and class names setup
3
+ import os
4
+ import torch
5
+ import gradio as gr
6
+ from model import create_vit_base_model
7
+ from timeit import default_timer as timer
8
+ from typing import Tuple, Dict
9
+ from torchvision import transforms as v2
10
+
11
+
12
+ # 2. Specify class names
13
+ with open(food_vision_class_names_path, "r") as f:
14
+ class_names = f.read().splitlines()
15
+
16
+
17
+ # 3. Load the food description file
18
+ with open(food_descriptions_json, 'r') as f:
19
+ food_descriptions = json.load(f)
20
+
21
+ # 4. Load the ViT-Base transformer
22
+ vitbase_model_name = "vitbase16_3.pth"
23
+ IMG_SIZE = 224
24
+ num_classes = len(class_names)
25
+ vitbase_model = create_vitbase_model(
26
+ model_weights_dir=food_vision_model_path,
27
+ model_weights_name=vitbase_model_name,
28
+ img_size=IMG_SIZE,
29
+ num_classes=num_classes
30
+ )
31
+
32
+ # 5. Specify manual transforms
33
+ transforms = v2.Compose([
34
+ v2.Resize((256, 256)),
35
+ v2.RandomCrop((IMG_SIZE, IMG_SIZE)),
36
+ v2.ToImage(),
37
+ v2.ToDtype(torch.float32, scale=True),
38
+ v2.Normalize(mean=[0.485, 0.456, 0.406],
39
+ std=[0.229, 0.224, 0.225])
40
+ ])
41
+
42
+ # 6. Predict function
43
+ def predict(img) -> Tuple[Dict, float]:
44
+ """Transforms and performs a prediction on img and returns prediction and time taken.
45
+ """
46
+ # Start the timer
47
+ start_time = timer()
48
+
49
+ # Transform the target image and add a batch dimension
50
+ img = transforms(img).unsqueeze(0)
51
+
52
+ # Put model into evaluation mode and turn on inference mode
53
+ vitbase_model.eval()
54
+ with torch.inference_mode():
55
+
56
+ # Pass the transformed image through the model and turn the prediction logits into prediction probabilities
57
+ pred_probs = torch.softmax(vitbase_model(img), dim=1)
58
+
59
+ # Create a prediction label and prediction probability dictionary for each prediction class
60
+ # (this is the required format for Gradio's output parameter)
61
+ pred_classes_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
62
+
63
+ # Get the top predicted class and its description
64
+ top_class = max(pred_classes_and_probs, key=pred_classes_and_probs.get)
65
+ #top_class_description = food_descriptions[top_class]
66
+ top_class_description = food_descriptions.get(top_class, "Description not available.")
67
+
68
+ # Calculate the prediction time
69
+ pred_time = round(timer() - start_time, 5)
70
+
71
+ # Return the prediction dictionary and prediction time
72
+ return pred_classes_and_probs, pred_time, top_class_description
73
+
74
+ # 7. Configure and design the Gradio App
75
+ # Create title, description, and examples
76
+ title = "TransformEats 101 🥪🥗🥩"
77
+ description = f"""
78
+ A cutting-edge Vision Transformer (ViT) model to classify 101 delicious food types. Discover the power of AI in culinary recognition.
79
+
80
+ ### Supported Food Types
81
+ {', '.join(class_names)}.
82
+ """
83
+
84
+ article = "Created by Sergio Sanz."
85
+
86
+
87
+ # Create the Gradio demo
88
+ demo = gr.Interface(fn=predict, # mapping function from input to outputs
89
+ inputs=gr.Image(type="pil"), # input
90
+ outputs=[gr.Label(num_top_classes=3, label="Predictions"), # outputs
91
+ gr.Number(label="Prediction time (s)"),
92
+ gr.Textbox(label="Food Description")],
93
+ examples=food_vision_examples, # Create examples list from "examples/" directory
94
+ title=title, # Title of the app
95
+ description=description, # Brief description of the app
96
+ article=article, # Created by...
97
+ theme="citrus") # Theme
98
+
99
+ # Launch the demo!
100
+ 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
examples/1134579.jpg ADDED
examples/2083247.jpg ADDED
examples/3770514.jpg ADDED
examples/470617.jpg ADDED
examples/511665.jpg ADDED
food_descriptions.json ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "apple_pie": "A classic American dessert made with spiced apple filling encased in a flaky pastry crust, often served with ice cream.",
3
+ "baby_back_ribs": "Juicy, tender pork ribs, slow-cooked and coated with a flavorful barbecue sauce.",
4
+ "baklava": "A rich, sweet pastry layered with chopped nuts and honey or syrup, originating from the Middle East and Mediterranean regions.",
5
+ "beef_carpaccio": "Thinly sliced raw beef served with olive oil, lemon, capers, and Parmesan, often as a starter.",
6
+ "beef_tartare": "Finely chopped or ground raw beef mixed with seasonings like capers, onions, and egg yolk, served uncooked.",
7
+ "beet_salad": "A refreshing dish featuring cooked or raw beets paired with greens, goat cheese, nuts, and a tangy vinaigrette.",
8
+ "beignets": "Deep-fried dough pastries dusted with powdered sugar, popular in New Orleans as a sweet treat.",
9
+ "bibimbap": "A Korean mixed rice dish topped with vegetables, meat, an egg, and spicy gochujang sauce.",
10
+ "bread_pudding": "A comforting dessert made from bread soaked in a sweet custard mixture and baked until golden.",
11
+ "breakfast_burrito": "A hearty wrap filled with scrambled eggs, cheese, meats, and sometimes vegetables or beans.",
12
+ "bruschetta": "An Italian appetizer of toasted bread rubbed with garlic and topped with fresh tomatoes, olive oil, and basil.",
13
+ "caesar_salad": "A classic salad made with romaine lettuce, croutons, Parmesan cheese, and Caesar dressing.",
14
+ "cannoli": "An Italian dessert consisting of a crispy pastry shell filled with sweet ricotta cheese and sometimes chocolate chips.",
15
+ "caprese_salad": "A simple Italian salad of fresh mozzarella, tomatoes, and basil, drizzled with olive oil and balsamic vinegar.",
16
+ "carrot_cake": "A moist cake made with grated carrots and often topped with cream cheese frosting.",
17
+ "ceviche": "A seafood dish where fresh fish or shrimp is 'cooked' in citrus juice and mixed with onions, peppers, and cilantro.",
18
+ "cheese_plate": "An assortment of cheeses served with accompaniments like crackers, fruit, and nuts.",
19
+ "cheesecake": "A creamy dessert made with a mixture of cream cheese, sugar, and eggs on a graham cracker or pastry crust.",
20
+ "chicken_curry": "A flavorful dish of chicken cooked in a spicy, aromatic curry sauce, popular in South Asian cuisine.",
21
+ "chicken_quesadilla": "A Mexican dish of tortillas filled with cheese, chicken, and spices, grilled until crispy and melty.",
22
+ "chicken_wings": "Juicy chicken wings fried or baked and often coated with a tangy or spicy sauce.",
23
+ "chocolate_cake": "A rich, moist dessert made with layers of chocolate sponge and frosting.",
24
+ "chocolate_mousse": "A light and creamy dessert made with whipped cream and melted chocolate, often served chilled.",
25
+ "churros": "Fried dough pastry, often coated in sugar and cinnamon, typically served with chocolate dipping sauce.",
26
+ "clam_chowder": "A creamy soup made with clams, potatoes, and onions, often served in a bread bowl.",
27
+ "club_sandwich": "A layered sandwich filled with turkey, bacon, lettuce, tomato, and mayonnaise.",
28
+ "crab_cakes": "Pan-fried or baked patties made from lump crab meat and breadcrumbs, seasoned with spices.",
29
+ "creme_brulee": "A custard dessert with a caramelized sugar crust on top, served cold.",
30
+ "croque_madame": "A French grilled sandwich filled with ham and cheese, topped with a fried egg.",
31
+ "cup_cakes": "Small, individual-sized cakes often topped with frosting and decorations.",
32
+ "deviled_eggs": "Hard-boiled eggs halved and filled with a seasoned yolk mixture.",
33
+ "donuts": "Sweet, fried dough pastries, often glazed or topped with sprinkles.",
34
+ "dumplings": "Small dough parcels filled with meat or vegetables, steamed, boiled, or fried.",
35
+ "edamame": "Boiled or steamed young soybeans served in their pods, sprinkled with salt.",
36
+ "eggs_benedict": "A breakfast dish of poached eggs, English muffins, Canadian bacon, and hollandaise sauce.",
37
+ "escargots": "Cooked snails, often served with garlic butter in French cuisine.",
38
+ "falafel": "Deep-fried balls or patties made from ground chickpeas or fava beans, often served in pita bread.",
39
+ "filet_mignon": "A tender and juicy cut of beef steak, often served as a fine dining dish.",
40
+ "fish_and_chips": "A classic British dish of battered and fried fish served with crispy fries.",
41
+ "foie_gras": "A French delicacy made from the liver of a fattened duck or goose, often served as a p\u00e2t\u00e9.",
42
+ "french_fries": "Thinly sliced potatoes deep-fried until crispy, often served as a side dish.",
43
+ "french_onion_soup": "A hearty soup made with caramelized onions and beef broth, topped with bread and melted cheese.",
44
+ "french_toast": "Bread slices soaked in a milk and egg mixture, fried until golden, and served with syrup.",
45
+ "fried_calamari": "Lightly battered and fried squid rings, often served with marinara or aioli sauce.",
46
+ "fried_rice": "A stir-fried rice dish mixed with vegetables, eggs, and meat or seafood.",
47
+ "frozen_yogurt": "A creamy, tangy dessert similar to ice cream but made with yogurt.",
48
+ "garlic_bread": "Toasted bread slices flavored with garlic butter, often served as a side dish.",
49
+ "gnocchi": "Soft Italian dumplings made from potato, flour, and sometimes cheese, served with sauce.",
50
+ "greek_salad": "A fresh salad made with cucumbers, tomatoes, olives, feta cheese, and olive oil.",
51
+ "grilled_cheese_sandwich": "A hot sandwich filled with melted cheese, grilled until crispy.",
52
+ "grilled_salmon": "Salmon fillets cooked on a grill, often seasoned with herbs and spices.",
53
+ "guacamole": "A creamy dip made from mashed avocados, lime juice, onions, and cilantro.",
54
+ "gyoza": "Japanese dumplings filled with minced meat and vegetables, pan-fried and steamed.",
55
+ "hamburger": "A ground beef patty served in a bun with toppings like lettuce, tomato, and cheese.",
56
+ "hot_and_sour_soup": "A Chinese soup with a tangy and spicy flavor, filled with tofu, mushrooms, and vegetables.",
57
+ "hot_dog": "A grilled or boiled sausage served in a bun with condiments like ketchup and mustard.",
58
+ "huevos_rancheros": "A Mexican breakfast dish with fried eggs, tortillas, and salsa.",
59
+ "hummus": "A creamy dip made from blended chickpeas, tahini, lemon juice, and garlic.",
60
+ "ice_cream": "A frozen dessert made from sweetened cream, often flavored and served in scoops.",
61
+ "lasagna": "An Italian pasta dish layered with meat, cheese, and tomato sauce, baked until bubbly.",
62
+ "lobster_bisque": "A creamy soup made from lobster stock, often served as a gourmet dish.",
63
+ "lobster_roll_sandwich": "A sandwich filled with chunks of lobster meat, dressed in butter or mayo.",
64
+ "macaroni_and_cheese": "A comfort food dish of macaroni pasta mixed with a creamy cheese sauce.",
65
+ "macarons": "Delicate French almond cookies filled with flavored buttercream or ganache.",
66
+ "miso_soup": "A Japanese soup made with fermented soybean paste, tofu, and seaweed.",
67
+ "mussels": "Shellfish steamed and served in a flavorful broth, often with bread.",
68
+ "nachos": "Tortilla chips topped with melted cheese and various toppings like jalape\u00f1os and sour cream.",
69
+ "omelette": "Beaten eggs cooked in a frying pan, often filled with cheese, meats, or vegetables.",
70
+ "onion_rings": "Crispy, deep-fried onion slices, often served as a side dish or snack.",
71
+ "oysters": "Shellfish often served raw on the half shell with lemon or hot sauce.",
72
+ "pad_thai": "Stir-fried rice noodles with eggs, tofu or shrimp, peanuts, and a tamarind-based sauce.",
73
+ "paella": "Spanish rice dish with seafood, meats, and saffron, traditionally cooked in a single pan.",
74
+ "pancakes": "Fluffy round cakes made from flour, eggs, and milk, served with syrup and butter.",
75
+ "panna_cotta": "Italian dessert of sweetened cream thickened with gelatin, often topped with berries or caramel.",
76
+ "peking_duck": "Crispy duck served with pancakes, hoisin sauce, and sliced scallions.",
77
+ "pho": "Vietnamese noodle soup with broth, rice noodles, herbs, and beef or chicken.",
78
+ "pizza": "Flat dough topped with tomato sauce, cheese, and various toppings, baked until crispy.",
79
+ "pork_chop": "Grilled or roasted cut of pork, often served with vegetables or a flavorful sauce.",
80
+ "poutine": "Canadian dish with French fries, cheese curds, and gravy.",
81
+ "prime_rib": "Tender beef rib roast, often seasoned and slow-cooked, served for special occasions.",
82
+ "pulled_pork_sandwich": "Slow-cooked shredded pork with barbecue sauce, served on a bun.",
83
+ "ramen": "Japanese noodle soup with broth, wheat noodles, and toppings like eggs and pork.",
84
+ "ravioli": "Italian dumplings filled with cheese, meat, or vegetables, served with sauce.",
85
+ "red_velvet_cake": "Rich cake with a hint of cocoa and red coloring, layered with cream cheese frosting.",
86
+ "risotto": "Italian creamy rice dish cooked with broth and flavored with vegetables or meat.",
87
+ "samosa": "Deep-fried pastry filled with spiced potatoes, peas, and sometimes meat.",
88
+ "sashimi": "Thinly sliced raw fish or seafood, often served with soy sauce and wasabi.",
89
+ "scallops": "Delicate shellfish, often seared and served as a seafood entr\u00e9e.",
90
+ "seaweed_salad": "Salad made from seasoned edible seaweed, typically with sesame oil and soy sauce.",
91
+ "shrimp_and_grits": "Southern dish of shrimp cooked in a savory sauce, served with creamy grits.",
92
+ "spaghetti_bolognese": "Italian pasta with a rich meat sauce made from ground beef, tomatoes, and herbs.",
93
+ "spaghetti_carbonara": "Pasta with a creamy sauce made from eggs, cheese, pancetta, and black pepper.",
94
+ "spring_rolls": "Rice paper rolls filled with vegetables, meat, or seafood, served with dipping sauce.",
95
+ "steak": "Grilled or pan-seared beef cut, often served with vegetables or potatoes.",
96
+ "strawberry_shortcake": "Dessert with layers of cake, fresh strawberries, and whipped cream.",
97
+ "sushi": "Japanese dish with vinegared rice, raw or cooked seafood, and sometimes vegetables.",
98
+ "tacos": "Mexican dish with a tortilla filled with meat, vegetables, cheese, and salsa.",
99
+ "takoyaki": "Japanese snack made from batter, octopus, and tempura bits, served with takoyaki sauce.",
100
+ "tiramisu": "Italian dessert with coffee-soaked ladyfingers, mascarpone cheese, and cocoa powder.",
101
+ "tuna_tartare": "Finely diced raw tuna, often mixed with soy sauce and served as an appetizer.",
102
+ "waffles": "Batter-based dish cooked in a grid pattern, served with syrup, fruit, or whipped cream."
103
+ }
model.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+ from torch import nn
4
+ from vision_transformer import ViT
5
+ from helper_functions import load_model
6
+ from torchvision.transforms import v2
7
+
8
+ def create_vitbase_model(
9
+ model_weights_dir:Path,
10
+ model_weights_name:str,
11
+ img_size:int=224,
12
+ num_classes:int=101
13
+ ):
14
+
15
+ # Instantiate the model
16
+ vitbase16_model = ViT(
17
+ img_size=img_size,
18
+ in_channels=3,
19
+ patch_size=16,
20
+ num_transformer_layers=12,
21
+ emb_dim=768,
22
+ mlp_size=3072,
23
+ num_heads=12,
24
+ attn_dropout=0,
25
+ mlp_dropout=0.1,
26
+ emb_dropout=0.1,
27
+ num_classes=num_classes
28
+ )
29
+
30
+ # Load the trained weights
31
+ vitbase16_model = load_model(
32
+ model=vitbase16_model,
33
+ model_weights_dir=model_weights_dir,
34
+ model_weights_name=model_weights_name
35
+ )
36
+
37
+ return vitbase16_model
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ torch==2.5.0
2
+ torchvision==0.20.0
3
+ gradio==5.7.1