Spaces:
Build error
Build error
changes
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182### 1. Imports and class names setup ###import gradio as grimport osimport torchimport numpy as npfrom PIL import Image, UnidentifiedImageErrorfrom model import create_vit_modelfrom timeit import default_timer as timerfrom typing import Tuple, Dict# List of 121 food classesclass_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"]# Load model and transformsvit, vit_transforms = create_vit_model(num_classes=121)vit.load_state_dict(torch.load("vit_epoch_2.pth", map_location=torch.device("cpu")))# Predict functiondef predict(img) -> Tuple[Dict, float]:"""Transforms and performs a prediction on img and returns prediction and time taken."""try:# Ensure image is PILif isinstance(img, np.ndarray):img = Image.fromarray(img)img = img.convert("RGB") # ensure it's 3-channel# Start the timerstart_time = timer()# Transform and predictimg = vit_transforms(img).unsqueeze(0) # Add batch dimensionvit.eval()with torch.inference_mode():pred_probs = torch.softmax(vit(img), dim=1)# Get label:probability dictionarypred_labels_and_probs = {class_names[i]: float(pred_probs[0][i]) for i in range(len(class_names))}pred_time = round(timer() - start_time, 5)return pred_labels_and_probs, pred_timeexcept Exception as e:raise RuntimeError("Failed to transform image. Possibly corrupted or unsupported format.") from e### 4. Gradio app #### App metadatatitle = "VisionBite ππ₯©π£"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."article = "Model has been trained on the [Food121 dataset](https://huggingface.co/datasets/ItsNotRohit/Food121) and achieves ~95% Top-5 accuracy."# Load examples with error handlingexample_list = []for filename in os.listdir("examples"):if filename.lower().endswith(('.jpg', '.jpeg', '.png')):try:img_path = os.path.join("examples", filename)with Image.open(img_path) as img:img.convert("RGB")example_list.append([img_path])except (UnidentifiedImageError, OSError):print(f"β Skipping corrupted or unreadable image: {filename}")# Gradio demodemo = gr.Interface(fn=predict,inputs=gr.Image(type="pil"),outputs=[gr.Label(num_top_classes=5, label="Top-5 Predictions"),gr.Number(label="Prediction time (s)")],examples=example_list,title=title,description=description,article=article,cache_examples=False # avoid caching startup crash)# Launch appdemo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990### 1. Imports and Setup ###import gradio as grimport osimport torchimport numpy as npfrom PIL import Imagefrom timeit import default_timer as timerfrom typing import Tuple, Dictfrom model import create_vit_model# Load class namesclass_names = [ # 121 classes"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"]# Load model and transformsvit, vit_transforms = create_vit_model(num_classes=121)vit.load_state_dict(torch.load("vit_epoch_2.pth", map_location=torch.device("cpu")))vit.eval()# Prediction functiondef predict(image: Image.Image) -> Tuple[Dict[str, float], float]:try:if isinstance(image, np.ndarray):image = Image.fromarray(image)start_time = timer()image = vit_transforms(image).unsqueeze(0) # Add batch dimensionwith torch.inference_mode():outputs = vit(image)probs = torch.softmax(outputs, dim=1)pred_dict = {class_names[i]: float(probs[0][i])for i in range(len(class_names))}elapsed = round(timer() - start_time, 5)return pred_dict, elapsedexcept Exception as e:raise RuntimeError("Prediction failed. Ensure image format is correct.") from e### 2. Gradio App Setup ###title = "VisionBite π±ππ"description = "A Vision Transformer (ViT-Base-16) trained on 121 food classes. Upload an image and get top-5 food predictions!"article = "Model trained on the [Food121 dataset](https://huggingface.co/datasets/ItsNotRohit/Food121) with ~95% Top-5 accuracy."# Load image examples if anyexample_list = [["examples/" + f] for f in os.listdir("examples") if f.lower().endswith((".png", ".jpg", ".jpeg"))]demo = gr.Interface(fn=predict,inputs=gr.Image(type="pil"),outputs=[gr.Label(num_top_classes=5, label="Top 5 Predictions"),gr.Number(label="Prediction Time (s)")],examples=example_list,title=title,description=description,article=article,cache_examples=False)# Launchif __name__ == "__main__":demo.launch()
app.py+55-47