Skip to content

Instantly share code, notes, and snippets.

@tcw165
Last active May 20, 2016 02:26
Show Gist options
  • Save tcw165/d4387f5f549c3a0d65f8816ae3bb44fa to your computer and use it in GitHub Desktop.
Save tcw165/d4387f5f549c3a0d65f8816ae3bb44fa to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import httplib, urllib
import argparse
import json
import os
def analyseImages(fileStream):
"""
:param fileStream: the 'file' array.
:return: the JSON object.
"""
# Request headers
headers = {
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': os.environ.get('BING_VISION_API_KEY'),
}
# Request parameters
params = urllib.urlencode({
'visualFeatures': 'Categories,Tags,Description,Faces,Color',
'details': 'Celebrities',
})
# Analyse the photo.
data = None
try:
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/vision/v1.0/analyze?%s" % params,
fileStream,
headers)
response = conn.getresponse()
data = response.read()
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
finally:
return data
# /////////////////////////////////////////////////////////////////////////////
# Plain Codes /////////////////////////////////////////////////////////////////
# Parse arguments.
argParser = argparse.ArgumentParser(description='Microsoft Vision APIs.')
argParser.add_argument('files',
metavar='FILENAME',
type=argparse.FileType('r'),
nargs='+',
help='The photo files.')
args = argParser.parse_args()
# Bing Keys.
BING_VISION_API_KEY = os.environ.get('BING_VISION_API_KEY')
BING_FACE_API_KEY = os.environ.get('BING_FACE_API_KEY')
BING_EMOTION_API_KEY = os.environ.get('BING_EMOTION_API_KEY')
# Extract files.
files = args.files
for f in files:
d = json.loads(analyseImages(f))
print ""
print "%s ==>" % f.name
print json.dumps(d,
separators=(',', ':'),
indent=4,
sort_keys=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment