2

I'm trying to use the Microsoft Cognitive Verify API with python 2.7: https://dev.projectoxford.ai/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523a

The code is:

import httplib, urllib, base64

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

params = '{\'faceId1\': \'URL.jpg\',\'faceId2\': \'URL.jpg.jpg\'}'

try:
    conn = httplib.HTTPSConnection('api.projectoxford.ai')
    conn.request("POST", "/face/v1.0/verify?%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))

I tried letting the conn.request line like this:

conn.request("POST", "/face/v1.0/verify?%s" % params, "", headers)

The error is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request</h2>
<hr><p>HTTP Error 400. The request is badly formed.</p>
</BODY></HTML>

I alrealy tried to follow and make work the following codes:

  1. https://github.com/Microsoft/Cognitive-Emotion-Python/blob/master/Jupyter%20Notebook/Emotion%20Analysis%20Example.ipynb

  2. Using Project Oxford's Emotion API

However I just can't make this one work. I guess there is something wrong with the params or body argument. Any help is very appreciated.

Community
  • 1
  • 1
  • I think JSON format uses double quotes not single. I would try to change them in paramas. – Dawid Aug 11 '16 at 08:57

3 Answers3

1

You can refer to this question.

Obviously you did not understand the code. "{body}" means you should replace it with your body which contains your request url, just like the site says: enter image description here

So you can use this api this way:

body = {
            "url": "http://example.com/1.jpg"                          
       }
…………

conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/face/v1.0/detect?%s" % params, str(body), headers)
Community
  • 1
  • 1
YJ. Yang
  • 978
  • 2
  • 11
  • 19
0

Dawid's comment looks like it should fix it (double quoting), try this for python 2.7:

import requests

url = "https://api.projectoxford.ai/face/v1.0/verify"

payload = "{\n    \"faceId1\":\"A Face ID\",\n    \"faceId2\":\"A Face ID\"\n}"
headers = {
    'ocp-apim-subscription-key': "KEY_HERE",
    'content-type': "application/json"
    }

response = requests.request("POST", url, data=payload, headers=headers)

print(response.text)

for python 3:

import http.client

conn = http.client.HTTPSConnection("api.projectoxford.ai")

payload = "{\n\"faceId1\": \"A Face ID\",\n\"faceId2\": \"Another Face ID\"\n}"

headers = {
    'ocp-apim-subscription-key': "keyHere",
    'content-type': "application/json"
    }

conn.request("POST", "/face/v1.0/verify", payload, headers)

res = conn.getresponse()
data = res.read()
Ryan Galgon
  • 431
  • 1
  • 3
  • 9
  • Thanks @Dawid, @Ryan. I'm afraid it didn't work. I tried just as you say and it shows the error `ImportError: No module named http.client.` If I change to use `conn = httplib.HTTPSConnection('api.projectoxford.ai')` with the double quoting `payload = "{\n\"faceId1\": \"A Face ID\",\n\"faceId2\": \"Another Face ID\"\n}"` I get this error: `{"error":{"code":"BadArgument","message":"Face ID is invalid."}}` – Gustavo Rojo Blasquez Aug 13 '16 at 09:11
  • Sorry, I didn't notice you were using python 2.7. http.client is part of python 3. – Ryan Galgon Aug 16 '16 at 01:14
  • Also for completeness you'll you'll have to swap in the actual valid face id guid(s) you have, say from a previous /detect/ call – Ryan Galgon Aug 16 '16 at 01:20
  • Formatting tip... Use triple quotes/apostrophes (ala docstrings) to enclose complex literals.... `payload = '''{"faceId1": "URL.jpg", ...}'''` – Basic Aug 16 '16 at 01:31
0

There are a couple issues with your script:

  1. You must pass face Ids and not URLs or file objects to the REST API.
  2. You must correctly formulate the HTTP request.

However, you may find it easier to use the Python API and not the REST API. For example, once you have the face ids, you can just run result = CF.face.verify(faceid1, another_face_id=faceid2) instead of worrying about setting up the correct POST request.

You will probably need to install cognitive_face with pip. I use this API to get the face Ids for some bonus instruction.

To make this simpler, let's assume you have img1.jpg and img2.jpg on disk.

Here is an example using the REST API:

import cognitive_face as CF
from io import BytesIO
import json
import http.client

# Setup
KEY = "your subscription key"


# Get Face Ids
def get_face_id(img_file):
    f = open(img_file, 'rb')
    data = f.read()
    f.close()
    faces = CF.face.detect(BytesIO(data))

    if len(faces) != 1:
        raise RuntimeError('Too many faces!')

    face_id = faces[0]['faceId']
    return face_id


# Initialize API
CF.Key.set(KEY)

faceId1 = get_face_id('img1.jpg')
faceId2 = get_face_id('img2.jpg')


# Now that we have face ids, we can setup our request
headers = {
    # Request headers
    'Content-Type': 'application/json',
    'Ocp-Apim-Subscription-Key': KEY
}

params = {
    'faceId1': faceId1,
    'faceId2': faceId2
}

# The Content-Type in the header specifies that the body will
# be json so convert params to json
json_body = json.dumps(params)

try:
    conn = httplib.HTTPSConnection('https://eastus.api.cognitive.microsoft.com')
    conn.request("POST", "/face/v1.0/verify", body=json_body, headers=headers)
    response = conn.getresponse()
    data = response.read()
    data = json.loads(data)
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))