Spaces:
Sleeping
Sleeping
changes done
Browse files
app.py
CHANGED
|
@@ -1,66 +1,66 @@
|
|
| 1 |
-
### 1. Imports and class names setup ###
|
| 2 |
import gradio as gr
|
| 3 |
import os
|
| 4 |
import torch
|
|
|
|
|
|
|
| 5 |
|
| 6 |
from model import create_vit_model
|
| 7 |
from timeit import default_timer as timer
|
| 8 |
from typing import Tuple, Dict
|
|
|
|
|
|
|
| 9 |
class_names = ["apple_pie", "baby_back_ribs", "baklava", "beef_carpaccio", "beef_tartare", "beet_salad", "beignets", "bibimbap", "biryani", "bread_pudding", "breakfast_burrito", "bruschetta", "caesar_salad", "cannoli", "caprese_salad", "carrot_cake", "ceviche", "chai", "chapati", "cheese_plate", "cheesecake", "chicken_curry", "chicken_quesadilla", "chicken_wings", "chocolate_cake", "chocolate_mousse", "chole_bhature", "churros", "clam_chowder", "club_sandwich", "crab_cakes", "creme_brulee", "croque_madame", "cup_cakes", "dabeli", "dal", "deviled_eggs", "dhokla", "donuts", "dosa", "dumplings", "edamame", "eggs_benedict", "escargots", "falafel", "filet_mignon", "fish_and_chips", "foie_gras", "french_fries", "french_onion_soup", "french_toast", "fried_calamari", "fried_rice", "frozen_yogurt", "garlic_bread", "gnocchi", "greek_salad", "grilled_cheese_sandwich", "grilled_salmon", "guacamole", "gyoza", "hamburger", "hot_and_sour_soup", "hot_dog", "huevos_rancheros", "hummus", "ice_cream", "idli", "jalebi", "kathi_rolls", "kofta", "kulfi", "lasagna", "lobster_bisque", "lobster_roll_sandwich", "macaroni_and_cheese", "macarons", "miso_soup", "momos", "mussels", "naan", "nachos", "omelette", "onion_rings", "oysters", "pad_thai", "paella", "pakoda", "pancakes", "pani_puri", "panna_cotta", "panner_butter_masala", "pav_bhaji", "peking_duck", "pho", "pizza", "pork_chop", "poutine", "prime_rib", "pulled_pork_sandwich", "ramen", "ravioli", "red_velvet_cake", "risotto", "samosa", "sashimi", "scallops", "seaweed_salad", "shrimp_and_grits", "spaghetti_bolognese", "spaghetti_carbonara", "spring_rolls", "steak", "strawberry_shortcake", "sushi", "tacos", "takoyaki", "tiramisu", "tuna_tartare", "vadapav", "waffles"]
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
)
|
| 13 |
-
vit.load_state_dict(
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
map_location=torch.device("cpu"), # load to CPU
|
| 17 |
-
)
|
| 18 |
-
)
|
| 19 |
-
# Create predict function
|
| 20 |
def predict(img) -> Tuple[Dict, float]:
|
| 21 |
-
"""Transforms and performs a prediction on img and returns prediction and time taken.
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
# Start the timer
|
| 24 |
start_time = timer()
|
| 25 |
-
|
| 26 |
-
# Transform
|
| 27 |
-
img = vit_transforms(img).unsqueeze(0)
|
| 28 |
-
|
| 29 |
-
# Put model into evaluation mode and turn on inference mode
|
| 30 |
vit.eval()
|
| 31 |
with torch.inference_mode():
|
| 32 |
-
# Pass the transformed image through the model and turn the prediction logits into prediction probabilities
|
| 33 |
pred_probs = torch.softmax(vit(img), dim=1)
|
| 34 |
-
|
| 35 |
-
#
|
| 36 |
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
|
| 37 |
-
|
| 38 |
-
# Calculate the prediction time
|
| 39 |
pred_time = round(timer() - start_time, 5)
|
| 40 |
-
|
| 41 |
-
# Return the prediction dictionary and prediction time
|
| 42 |
return pred_labels_and_probs, pred_time
|
| 43 |
|
| 44 |
### 4. Gradio app ###
|
| 45 |
|
| 46 |
-
#
|
| 47 |
title = "VisionBite ππ₯©π£"
|
| 48 |
description = "A Vision Transformer (ViT-Base-16) model trained to classify images of food into 121 distinct categories. The model uses a transformer-based architecture to extract visual features and achieve accurate classification across diverse food items."
|
| 49 |
-
article = "Model has been trained on Food121 dataset
|
| 50 |
|
| 51 |
# Create examples list from "examples/" directory
|
| 52 |
-
example_list = [["examples/" + example] for example in os.listdir("examples")]
|
| 53 |
|
| 54 |
-
#
|
| 55 |
-
demo = gr.Interface(
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
-
# Launch
|
| 66 |
demo.launch()
|
|
|
|
| 1 |
+
### 1. Imports and class names setup ###
|
| 2 |
import gradio as gr
|
| 3 |
import os
|
| 4 |
import torch
|
| 5 |
+
import numpy as np
|
| 6 |
+
from PIL import Image
|
| 7 |
|
| 8 |
from model import create_vit_model
|
| 9 |
from timeit import default_timer as timer
|
| 10 |
from typing import Tuple, Dict
|
| 11 |
+
|
| 12 |
+
# List of 121 food classes
|
| 13 |
class_names = ["apple_pie", "baby_back_ribs", "baklava", "beef_carpaccio", "beef_tartare", "beet_salad", "beignets", "bibimbap", "biryani", "bread_pudding", "breakfast_burrito", "bruschetta", "caesar_salad", "cannoli", "caprese_salad", "carrot_cake", "ceviche", "chai", "chapati", "cheese_plate", "cheesecake", "chicken_curry", "chicken_quesadilla", "chicken_wings", "chocolate_cake", "chocolate_mousse", "chole_bhature", "churros", "clam_chowder", "club_sandwich", "crab_cakes", "creme_brulee", "croque_madame", "cup_cakes", "dabeli", "dal", "deviled_eggs", "dhokla", "donuts", "dosa", "dumplings", "edamame", "eggs_benedict", "escargots", "falafel", "filet_mignon", "fish_and_chips", "foie_gras", "french_fries", "french_onion_soup", "french_toast", "fried_calamari", "fried_rice", "frozen_yogurt", "garlic_bread", "gnocchi", "greek_salad", "grilled_cheese_sandwich", "grilled_salmon", "guacamole", "gyoza", "hamburger", "hot_and_sour_soup", "hot_dog", "huevos_rancheros", "hummus", "ice_cream", "idli", "jalebi", "kathi_rolls", "kofta", "kulfi", "lasagna", "lobster_bisque", "lobster_roll_sandwich", "macaroni_and_cheese", "macarons", "miso_soup", "momos", "mussels", "naan", "nachos", "omelette", "onion_rings", "oysters", "pad_thai", "paella", "pakoda", "pancakes", "pani_puri", "panna_cotta", "panner_butter_masala", "pav_bhaji", "peking_duck", "pho", "pizza", "pork_chop", "poutine", "prime_rib", "pulled_pork_sandwich", "ramen", "ravioli", "red_velvet_cake", "risotto", "samosa", "sashimi", "scallops", "seaweed_salad", "shrimp_and_grits", "spaghetti_bolognese", "spaghetti_carbonara", "spring_rolls", "steak", "strawberry_shortcake", "sushi", "tacos", "takoyaki", "tiramisu", "tuna_tartare", "vadapav", "waffles"]
|
| 14 |
+
|
| 15 |
+
# Load model and transforms
|
| 16 |
+
vit, vit_transforms = create_vit_model(num_classes=121)
|
| 17 |
+
vit.load_state_dict(torch.load("vit_epoch_2.pth", map_location=torch.device("cpu")))
|
| 18 |
+
|
| 19 |
+
# Predict function
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
def predict(img) -> Tuple[Dict, float]:
|
| 21 |
+
"""Transforms and performs a prediction on img and returns prediction and time taken."""
|
| 22 |
+
# Ensure image is PIL
|
| 23 |
+
if isinstance(img, np.ndarray):
|
| 24 |
+
img = Image.fromarray(img)
|
| 25 |
+
|
| 26 |
# Start the timer
|
| 27 |
start_time = timer()
|
| 28 |
+
|
| 29 |
+
# Transform and predict
|
| 30 |
+
img = vit_transforms(img).unsqueeze(0) # Add batch dimension
|
|
|
|
|
|
|
| 31 |
vit.eval()
|
| 32 |
with torch.inference_mode():
|
|
|
|
| 33 |
pred_probs = torch.softmax(vit(img), dim=1)
|
| 34 |
+
|
| 35 |
+
# Get label:probability dictionary
|
| 36 |
pred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}
|
|
|
|
|
|
|
| 37 |
pred_time = round(timer() - start_time, 5)
|
| 38 |
+
|
|
|
|
| 39 |
return pred_labels_and_probs, pred_time
|
| 40 |
|
| 41 |
### 4. Gradio app ###
|
| 42 |
|
| 43 |
+
# App metadata
|
| 44 |
title = "VisionBite ππ₯©π£"
|
| 45 |
description = "A Vision Transformer (ViT-Base-16) model trained to classify images of food into 121 distinct categories. The model uses a transformer-based architecture to extract visual features and achieve accurate classification across diverse food items."
|
| 46 |
+
article = "Model has been trained on the [Food121 dataset](https://huggingface.co/datasets/ItsNotRohit/Food121) and achieves ~95% Top-5 accuracy."
|
| 47 |
|
| 48 |
# Create examples list from "examples/" directory
|
| 49 |
+
example_list = [["examples/" + example] for example in os.listdir("examples") if example.lower().endswith(('.jpg', '.jpeg', '.png'))]
|
| 50 |
|
| 51 |
+
# Gradio demo
|
| 52 |
+
demo = gr.Interface(
|
| 53 |
+
fn=predict,
|
| 54 |
+
inputs=gr.Image(type="pil"),
|
| 55 |
+
outputs=[
|
| 56 |
+
gr.Label(num_top_classes=5, label="Top-5 Predictions"),
|
| 57 |
+
gr.Number(label="Prediction time (s)")
|
| 58 |
+
],
|
| 59 |
+
examples=example_list,
|
| 60 |
+
title=title,
|
| 61 |
+
description=description,
|
| 62 |
+
article=article
|
| 63 |
+
)
|
| 64 |
|
| 65 |
+
# Launch app
|
| 66 |
demo.launch()
|