· 6 years ago · Jan 26, 2020, 02:34 PM
1
2import json
3import requests
4import os
5
6#TODO: CRIO_TASK_MODULE_TAG_SUGGESTION
7# As part of this module you are expected to complete the get_tags_suggestions() function
8# Tasks:
9# 1) You need to register as Clarifai developer to obtain an API Key to the Food Model
10# The Food model can be found here:
11# https://www.clarifai.com/models/food-image-recognition-model-bd367be194cf45149e75f01d59f77ba7
12# A sample request and response can be found in the above link
13# 2) Use the food model to get implement tag suggestions
14
15# Parameters
16# ----------
17# api_key : string
18# API Key for Clarifai
19# image_url : string
20# publicly accessible URL of the image to get tag suggestions
21# Return Type: list()
22# return a list of tags provided by the Clarifai API
23def get_tags_suggestions(api_key, image_url):
24 # write your code here
25 data = {
26 "inputs": [
27 {
28 "data": {
29 "image": {
30 "url": image_url
31 }
32 }
33 }
34 ]
35
36 }
37 headers={
38 'Authorization': 'Key '+api_key,
39 'Content-Type': 'application/json'
40 }
41 json_data = json.dumps(data)
42 my_req = requests.post(url = 'https://api.clarifai.com/v2/models/bd367be194cf45149e75f01d59f77ba7/outputs',headers=headers , data = json_data)
43 a=my_req.json()
44 b=a['outputs'][0]['data']['concepts']
45 c=[]
46 for i in b:
47 #print(i)
48
49 c.append(i['name'])
50 return c
51
52def get_access_token(token_name):
53 dir = os.path.dirname(__file__)
54 file_path = os.path.join(dir, '../access_tokens.sh')
55 file_handle = open(file_path, 'r+')
56 lines = file_handle.readlines()
57 file_handle.close()
58 for line in lines:
59 tokens = line.strip().split('=')
60 if tokens[0] == token_name:
61 return tokens[1].strip()
62 return 'Not found'
63
64if __name__ == '__main__':
65 clarify_api_key = get_access_token('CLARIFAI_API_KEY')
66 test_image_url = 'https://i.imgur.com/dlMjqQe.jpg'
67 tags_suggessted = get_tags_suggestions(clarify_api_key, test_image_url)
68 print(tags_suggessted)
69
70
71
72
73
74
75
76
77
78views --------
79
80
81
82import os
83from rest_framework.permissions import AllowAny
84from rest_framework.views import APIView
85from django.shortcuts import render
86from django.http import JsonResponse
87from rest_framework.generics import ListAPIView
88from rest_framework.response import Response
89from rest_framework import status
90
91import restaurants.image_uploader
92import restaurants.facebook_post
93import restaurants.clarifai_tag_suggestions
94# Create your views here.
95def get_access_token(token_name):
96 dir = os.path.dirname(__file__)
97 file_path = os.path.join(dir, '../access_tokens.sh')
98 file_handle = open(file_path, 'r+')
99 lines = file_handle.readlines()
100 for line in lines:
101 tokens = line.strip().split('=')
102 if tokens[0] == token_name:
103 return tokens[1].strip()
104
105 return 'Not found'
106
107class GetRestaurants(ListAPIView):
108 #serializer_class = RestaurantSerializer
109 def list(self, request, *args, **kwargs):
110 restaurants = {
111 "restaurants": [
112 {
113 "restaurantId": "10",
114 "name": "A2B",
115 "city": "Btm Layout",
116 "imageUrl": "www.google.com",
117 "latitude": 20.027,
118 "longitude": 30.0,
119 "opensAt": "18:00",
120 "closesAt": "23:00",
121 "attributes": [
122 "Tamil",
123 "South Indian"
124 ]
125 },
126 {
127 "restaurantId": "11",
128 "name": "A2B",
129 "city": "Hsr Layout",
130 "imageUrl": "www.google.com",
131 "latitude": 20.027,
132 "longitude": 30.0,
133 "opensAt": "18:00",
134 "closesAt": "23:00",
135 "attributes": [
136 "Tamil",
137 "South Indian"
138 ]
139 }
140 ]
141 }
142
143 return Response(restaurants)
144
145
146class MenuApiView(ListAPIView):
147 def list(self, request, *args, **kwargs):
148 menu_response = {
149 "menu": {
150 "items": [
151 {
152 "attributes": [
153 "South Indian"
154 ],
155 "id": "1",
156 "imageUrl": "www.google.com",
157 "itemId": "10",
158 "name": "Idly",
159 "price": 45
160 },
161 {
162 "attributes": [
163 "South Indian"
164 ],
165 "id": "2",
166 "imageUrl": "www.google.com",
167 "itemId": "10",
168 "name": "Vadai",
169 "price": 30
170 },
171 {
172 "attributes": [
173 "South Indian"
174 ],
175 "id": "1",
176 "imageUrl": "www.google.com",
177 "itemId": "10",
178 "name": "Masala Dosai",
179 "price": 90
180 }
181 ],
182 "restaurantId": "11"
183 }
184 }
185
186 return Response(menu_response)
187
188
189class OrderListView(ListAPIView):
190 def list(self, request, *args, **kwargs):
191 order_lists = [
192 {
193 "id": "1",
194 "items": [
195 {
196 "attributes": [
197 "South Indian"
198 ],
199 "id": "1",
200 "imageUrl": "www.google.com",
201 "itemId": "10",
202 "name": "Idly",
203 "price": 45
204 }
205 ],
206 "restaurantId": "11",
207 "timePlaced": "",
208 "total": 45,
209 "userId": "string"
210 },
211 {
212 "id": "10",
213 "items": [
214 {
215 "attributes": [
216 "South Indian"
217 ],
218 "id": "1",
219 "imageUrl": "www.google.com",
220 "itemId": "10",
221 "name": "Idly",
222 "price": 45
223 }
224 ],
225 "restaurantId": "11",
226 "timePlaced": "",
227 "total": 45,
228 "userId": "string"
229 },
230 {
231 "id": "102",
232 "items": [
233 {
234 "attributes": [
235 "South Indian"
236 ],
237 "id": "1",
238 "imageUrl": "www.google.com",
239 "itemId": "10",
240 "name": "Idly",
241 "price": 45
242 }
243 ],
244 "restaurantId": "11",
245 "timePlaced": "",
246 "total": 45,
247 "userId": "string"
248 }
249 ]
250 return JsonResponse(order_lists, safe=False)
251
252
253class GetSocial(ListAPIView):
254 #serializer_class = RestaurantSerializer
255 def list(self, request, *args, **kwargs):
256 tags = ['Facebook', 'Pinterest']
257 return JsonResponse(tags, safe=False)
258
259
260class GetCart(ListAPIView):
261 #serializer_class = RestaurantSerializer
262 def list(self, request, *args, **kwargs):
263 cart = {}
264 return Response(cart)
265
266
267# @POST
268# ENDPOINT 'qeats/v1/tags'
269# request body = {
270# 'img_base64' : '<BASE 64 IMAGE CONTENT>',
271# }
272
273#response = ['tag1', 'tag2']
274class GetTags(APIView):
275 permission_classes = [AllowAny]
276 authentication_classes = []
277
278 def post(self, request, *args, **kwargs):
279 tags = []
280 body = request.data
281 assert set(['imgBase64']) == set(sorted(list(body.keys())))
282 img_b64 = body['imgBase64']
283 image_url = restaurants.image_uploader.upload(img_b64)
284 tags=restaurants.clarifai_tag_suggestions.get_tags_suggestions(get_access_token('CLARIFAI_API_KEY'),image_url)
285 #print(tags)
286
287 # TODO: CRIO_TASK_MODULE_TAG_SUGGESTION
288 # Add call to clarifai api here.
289 # Refer todo in qeats/restaurants/clarifai_tag_suggestions.py for instructions
290
291 return JsonResponse(tags, safe=False)
292
293# @POST
294# ENDPOINT 'qeats/v1/reviews/share'
295# {
296# 'imgBase64' : '',
297# 'text' : 'Great Food!',
298# 'orderId' : '0x12312',
299# 'tags' : ['Briyani'],
300# 'share' : ['Facebook', 'Pinterest']
301# }
302class ShareReview(ListAPIView):
303 def post(self, request, *args, **kwargs):
304 body = request.data
305 assert set(['imgBase64', 'orderId', 'share', 'tags', 'text']
306 ) == set(sorted(list(body.keys())))
307 message = body['text'] + ' ' + \
308 ''.join(['#' + tag + ' ' for tag in body['tags']])
309 image_base64 = body['imgBase64']
310 image_url = restaurants.image_uploader.upload(image_base64)
311
312 if 'Facebook' in body['share']:
313 facebook = restaurants.facebook_post.Facebook()
314 facebook.publish_photo_msg(message, image_url)
315
316 #TODO: CRIO_TASK_MODULE_PINTEREST_SHARE
317 # add support to share a review to a Pinterest board
318 # check if you get Pinterest in body['share']
319
320
321 response_data = {
322 "reviewId": body['orderId'],
323 "responseType": 1
324 }
325
326 return Response(response_data)