citradiani commited on
Commit
405e855
·
verified ·
1 Parent(s): 70e3507

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +158 -40
app.py CHANGED
@@ -20,20 +20,113 @@ class_names = ['apple_pie',
20
  'sushi',
21
  'tiramisu']
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  def pil_loader(path):
 
 
24
  with open(path, 'rb') as f:
25
  img = Image.open(f)
26
  return img.convert('RGB')
27
 
28
  def predict(img_path):
29
  # Load and preprocess the image
 
30
  # image = pil_loader(img_path)
31
- # Convert Gradio image input to a NumPy array
 
 
32
  img_array = img_path.astype(np.uint8)
33
 
34
- # # Convert NumPy array to PIL Image
35
  image = Image.fromarray(img_array)
36
 
 
37
  test_transforms = transforms.Compose([
38
  transforms.Resize(256),
39
  transforms.CenterCrop(224),
@@ -44,87 +137,112 @@ def predict(img_path):
44
  # Apply transformations
45
  image = test_transforms(image)
46
 
 
47
  inf_model = models.resnet18(pretrained=False)
48
-
49
  num_ftrs = inf_model.fc.in_features
50
  # Here the size of each output sample is set to 2.
51
  # Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).
52
  inf_model.fc = nn.Linear(num_ftrs, len(class_names))
53
 
54
- # model_1 = model_1.to(device)
 
 
55
  inf_model.to(torch.device('cpu'))
56
- inf_model.load_state_dict(torch.load('./resnet18_tinyfood_classifier.pth', map_location='cpu'))
57
 
58
- # Perform inference
59
  with torch.no_grad():
60
  inf_model.eval()
61
  out = inf_model(image.unsqueeze(0)) # Add batch dimension
62
-
63
  # Get the predicted class and confidence
64
  _, preds = torch.max(out, 1)
65
  idx = preds.cpu().numpy()[0]
66
  pred_class = class_names[idx]
67
 
68
  # Assuming `out` is logits, you may need to apply softmax instead of sigmoid
 
69
  probabilities = torch.softmax(out, dim=1) # Apply softmax to get probabilities
70
  confidence = probabilities[0, idx].item() * 100 # Get confidence for the predicted class
71
 
72
- nutrition_data_path = './food-data.csv'
73
- # Membaca file CSV
74
  df = pd.read_csv(nutrition_data_path)
75
 
76
- # Mencocokkan prediksi dengan data CSV
77
  if pred_class.capitalize() in df["Makanan"].values:
78
  row = df.loc[df["Makanan"] == pred_class.capitalize()]
79
 
80
- # Convert int64 values to native Python data types
81
- calories = int(row["Kalori"].values[0])
82
- protein = int(row["Protein"].values[0])
83
- fat = int(row["Lemak"].values[0])
84
- carbs = int(row["Karbohidrat"].values[0])
85
- fiber = int(row["Serat"].values[0])
86
- sugar = int(row["Gula"].values[0])
87
- price = int(row["Harga (Rp)"].values[0])
88
-
89
- # # Mengambil informasi gizi
90
- # calories = row["Kalori"].values[0]
91
- # protein = row["Protein"].values[0]
92
- # fat = row["Lemak"].values[0]
93
- # carbs = row["Karbohidrat"].values[0]
94
- # fiber = row["Serat"].values[0]
95
- # sugar = row["Gula"].values[0]
96
- # price = row["Harga (Rp)"].values[0]
97
 
98
  return pred_class, calories, protein, fat, carbs, fiber, sugar, price
 
 
99
  else:
100
  nutrition_info = None
 
101
  return 'Food not found', 0, 0, 0, 0, 0, 0
 
102
 
103
  # return pred_class, confidence
104
 
105
 
106
  # img_path = '/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/bibimbap.jpeg'
 
107
  # print(predict(img_path))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  interface = gr.Interface(
110
  predict,
111
  inputs="image",
112
- title="Cafe App",
113
  description="This App will provide the information of your food choice in Selera Cafe. The menu includes: Apple Pie, Bibimbap, Cannoli, Edamame, Falafel, French Toast, Ramen, Sushi, Tiramisu. Enjoy your food!",
114
-
115
  outputs=[
116
  gr.Text(label="Food Label"),
117
- gr.Number(label="Calories"),
118
- gr.Number(label="Protein"),
119
- gr.Number(label="Fat"),
120
- gr.Number(label="Carbs"),
121
- gr.Number(label="Fiber"),
122
- gr.Number(label="Sugar"),
123
- gr.Number(label="Price")
124
  ],
 
125
  examples = [
126
- './bibimbap.jpeg',
127
- './apple-pie.jpeg',
128
- './cannoli.jpeg'
129
  ])
130
- interface.launch()
 
 
 
20
  'sushi',
21
  'tiramisu']
22
 
