· 6 years ago · Feb 04, 2020, 07:22 PM
1import json
2import requests
3
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 presponse 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 # write your code here
23 headers = {
24 'Authorization': 'Key '+ api_key ,
25 'Content-Type': 'application/json',
26 }
27
28 data = {'inputs': [{'data': {'image': {'url': image_url}}}]}
29 json_data = json.dumps(data)
30
31 tags = requests.post('https://api.clarifai.com/v2/models/bd367be194cf45149e75f01d59f77ba7/outputs', headers=headers, data=json_data)
32 tags_list =[]
33 re_tags=tags.json()["outputs"][0]["data"]["concepts"]
34 for item in re_tags:
35 tags_list.append(item["name"])
36
37 return tags_list
38
39def get_access_token(token_name):
40 file_handle = open('access_tokens.sh', 'r+')
41 lines = file_handle.readlines()
42 file_handle.close()
43 for line in lines:
44 tokens = line.strip().split('=')
45 if tokens[0] == token_name:
46 return tokens[1].strip()
47 return 'Not found'
48
49if __name__ == '__main__':
50 clarify_api_key = get_access_token('CLARIFAI_API_KEY')
51 test_image_url = 'https://i.imgur.com/dlMjqQe.jpg'
52 tags_suggessted = get_tags_suggestions(clarify_api_key, test_image_url)
53 print(tags_suggessted)