Last active
March 2, 2016 20:24
-
-
Save jeffbaumes/d813f210409723f8686d to your computer and use it in GitHub Desktop.
Google Vision API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import argparse | |
| import base64 | |
| import json | |
| import sys | |
| import requests | |
| KEY = '<<your API key here>>' | |
| # Usage: | |
| # python visionapi.py -i input_file -o output_json_file | |
| def main(input_filename, output_filename): | |
| """Translates the input file into a json output file. | |
| Args: | |
| input_file: a file object, containing lines of input to convert. | |
| output_filename: the name of the file to output the json to. | |
| """ | |
| request_list = [] | |
| with open(input_filename, 'rb') as image_file: | |
| content_json_obj = { | |
| 'content': base64.b64encode(image_file.read()) | |
| } | |
| feature_json_obj = [] | |
| feature, max_results = [4, 10] | |
| feature_json_obj.append({ | |
| 'type': get_detection_type(feature), | |
| 'maxResults': int(max_results), | |
| }) | |
| request_list.append({ | |
| 'features': feature_json_obj, | |
| 'image': content_json_obj, | |
| }) | |
| response = requests.post(url='https://vision.googleapis.com/v1/images:annotate?key=' + KEY, | |
| data=json.dumps({'requests': request_list}), | |
| headers={'Content-Type': 'application/json'}) | |
| with open(output_filename, 'w') as output_file: | |
| output_file.write(response.text) | |
| DETECTION_TYPES = [ | |
| 'TYPE_UNSPECIFIED', | |
| 'FACE_DETECTION', | |
| 'LANDMARK_DETECTION', | |
| 'LOGO_DETECTION', | |
| 'LABEL_DETECTION', | |
| 'TEXT_DETECTION', | |
| 'SAFE_SEARCH_DETECTION', | |
| ] | |
| def get_detection_type(detect_num): | |
| """Return the Vision API symbol corresponding to the given number.""" | |
| detect_num = int(detect_num) | |
| if 0 < detect_num < len(DETECTION_TYPES): | |
| return DETECTION_TYPES[detect_num] | |
| else: | |
| return DETECTION_TYPES[0] | |
| if __name__ == '__main__': | |
| main(sys.argv[2], sys.argv[4]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That CLI is pretty... not right. Why even bother with dash args when you're pulling directly from args list. =^.^=