Eligoo
Eligoo

Reputation: 23

Using Project Oxford's Emotion API

I came across Project Oxford and became really interested in it and using its API, specifically the emotion one. Microsoft provides sample code

########### Python 2.7 #############
import httplib, urllib, base64

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

}

params = urllib.urlencode({
    # Request parameters
    'faceRectangles': '{string}',

})

try:
    conn = httplib.HTTPSConnection('api.projectoxford.ai')
    conn.request("POST", "/emotion/v1.0/recognize&%s" % params, "{body}", headers)
    response = conn.getresponse()
    data = response.read()
    print(data)
    conn.close()

except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

This doesn't contain the request body. I thought all I need to add was

body = {
    'url': 'url here',
}

and change

   conn.request("POST", "/emotion/v1.0/recognize&%s" % params, "{body}",headers)

to

conn.request("POST", "/emotion/v1.0/recognize&%s" % params, body, headers)

However that isn't working. I am getting this when I run it

Traceback (most recent call last):
File "C:/Users/User/Desktop/python/emotion.py", line 29, in <module>
print("[Errno {0}] {1}".format(e.errno, e.strerror))
AttributeError: 'exceptions.TypeError' object has no attribute 'errno'

Any help is much appreciated!

Upvotes: 2

Views: 1732

Answers (2)

Joining Dots
Joining Dots

Reputation: 186

The following works for me (Python 2.7), also based on the sample code provided by MSDN. You don't need to specify faceRectangles (unless you want to because they've already been detected, to save compute time).

import httplib, urllib, base64  

# Image to analyse (body of the request)

body = '{\'URL\': \'https://<path to image>.jpg\'}'

# API request for Emotion Detection

headers = {
   'Content-type': 'application/json',
}

params = urllib.urlencode({
   'subscription-key': '',  # Enter EMOTION API key
   #'faceRectangles': '',
})

try:
   conn = httplib.HTTPSConnection('api.projectoxford.ai')
   conn.request("POST", "/emotion/v1.0/recognize?%s" % params, body , headers)
   response = conn.getresponse()
   print("Send request")

   data = response.read()
   print(data)
   conn.close()
except Exception as e:
   print("[Errno {0}] {1}".format(e.errno, e.strerror))

Upvotes: 0

cthrash
cthrash

Reputation: 2973

You need to pass str(body) to the request.

Also, make sure to not include params if you don't have any face rectangles.

Upvotes: 3

Related Questions