Python Microsoft认知验证API(params)

2024-04-23 14:53:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在python2.7中使用microsoftcognitiveverifyapi:https://dev.projectoxford.ai/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f3039523a

代码是:

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))

我试着让连接请求像这样的线条:

^{pr2}$

错误是:

<!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>

我一直努力遵循以下准则:

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

  2. Using Project Oxford's Emotion API

但是我不能让这一个成功。我想参数或体参数有问题。 非常感谢任何帮助。在


Tags: httpsurlresponserequesthtmltypeparamscontent
3条回答

你的脚本有几个问题:

  1. 必须向restapi传递faceids,而不是url或file对象。在
  2. 您必须正确地构造HTTP请求。在

但是,您可能会发现使用Python API比使用restapi更容易。例如,一旦有了faceid,就可以运行result = CF.face.verify(faceid1, another_face_id=faceid2),而不用担心设置正确的POST请求。在

您可能需要使用pip安装cognitive_face。我使用这个API来获取一些奖金指令的面部ID。在

为了简化这一点,我们假设磁盘上有img1.jpg和img2.jpg。在

下面是使用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))

您可以参考this question。在

很明显你不明白密码。"{body}"意味着您应该将其替换为包含您的请求url的body,就像网站上说的那样: enter image description here

因此,可以通过以下方式使用此api:

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)

Dawid的评论看起来应该修复它(双引号),在python2.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)

对于python 3:

^{pr2}$

相关问题 更多 >