aayanb09 commited on
Commit
3d92fe2
·
verified ·
1 Parent(s): 6d711a0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import torch
3
+ import gradio as gr
4
+ import numpy as np
5
+ from PIL import Image
6
+ from torchvision import transforms
7
+
8
+ from model import FoodIngredientClassifier
9
+
10
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
+
12
+ # Load classes
13
+ with open("mlb_classes.json", "r") as f:
14
+ classes = json.load(f)
15
+
16
+ NUM_CLASSES = len(classes)
17
+
18
+ # Load model
19
+ model = FoodIngredientClassifier(NUM_CLASSES)
20
+ checkpoint = torch.load("best_model.pth", map_location=DEVICE)
21
+ model.load_state_dict(checkpoint["model_state_dict"])
22
+ model.to(DEVICE)
23
+ model.eval()
24
+
25
+ # Image preprocessing
26
+ transform = transforms.Compose([
27
+ transforms.Resize((224, 224)),
28
+ transforms.ToTensor(),
29
+ transforms.Normalize(
30
+ mean=[0.485, 0.456, 0.406],
31
+ std=[0.229, 0.224, 0.225]
32
+ )
33
+ ])
34
+
35
+ def predict(image, threshold=0.5):
36
+ image = image.convert("RGB")
37
+ x = transform(image).unsqueeze(0).to(DEVICE)
38
+
39
+ with torch.no_grad():
40
+ logits = model(x)
41
+ probs = torch.sigmoid(logits).cpu().numpy()[0]
42
+
43
+ results = [
44
+ (classes[i], float(probs[i]))
45
+ for i in np.where(probs > threshold)[0]
46
+ ]
47
+
48
+ results.sort(key=lambda x: x[1], reverse=True)
49
+ return results[:10]
50
+
51
+ demo = gr.Interface(
52
+ fn=predict,
53
+ inputs=[
54
+ gr.Image(type="pil", label="Upload Food Image"),
55
+ gr.Slider(0.1, 0.9, value=0.5, label="Confidence Threshold")
56
+ ],
57
+ outputs=gr.Label(label="Detected Ingredients"),
58
+ title="🍽️ Food Ingredient Detector",
59
+ description="Upload a food image and detect likely ingredients using a ResNet50 multi-label model."
60
+ )
61
+
62
+ if __name__ == "__main__":
63
+ demo.launch()