Vrk commited on
Commit
7fca85d
1 Parent(s): 80def48

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +117 -93
utils.py CHANGED
@@ -1,94 +1,118 @@
1
- import tensorflow as tf
2
- import numpy as np
3
- import os
4
-
5
- import requests
6
- import json
7
- # def view_and_predict(target_dir, target_class, model_path):
8
-
9
- # # Reading image and plotting image
10
- # img = tf.io.read_file(target_folder + '/' + random_image[0])
11
- # img = tf.io.decode_image(img)
12
- # img = tf.image.resize(img,(224,224))
13
- # img_show = img/255.
14
-
15
- # pred = model_pred(model_path, img, class_names)
16
-
17
- # plt.imshow(img_show)
18
- # plt.title(f"Real Label: {target_class}, prediction: {pred}")
19
- # plt.axis('off');
20
-
21
- # return img
22
-
23
-
24
- classes = ['apple pie', 'baby back ribs', 'baklava', 'beef carpaccio', 'beef tartare',
25
- 'beet salad', 'beignets', 'bibimbap', 'bread pudding', 'breakfast burrito',
26
- 'bruschetta', 'caesar_salad', 'cannoli', 'caprese salad', 'carrot cake',
27
- 'ceviche', 'cheese plate', 'cheesecake', 'chicken curry',
28
- 'chicken quesadilla', 'chicken wings', 'chocolate cake', 'chocolate mousse',
29
- 'churros', 'clam chowder', 'club sandwich', 'crab cakes', 'creme brulee',
30
- 'croque madame', 'cup cakes', 'deviled eggs', 'donuts', 'dumplings', 'edamame',
31
- 'eggs benedict', 'escargots', 'falafel', 'filet mignon', 'fish and chips',
32
- 'foie gras', 'french fries', 'french onion soup', 'french toast',
33
- 'fried calamari', 'fried rice', 'frozen yogurt', 'garlic bread', 'gnocchi',
34
- 'greek salad', 'grilled cheese sandwich', 'grilled salmon', 'guacamole',
35
- 'gyoza', 'hamburger', 'hot and sour soup', 'hot dog', 'huevos rancheros',
36
- 'hummus', 'ice cream', 'lasagna', 'lobster bisque', 'lobster roll sandwich',
37
- 'macaroni and cheese', 'macarons', 'miso soup', 'mussels', 'nachos',
38
- 'omelette', 'onion rings', 'oysters', 'pad thai', 'paella', 'pancakes',
39
- 'panna cotta', 'peking duck', 'pho', 'pizza', 'pork chop', 'poutine',
40
- 'prime rib', 'pulled pork sandwich', 'ramen', 'ravioli', 'red velvet cake',
41
- 'risotto', 'samosa', 'sashimi', 'scallops', 'seaweed salad',
42
- 'shrimp and grits', 'spaghetti bolognese', 'spaghetti carbonara',
43
- 'spring rolls', 'steak', 'strawberry_shortcake', 'sushi', 'tacos', 'takoyaki',
44
- 'tiramisu', 'tuna tartare', 'waffles']
45
-
46
- def load_prepare_image(filepath, img_size, rescale=False):
47
- img = tf.io.decode_image(filepath, channels=3)
48
- img = tf.image.resize(img, img_size)
49
-
50
- if rescale:
51
- return img/255.
52
- else:
53
- return img
54
-
55
- def model_pred(model_path, img, class_names=classes):
56
- # Load TFLite model and allocate tensors.
57
- interpreter = tf.lite.Interpreter(model_path=model_path)
58
- #allocate the tensors
59
- interpreter.allocate_tensors()
60
-
61
- input_tensor= np.array(np.expand_dims(img,0), dtype=np.float32)
62
- input_index = interpreter.get_input_details()[0]["index"]
63
-
64
- # setting input tensor
65
- interpreter.set_tensor(input_index, input_tensor)
66
-
67
- #Run the inference
68
- interpreter.invoke()
69
- output_details = interpreter.get_output_details()
70
-
71
- # output data of image
72
- output_data = interpreter.get_tensor(output_details[0]['index'])
73
-
74
- pred = output_data.argmax()
75
-
76
- food_name = class_names[pred]
77
-
78
- return food_name
79
-
80
- def fetch_recipe(food_name):
81
- url = "https://recipesapi2.p.rapidapi.com/recipes/"+food_name
82
- querystring = {"maxRecipes":"1"}
83
-
84
- headers = {
85
- 'x-rapidapi-host': "recipesapi2.p.rapidapi.com",
86
- 'x-rapidapi-key': "f6f6823b91msh9e92fed91d5356ap136f5djsn494d8f582fb3"
87
- }
88
-
89
- response = requests.request("GET", url, headers=headers, params=querystring)
90
- json_data = json.loads(response.text)
91
-
92
- recipe_data = json_data['data'][0]
93
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  return recipe_data
 
