Skip to content

Instantly share code, notes, and snippets.

@ramhiser
Last active February 19, 2016 21:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramhiser/ece557c315491672e56e to your computer and use it in GitHub Desktop.
Save ramhiser/ece557c315491672e56e to your computer and use it in GitHub Desktop.
Simple script to generate JSON to send to Google CloudVision API
# Did this without *requests* to avoid dependencies.
import urllib
import urllib2
import argparse
import base64
import json
API_URL = 'https://vision.googleapis.com/v1/images:annotate'
API_KEY = 'FLUFFY BUNNIES'
def main(image_url):
content_json = dict()
img = urllib2.urlopen(image_url)
if img.headers.maintype != 'image':
raise TypeError('Invalid filetype given')
content_json['content'] = base64.b64encode(img.read())
img.close()
# TODO: Get from user.
feature_json = {'type': 'TEXT_DETECTION', 'maxResults': 10}
request_list = []
cloudvision_json = {'features': feature_json, 'image': content_json}
request_list.append(cloudvision_json)
headers = {'Content-Type': 'application/json'}
get_params = urllib.urlencode({'key': API_KEY})
api_call = API_URL + '?' + get_params
request = urllib2.Request(api_call,
data=json.dumps({'requests': request_list}),
headers=headers)
f = urllib2.urlopen(request)
response = f.read()
f.close()
return json.loads(response)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-i', dest='image_url', required=True,
help='URL to image to encode')
args = parser.parse_args()
google_response = main(args.image_url)
print google_response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment