0
votes

I am new to Python and Microsoft Cognitive Services. I am trying an example for Computer Vision API where I am trying to POST the URL of an image for analysis and following is the code I have -

import http.client, urllib.request, urllib.parse, urllib.error, base64

MICROSOFT_CV_SUBSCRIPTION_KEY='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'

headers = {
   # Request headers
   'Content-Type': 'application/json',
   'Ocp-Apim-Subscription-Key': MICROSOFT_CV_SUBSCRIPTION_KEY,
}

params = urllib.parse.urlencode({
   'visualFeatures': 'Categories,Adult,Faces,Description,ImageType',
   'details': 'Celebrities',
   'language': 'en',
})

data = {
    'url':'http://img.wennermedia.com/article-leads-vertical-300/1250530894_brad_pitt_290x402.jpg',
}

try:
    conn = http.client.HTTPSConnection('api.projectoxford.ai')
    conn.request("POST", "/vision/v1.0/analyze?%s" % params, data, headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

But I am getting the following exception each time. Can someone help?

TypeError: unhashable type: 'slice' line 23, in conn.request("POST", "/vision/v1.0/analyze?%s" % params, data, headers)

TypeError: a bytes-like object is required, not 'str'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "D:/Users/aa/PycharmProjects/untitled/Demo2/ComputerVisionAPIDemo", line 29, in print("[Errno {0}] {1}".format(e.errno, e.strerror)) AttributeError: 'TypeError' object has no attribute 'errno'

1

1 Answers

1
votes

The body needs to be properly stringified:

conn.request("POST", "/vision/v1.0/analyze?%s" % params, str(data), headers)