23
+ # def pil_loader(path):
24
+ # with open(path, 'rb') as f:
25
+ # img = Image.open(f)
26
+ # return img.convert('RGB')
27
+
28
+ # def predict(img_path):
29
+ # # Load and preprocess the image
30
+ # # image = pil_loader(img_path)
31
+ # # Convert Gradio image input to a NumPy array
32
+ # img_array = img_path.astype(np.uint8)
33
+
34
+ # # # Convert NumPy array to PIL Image
35
+ # image = Image.fromarray(img_array)
36
+
37
+ # test_transforms = transforms.Compose([
38
+ # transforms.Resize(256),
39
+ # transforms.CenterCrop(224),
40
+ # transforms.ToTensor(),
41
+ # transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
42
+ # ])
43
+
44
+ # # Apply transformations
45
+ # image = test_transforms(image)
46
+
47
+ # inf_model = models.resnet18(pretrained=False)
48
+
49
+ # num_ftrs = inf_model.fc.in_features
50
+ # # Here the size of each output sample is set to 2.
51
+ # # Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).
52
+ # inf_model.fc = nn.Linear(num_ftrs, len(class_names))
53
+
54
+ # # model_1 = model_1.to(device)
55
+ # inf_model.to(torch.device('cpu'))
56
+ # inf_model.load_state_dict(torch.load('./resnet18_tinyfood_classifier.pth', map_location='cpu'))
57
+
58
+ # # Perform inference
59
+ # with torch.no_grad():
60
+ # inf_model.eval()
61
+ # out = inf_model(image.unsqueeze(0)) # Add batch dimension
62
+
63
+ # # Get the predicted class and confidence
64
+ # _, preds = torch.max(out, 1)
65
+ # idx = preds.cpu().numpy()[0]
66
+ # pred_class = class_names[idx]
67
+
68
+ # # Assuming `out` is logits, you may need to apply softmax instead of sigmoid
69
+ # probabilities = torch.softmax(out, dim=1) # Apply softmax to get probabilities
70
+ # confidence = probabilities[0, idx].item() * 100 # Get confidence for the predicted class
71
+
72
+ # nutrition_data_path = './food-data.csv'
73
+ # # Membaca file CSV
74
+ # df = pd.read_csv(nutrition_data_path)
75
+
76
+ # # Mencocokkan prediksi dengan data CSV
77
+ # if pred_class.capitalize() in df["Makanan"].values:
78
+ # row = df.loc[df["Makanan"] == pred_class.capitalize()]
79
+
80
+ # # Convert int64 values to native Python data types
81
+ # calories = int(row["Kalori"].values[0])
82
+ # protein = int(row["Protein"].values[0])
83
+ # fat = int(row["Lemak"].values[0])
84
+ # carbs = int(row["Karbohidrat"].values[0])
85
+ # fiber = int(row["Serat"].values[0])
86
+ # sugar = int(row["Gula"].values[0])
87
+ # price = int(row["Harga (Rp)"].values[0])
88
+
89
+ # # # Mengambil informasi gizi
90
+ # # calories = row["Kalori"].values[0]
91
+ # # protein = row["Protein"].values[0]
92
+ # # fat = row["Lemak"].values[0]
93
+ # # carbs = row["Karbohidrat"].values[0]
94
+ # # fiber = row["Serat"].values[0]
95
+ # # sugar = row["Gula"].values[0]
96
+ # # price = row["Harga (Rp)"].values[0]
97
+
98
+ # return pred_class, calories, protein, fat, carbs, fiber, sugar, price
99
+ # else:
100
+ # nutrition_info = None
101
+ # return 'Food not found', 0, 0, 0, 0, 0, 0
102
+
103
+ # # return pred_class, confidence
104
+
105
+
106
+ # img_path = '/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/bibimbap.jpeg'
107
+ # print(predict(img_path))
108
+
109
+
110
  def pil_loader(path):
111
+ # Define a function to load an image using PIL and convert it to RGB format
112
+ with open(path, 'rb') as f:
113
  with open(path, 'rb') as f:
114
  img = Image.open(f)
115
  return img.convert('RGB')
116
 
117
  def predict(img_path):
118
  # Load and preprocess the image
119
+ ##### Uncomment: without gradio
120
  # image = pil_loader(img_path)
121
+
122
+ ##### Uncomment: with gradio
123
+ # Convert Gradio image input to a NumPy array
124
  img_array = img_path.astype(np.uint8)
125
 
126
+ # Convert NumPy array to PIL Image
127
  image = Image.fromarray(img_array)
128
 
129
+ # Define transformations to apply to the image
130
  test_transforms = transforms.Compose([
131
  transforms.Resize(256),
132
  transforms.CenterCrop(224),
 
137
  # Apply transformations
138
  image = test_transforms(image)
139
 
140
+ # Load a pre-trained ResNet18 model and modify the fully connected layer
141
  inf_model = models.resnet18(pretrained=False)
 
142
  num_ftrs = inf_model.fc.in_features
143
  # Here the size of each output sample is set to 2.
144
  # Alternatively, it can be generalized to nn.Linear(num_ftrs, len(class_names)).
145
  inf_model.fc = nn.Linear(num_ftrs, len(class_names))
146
 
147
+ # model_1 = model_1.to(device)
148
+
149
+ # Move the model to CPU and load its state dict from the specified path
150
  inf_model.to(torch.device('cpu'))
151
+ inf_model.load_state_dict(torch.load('/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/resnet18_tinyfood_classifier.pth', map_location='cpu'))
152
 
153
+ # Perform inference on the image using the model
154
  with torch.no_grad():
155
  inf_model.eval()
156
  out = inf_model(image.unsqueeze(0)) # Add batch dimension
157
+
158
  # Get the predicted class and confidence
159
  _, preds = torch.max(out, 1)
160
  idx = preds.cpu().numpy()[0]
161
  pred_class = class_names[idx]
162
 
163
  # Assuming `out` is logits, you may need to apply softmax instead of sigmoid
164
+ # Apply softmax to get probabilities and calculate confidence for the predicted class
165
  probabilities = torch.softmax(out, dim=1) # Apply softmax to get probabilities
166
  confidence = probabilities[0, idx].item() * 100 # Get confidence for the predicted class
167
 
168
+ # Read nutrition data from a CSV file and match the predicted class
169
+ nutrition_data_path = '/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/food-data.csv'
170
  df = pd.read_csv(nutrition_data_path)
171
 
 
172
  if pred_class.capitalize() in df["Makanan"].values:
173
  row = df.loc[df["Makanan"] == pred_class.capitalize()]
174
 
175
+ # Extract nutrition information for the predicted class
176
+ calories = row["Kalori"].values[0]
177
+ protein = row["Protein"].values[0]
178
+ fat = row["Lemak"].values[0]
179
+ carbs = row["Karbohidrat"].values[0]
180
+ fiber = row["Serat"].values[0]
181
+ sugar = row["Gula"].values[0]
182
+ price = row["Harga (Rp)"].values[0]
 
 
 
 
 
 
 
 
 
183
 
184
  return pred_class, calories, protein, fat, carbs, fiber, sugar, price
185
+ # return "Food", 1, 1, 1, 1, 1, 1
186
+ # return calories
187
  else:
188
  nutrition_info = None
189
+ # Return 'Food not found' message if predicted class not in the nutrition data
190
  return 'Food not found', 0, 0, 0, 0, 0, 0
191
+ # return "Text2"
192
 
193
  # return pred_class, confidence
194
 
195
 
196
  # img_path = '/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/bibimbap.jpeg'
197
+ # img_path = '/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/food-101-tiny/cannoli.jpeg'
198
  # print(predict(img_path))
199
+
200
+
201
+ # interface = gr.Interface(
202
+ # predict,
203
+ # inputs="image",
204
+ # title="Cafe App",
205
+ # description="This App will provide the information of your food choice in Selera Cafe. The menu includes: Apple Pie, Bibimbap, Cannoli, Edamame, Falafel, French Toast, Ramen, Sushi, Tiramisu. Enjoy your food!",
206
+
207
+ # outputs=[
208
+ # gr.Text(label="Food Label"),
209
+ # gr.Number(label="Calories"),
210
+ # gr.Number(label="Protein"),
211
+ # gr.Number(label="Fat"),
212
+ # gr.Number(label="Carbs"),
213
+ # gr.Number(label="Fiber"),
214
+ # gr.Number(label="Sugar"),
215
+ # gr.Number(label="Price")
216
+ # ],
217
+ # examples = [
218
+ # './bibimbap.jpeg',
219
+ # './apple-pie.jpeg',
220
+ # './cannoli.jpeg'
221
+ # ])
222
+ # interface.launch()
223
 
224
  interface = gr.Interface(
225
  predict,
226
  inputs="image",
227
+ title="Selera Cafe App",
228
  description="This App will provide the information of your food choice in Selera Cafe. The menu includes: Apple Pie, Bibimbap, Cannoli, Edamame, Falafel, French Toast, Ramen, Sushi, Tiramisu. Enjoy your food!",
229
+ # outputs=gr.Text(),
230
  outputs=[
231
  gr.Text(label="Food Label"),
232
+ gr.Text(label="Calories"),
233
+ gr.Text(label="Protein"),
234
+ gr.Text(label="Fat"),
235
+ gr.Text(label="Carbs"),
236
+ gr.Text(label="Fiber"),
237
+ gr.Text(label="Sugar"),
238
+ gr.Text(label="Price")
239
  ],
240
+
241
  examples = [
242
+ '/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/bibimbap.jpeg',
243
+ '/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/food-101-tiny/apple-pie.jpeg',
244
+ '/content/drive/MyDrive/Assignment-Citra-SkillacademyAI/food-101-tiny/cannoli.jpeg'
245
  ])
246
+ interface.launch()
247
+
248
+ # Type is not JSON serializable: numpy.int64