Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import requests
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from transformers import AutoFeatureExtractor, AutoModelForImageClassification
|
| 7 |
+
|
| 8 |
+
# Load model and extractor
|
| 9 |
+
model_id = "Adriana213/vgg16-food-classification"
|
| 10 |
+
model = AutoModelForImageClassification.from_pretrained(model_id)
|
| 11 |
+
extractor = AutoFeatureExtractor.from_pretrained(model_id)
|
| 12 |
+
|
| 13 |
+
# Transform image to model input
|
| 14 |
+
def transform_image(img):
|
| 15 |
+
return extractor(images=img, return_tensors="pt")["pixel_values"]
|
| 16 |
+
|
| 17 |
+
# Predict function
|
| 18 |
+
def detect_food(image):
|
| 19 |
+
inputs = transform_image(image)
|
| 20 |
+
with torch.no_grad():
|
| 21 |
+
outputs = model(inputs)
|
| 22 |
+
probs = torch.nn.functional.softmax(outputs.logits, dim=1)[0]
|
| 23 |
+
|
| 24 |
+
# Get top 5 predictions
|
| 25 |
+
topk = torch.topk(probs, 5)
|
| 26 |
+
labels = [model.config.id2label[i.item()] for i in topk.indices]
|
| 27 |
+
scores = [round(i.item() * 100, 2) for i in topk.values]
|
| 28 |
+
|
| 29 |
+
results = "\n".join([f"{label}: {score}%" for label, score in zip(labels, scores)])
|
| 30 |
+
return results
|
| 31 |
+
|
| 32 |
+
# Gradio UI
|
| 33 |
+
gr.Interface(
|
| 34 |
+
fn=detect_food,
|
| 35 |
+
inputs=gr.Image(type="pil"),
|
| 36 |
+
outputs="text",
|
| 37 |
+
title="🍔 Ultimate Food Detector",
|
| 38 |
+
description="Upload a food image. Get the dish names. Auto chef mode enabled. 🔥",
|
| 39 |
+
allow_flagging="never"
|
| 40 |
+
).launch()
|