aayanb09 commited on
Commit
da50974
·
verified ·
1 Parent(s): be4029e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -0
app.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from PIL import Image
4
+ import numpy as np
5
+ from torchvision import transforms
6
+
7
+ from model import FoodIngredientClassifier
8
+ from utils import load_model_and_mlb
9
+
10
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+
12
+ # Load model + label binarizer
13
+ model, mlb, threshold = load_model_and_mlb("model.pth", DEVICE)
14
+ model.eval()
15
+
16
+ transform = transforms.Compose([
17
+ transforms.Resize((224, 224)),
18
+ transforms.ToTensor(),
19
+ transforms.Normalize([0.485, 0.456, 0.406],
20
+ [0.229, 0.224, 0.225])
21
+ ])
22
+
23
+ def predict(image):
24
+ image = image.convert("RGB")
25
+ img_tensor = transform(image).unsqueeze(0).to(DEVICE)
26
+
27
+ with torch.no_grad():
28
+ output = model(img_tensor)
29
+ probs = torch.sigmoid(output).cpu().numpy()[0]
30
+
31
+ pred_indices = np.where(probs > threshold)[0]
32
+ ingredients = mlb.classes_[pred_indices]
33
+ confidences = probs[pred_indices]
34
+
35
+ results = sorted(
36
+ [(ing, float(conf)) for ing, conf in zip(ingredients, confidences)],
37
+ key=lambda x: x[1],
38
+ reverse=True
39
+ )
40
+
41
+ if not results:
42
+ return {"No ingredient detected": 1.0}
43
+
44
+ return {k: v for k, v in results}
45
+
46
+ iface = gr.Interface(
47
+ fn=predict,
48
+ inputs=gr.Image(type="pil"),
49
+ outputs=gr.Label(num_top_classes=10),
50
+ title="Food Ingredient Classifier",
51
+ description="Upload a food image to detect ingredients."
52
+ )
53
+
54
+ iface.launch()