· 5 years ago · Jun 26, 2020, 08:30 AM
1import json
2import requests
3import pprint
4#TODO: CRIO_TASK_MODULE_TAG_SUGGESTION
5# As part of this module you are expected to complete the get_tags_suggestions() function
6# Tasks:
7# 1) You need to register as Clarifai developer to obtain an API Key to the Food Model
8# The Food model can be found here:
9# https://www.clarifai.com/models/food-image-recognition-model-bd367be194cf45149e75f01d59f77ba7
10# A sample request and response can be found in the above link
11# 2) Use the food model to get implement tag suggestions
12
13# Parameters
14# ----------
15# api_key : string
16# API Key for Clarifai
17# image_url : string
18# publicly accessible URL of the image to get tag suggestions
19# Return Type: list()
20# return a list of tags provided by the Clarifai API
21def get_tags_suggestions(api_key, image_url):
22 headers = {
23 'Authorization': 'Key '+api_key,
24 'Content-Type': 'application/json',
25 }
26 data = {"inputs": [{"data": {"image": {"url": f"{image_url}"}}}]}
27 json_data = json.dumps(data)
28 response = requests.post('https://api.clarifai.com/v2/models/bd367be194cf45149e75f01d59f77ba7/outputs', headers=headers, data=json_data)
29 fooddict=response.json()
30 foodlist=[]
31 for i in range(0,len(fooddict['outputs'][0]['data']['concepts'])):
32 foodlist.append(fooddict['outputs'][0]['data']['concepts'][i]['name'])
33 return foodlist
34
35def get_access_token(token_name):
36 file_handle = open('access_tokens.sh', 'r+')
37 lines = file_handle.readlines()
38 file_handle.close()
39 for line in lines:
40 tokens = line.strip().split('=')
41 if tokens[0] == token_name:
42 return tokens[1].strip()
43 return 'Not found'
44
45if __name__ == '__main__':
46 clarify_api_key = '861f3a8c8ef64d979656d4c4f34f9412'
47 test_image_url = 'https://i.imgur.com/dlMjqQe.jpg'
48 tags_suggessted = get_tags_suggestions(clarify_api_key, test_image_url)
49 print(tags_suggessted)