Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
from torchvision import models, transforms
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
# Define class names
|
| 9 |
+
class_names = ['acorn_squash', 'almond', 'almonds', 'anchovy_(fish)', 'apple', 'apricot', 'artichoke', 'arugula', 'asparagus', 'avocado', 'baguette', 'banana', 'barley', 'barley_(grain)', 'beef_(meat)', 'beet', 'black_beans', 'black_pepper_(spice)', 'blackberry', 'bok_choy', 'bread_(loaf)', 'breadcrumbs', 'broccoli', 'brussels_sprouts', 'butter_(dairy)', 'butternut_squash', 'cabbage', 'canola_oil', 'cantaloupe', 'carrot', 'cashews', 'cauliflower', 'celery', 'cheddar_cheese', 'cherry', 'chicken_(meat)', 'chickpeas', 'chive', 'chocolate_chips', 'clams', 'clams_(seafood)', 'cocoa_powder', 'coconut', 'cod_(fish)', 'condensed_milk', 'confectioners_sugar', 'corn', 'corn_syrup', 'cornflakes', 'cornmeal', 'cottage_cheese', 'crab_(seafood)', 'crackers', 'cranberry', 'cream_(dairy)', 'cream_cheese', 'cucumber', 'date_(fruit)', 'dragonfruit', 'duck_(meat)', 'egg', 'eggplant', 'evaporated_milk', 'feta', 'feta_cheese', 'fig', 'fish_sauce', 'garlic', 'goat_cheese', 'grape', 'ground_beef', 'ground_pork', 'ground_turkey', 'guava', 'honeydew', 'jackfruit', 'kale', 'ketchup', 'kidney_beans', 'kiwi_(fruit)', 'lamb_(meat)', 'leek', 'lemon_(fruit)', 'lentils', 'lettuce', 'lime_(fruit)', 'lobster_(seafood)', 'lychee', 'mango', 'mayonnaise', 'meatballs', 'milk_(dairy)', 'molasses', 'mozzarella_cheese', 'mulberry', 'mushroom', 'mussels_(seafood)', 'mustard_(condiment)', 'mustard_greens', 'navy_beans', 'nectarine', 'noodles_(cooked)', 'oats', 'oats_(grain)', 'octopus_(seafood)', 'okra', 'olive', 'olive_oil', 'onion', 'orange_(fruit)', 'oyster_sauce', 'papaya', 'parmesan_cheese', 'parsnip', 'passionfruit', 'pasta_(cooked)', 'peach', 'peanut', 'peanut_butter', 'pear', 'pecans', 'pepper', 'persimmon', 'pineapple', 'pinto_beans', 'pita_bread', 'plum', 'pomegranate', 'pork_(meat)', 'potato', 'powdered_milk', 'powdered_sugar', 'pumpkin_seeds', 'quinoa', 'quinoa_(grain)', 'radish', 'raspberry', 'rice_(brown,_grain)', 'rice_(white,_grain)', 'ricotta', 'ricotta_cheese', 'rolled_oats', 'salmon', 'salmon_(fish)', 'salt', 'sardine_(fish)', 'scallion', 'scallops_(seafood)', 'seitan', 'sesame_oil', 'sesame_seeds', 'shallot', 'shrimp_(seafood)', 'sour_cream', 'soy_sauce', 'spinach', 'split_peas', 'squid_(seafood)', 'starfruit', 'strawberry', 'sunflower_oil', 'sunflower_seeds', 'sweet_potato', 'swiss_chard', 'tangerine', 'tempeh', 'tofu', 'tomato', 'tortilla_(flatbread)', 'tortillas', 'tuna', 'tuna_(fish)', 'turkey_(meat)', 'turnip', 'vegetable_oil', 'walnut', 'walnuts', 'watermelon', 'wheat_flour', 'whipping_cream', 'yam', 'yogurt_(dairy)', 'zucchini']
|
| 10 |
+
|
| 11 |
+
# Load model
|
| 12 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
+
print(f"Using device: {device}")
|
| 14 |
+
|
| 15 |
+
model = models.mobilenet_v2(pretrained=False)
|
| 16 |
+
num_ftrs = model.classifier[1].in_features
|
| 17 |
+
model.classifier[1] = nn.Linear(num_ftrs, len(class_names))
|
| 18 |
+
model.load_state_dict(torch.load("ingredientRecognitionModel.pth", map_location=device))
|
| 19 |
+
model = model.to(device)
|
| 20 |
+
model.eval()
|
| 21 |
+
|
| 22 |
+
# Image transformation
|
| 23 |
+
transform = transforms.Compose([
|
| 24 |
+
transforms.Resize((224, 224)),
|
| 25 |
+
transforms.ToTensor(),
|
| 26 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
|
| 27 |
+
])
|
| 28 |
+
|
| 29 |
+
def clean_ingredient_name(name):
|
| 30 |
+
"""Clean up ingredient name for display"""
|
| 31 |
+
name = name.split('_(')[0]
|
| 32 |
+
name = name.replace('_', ' ')
|
| 33 |
+
return name.title()
|
| 34 |
+
|
| 35 |
+
def predict(image):
|
| 36 |
+
"""Predict ingredients from image"""
|
| 37 |
+
if image is None:
|
| 38 |
+
return {"error": "No image provided"}
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
# Convert to PIL Image if needed
|
| 42 |
+
if not isinstance(image, Image.Image):
|
| 43 |
+
image = Image.fromarray(image)
|
| 44 |
+
|
| 45 |
+
# Convert to RGB
|
| 46 |
+
image = image.convert("RGB")
|
| 47 |
+
|
| 48 |
+
# Transform image
|
| 49 |
+
input_tensor = transform(image).unsqueeze(0).to(device)
|
| 50 |
+
|
| 51 |
+
# Run inference
|
| 52 |
+
with torch.no_grad():
|
| 53 |
+
outputs = model(input_tensor)
|
| 54 |
+
probs = torch.nn.functional.softmax(outputs[0], dim=0)
|
| 55 |
+
|
| 56 |
+
# Get top 5 predictions
|
| 57 |
+
k = min(5, len(class_names))
|
| 58 |
+
top_probs, top_idxs = torch.topk(probs, k)
|
| 59 |
+
|
| 60 |
+
# Build results dictionary
|
| 61 |
+
results = {}
|
| 62 |
+
for prob, idx in zip(top_probs, top_idxs):
|
| 63 |
+
raw_name = class_names[idx]
|
| 64 |
+
clean_name = clean_ingredient_name(raw_name)
|
| 65 |
+
confidence = prob.item()
|
| 66 |
+
results[clean_name] = float(confidence)
|
| 67 |
+
|
| 68 |
+
return results
|
| 69 |
+
|
| 70 |
+
except Exception as e:
|
| 71 |
+
return {"error": str(e)}
|
| 72 |
+
|
| 73 |
+
# Create Gradio interface
|
| 74 |
+
iface = gr.Interface(
|
| 75 |
+
fn=predict,
|
| 76 |
+
inputs=gr.Image(type="pil", label="Upload Food Image"),
|
| 77 |
+
outputs=gr.Label(num_top_classes=5, label="Predictions"),
|
| 78 |
+
title="Ingredient Classification Model",
|
| 79 |
+
description="Upload an image of food to identify the ingredients. This model recognizes over 200 different foods and ingredients.",
|
| 80 |
+
examples=[
|
| 81 |
+
# Add example images if you have them
|
| 82 |
+
],
|
| 83 |
+
theme=gr.themes.Soft(),
|
| 84 |
+
allow_flagging="never"
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
if __name__ == "__main__":
|
| 88 |
+
iface.launch()
|