【问题标题】:Python - Microsoft Cognitive Verify API (params)Python - Microsoft 认知验证 API(参数)
【发布时间】:2018-11-02 11:23:25
【问题描述】:

我正在尝试将 Microsoft Cognitive Verify API 与 python 2.7 一起使用: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))

我试着让 conn.request 像这样:

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

错误是:

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

但是我就是不能让这个工作。我猜 params 或 body 参数有问题。 非常感谢任何帮助。

【问题讨论】:

  • 我认为 JSON 格式使用双引号而不是单引号。我会尝试在 paramas 中更改它们。

标签: python microsoft-cognitive


【解决方案1】:

您可以参考this question

显然你没有看懂代码。 "{body}" 表示您应该将其替换为包含您的请求 url 的正文,就像该网站说的那样:

所以你可以这样使用这个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)

【讨论】:

    【解决方案2】:

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

    对于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()
    

    【讨论】:

    • 谢谢@Dawid,@Ryan。恐怕它没有用。我按照您说的尝试了,它显示错误ImportError: No module named http.client. 如果我更改为使用conn = httplib.HTTPSConnection('api.projectoxford.ai') 和双引号payload = "{\n\"faceId1\": \"A Face ID\",\n\"faceId2\": \"Another Face ID\"\n}",我会收到此错误:{"error":{"code":"BadArgument","message":"Face ID is invalid."}}
    • 抱歉,我没有注意到您使用的是 python 2.7。 http.client 是 python 3 的一部分。
    • 另外,为了完整起见,您必须换入您拥有的实际有效的人脸 id guid,例如之前的 /detect/ 调用
    • 格式化提示...使用三引号/撇号(ala docstrings)将复杂的文字括起来...payload = '''{"faceId1": "URL.jpg", ...}'''
    【解决方案3】:

    您的脚本有几个问题:

    1. 您必须将 face Ids 而不是 URL 或文件对象传递给 REST API。
    2. 您必须正确制定 HTTP 请求。

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

    您可能需要安装cognitive_facepip。我使用这个 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 2018-12-02
      • 2017-05-11
      • 2022-10-31
      • 1970-01-01
      • 2019-04-11
      相关资源
      最近更新 更多