1
+ import tensorflow as tf
2
+ import numpy as np
3
+ import torch
4
+ import torch.nn as nn
5
+ import timm
6
+ from torchvision import transforms
7
+ import os
8
+
9
+ import requests
10
+ import json
11
+
12
+ classes = ['apple pie', 'baby back ribs', 'baklava', 'beef carpaccio', 'beef tartare',
13
+ 'beet salad', 'beignets', 'bibimbap', 'bread pudding', 'breakfast burrito',
14
+ 'bruschetta', 'caesar_salad', 'cannoli', 'caprese salad', 'carrot cake',
15
+ 'ceviche', 'cheese plate', 'cheesecake', 'chicken curry',
16
+ 'chicken quesadilla', 'chicken wings', 'chocolate cake', 'chocolate mousse',
17
+ 'churros', 'clam chowder', 'club sandwich', 'crab cakes', 'creme brulee',
18
+ 'croque madame', 'cup cakes', 'deviled eggs', 'donuts', 'dumplings', 'edamame',
19
+ 'eggs benedict', 'escargots', 'falafel', 'filet mignon', 'fish and chips',
20
+ 'foie gras', 'french fries', 'french onion soup', 'french toast',
21
+ 'fried calamari', 'fried rice', 'frozen yogurt', 'garlic bread', 'gnocchi',
22
+ 'greek salad', 'grilled cheese sandwich', 'grilled salmon', 'guacamole',
23
+ 'gyoza', 'hamburger', 'hot and sour soup', 'hot dog', 'huevos rancheros',
24
+ 'hummus', 'ice cream', 'lasagna', 'lobster bisque', 'lobster roll sandwich',
25
+ 'macaroni and cheese', 'macarons', 'miso soup', 'mussels', 'nachos',
26
+ 'omelette', 'onion rings', 'oysters', 'pad thai', 'paella', 'pancakes',
27
+ 'panna cotta', 'peking duck', 'pho', 'pizza', 'pork chop', 'poutine',
28
+ 'prime rib', 'pulled pork sandwich', 'ramen', 'ravioli', 'red velvet cake',
29
+ 'risotto', 'samosa', 'sashimi', 'scallops', 'seaweed salad',
30
+ 'shrimp and grits', 'spaghetti bolognese', 'spaghetti carbonara',
31
+ 'spring rolls', 'steak', 'strawberry_shortcake', 'sushi', 'tacos', 'takoyaki',
32
+ 'tiramisu', 'tuna tartare', 'waffles']
33
+
34
+ ##########################################################################
35
+ # TENSORFLOW FUNCTIONS #
36
+ ##########################################################################
37
+
38
+ def load_prepare_image_tf(filepath, img_size, rescale=False):
39
+ img = tf.io.decode_image(filepath, channels=3)
40
+ img = tf.image.resize(img, img_size)
41
+
42
+ if rescale:
43
+ return img/255.
44
+ else:
45
+ return img
46
+
47
+ def model_pred_tf(model_path, img, class_names=classes):
48
+ # Load TFLite model and allocate tensors.
49
+ interpreter = tf.lite.Interpreter(model_path=model_path)
50
+ #allocate the tensors
51
+ interpreter.allocate_tensors()
52
+
53
+ input_tensor= np.array(np.expand_dims(img,0), dtype=np.float32)
54
+ input_index = interpreter.get_input_details()[0]["index"]
55
+
56
+ # setting input tensor
57
+ interpreter.set_tensor(input_index, input_tensor)
58
+
59
+ #Run the inference
60
+ interpreter.invoke()
61
+ output_details = interpreter.get_output_details()
62
+
63
+ # output data of image
64
+ output_data = interpreter.get_tensor(output_details[0]['index'])
65
+
66
+ pred = output_data.argmax()
67
+
68
+ food_name = class_names[pred]
69
+
70
+ return food_name
71
+
72
+ ##########################################################################
73
+ # PyTorch FUNCTIONS #
74
+ ##########################################################################
75
+
76
+ def get_model_pt(model_path):
77
+ model = timm.create_model('vit_base_patch16_224', pretrained=False)
78
+ model.head = nn.Linear(in_features=768, out_features=len(classes), bias=True)
79
+ model.load_state_dict(torch.load('models/ViT-101-1.pt', map_location='cpu'))
80
+ return model
81
+
82
+ def load_prepare_image_pt(input_image):
83
+ normalize = transforms.Normalize(
84
+ [0.485, 0.456, 0.406],
85
+ [0.229, 0.224, 0.225]
86
+ )
87
+ img_transform = transforms.Compose([
88
+ transforms.Resize((225, 225)),
89
+ transforms.CenterCrop(224),
90
+ transforms.ToTensor(),
91
+ normalize,
92
+ ])
93
+ input_image = img_transform(input_image).unsqueeze(0)
94
+ return input_image
95
+
96
+
97
+ def model_pred_pt(input_image, model_path):
98
+ model = get_model_pt(model_path)
99
+ probs = model(input_image)
100
+ y_preds = torch.softmax(probs, dim=1).detach().numpy().argmax()
101
+ pred = classes[y_preds]
102
+ return pred
103
+
104
+ def fetch_recipe(food_name):
105
+ url = "https://recipesapi2.p.rapidapi.com/recipes/"+food_name
106
+ querystring = {"maxRecipes":"1"}
107
+
108
+ headers = {
109
+ 'x-rapidapi-host': "recipesapi2.p.rapidapi.com",
110
+ 'x-rapidapi-key': "f6f6823b91msh9e92fed91d5356ap136f5djsn494d8f582fb3"
111
+ }
112
+
113
+ response = requests.request("GET", url, headers=headers, params=querystring)
114
+ json_data = json.loads(response.text)
115
+
116
+ recipe_data = json_data['data'][0]
117
+
118
  return recipe_data