Python - Microsoft Cognitive Verify API (params) - python

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:
https://github.com/Microsoft/Cognitive-Emotion-Python/blob/master/Jupyter%20Notebook/Emotion%20Analysis%20Example.ipynb
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.

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

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

There are a couple issues with your script:
You must pass face Ids and not URLs or file objects to the REST API.
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))

Related

In python, how can we connect to API using a certificate, subscription key?

I am trying to connect to an api for which I was provided with link, certificate(.p12) and subscription key.
Having some issue while giving the certificate details. I am trying in the following 2 ways:
1.
import json
from requests_pkcs12 import get,post
url = 'https://....'
pkcs12_filename = '<certificate file path>'
pkcs12_password = '<certificate password>'
headers = {
# Request headers
'Subscription-Key': '<subscription key>',}
response = post(url, headers=headers, verify=False, pkcs12_filename=pkcs12_filename,pkcs12_password=pkcs12_password)
print(response.status_code)
import http.client, urllib.request, urllib.parse, urllib.error, base64
#file = "<certificate path>"
headers = {
'Subscription-Key': '<subscriptionkey>',
#'cert' : crypto.load_pkcs12(open(file, 'rb').read(), "<password>").get_certificate(),
'file' : '<certificate path>',
'password':'<certificate password>',}
params = urllib.parse.urlencode({
})
conn = http.client.HTTPSConnection('<api main link>')
conn.request("GET", "<api remaining link>" , params, headers)
response = conn.getresponse()
data = response.read()
print("Status: {} and reason: {}".format(response.status, response.reason))
conn.close()
I am new to API concept. Will someone help me over this?
Refered to this link: How to use .p12 certificate to authenticate rest api
But didn't get what i need to put in data variable

"Bad Gateway" error using Python requests module with multipart encoded file POST

I am getting the error message "Bad Gateway
The proxy server received an invalid
response from an upstream server" with the following code:
import requests
url = "https://apis.company.com/v3/media"
attachments = 'media': ('x.mp3', open('x.mp3', 'r'))}
headers = {'content-type': "multipart/form-data",'cache-control': "no-cache"
'Authorization':"Bearer zzz" }
response = requests.post(url, files=attachments, headers = headers)
print response.text
I'm following the example in the requests Quickstart documentation, where it says "You can also pass a list of tuples to the data argument": http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file
What is causing this error and how can I fix it?
The main problem was that I set the content-type in the header. This code works:
import requests
url = 'https://apis.company.com/v3/media'
token = 'token-goes-here'
headers = { 'Authorization' : 'Bearer ' + token }
filename = 'x.mp3'
with open(filename, 'rb') as media_file:
attachments = {
'media': (filename, media_file, 'application/octet-stream')
}
response = requests.post(url, files = attachments, headers = headers)
print response.text

Python Requests - POST file with additional paramas

So I have this code that send API request to upload a file to a server, after searching the web I came up with something like that where 'payload' is additional params I need to send and 'files' is a path to the file I want to upload :
def sendAPIRequest2(self, env, object, method, params, files):
apiPath = "/api/secure/jsonws"
headers = {'content-type': 'multipart/form-data'}
url = env + apiPath + object
payload = {
"method": method,
"params": params,
"jsonrpc": "2.0"
}
data = json.dumps(payload)
myFile = {'file': open(files,'rb')}
try:
r = requests.post(url, files=myFile, data=data, headers=headers,
auth=HTTPBasicAuth(self.user, self.password), verify=False)
print r.text
resjson = json.loads(r.text)
except:
print "no Valid JSON has returned from"+object+" API"
sys.exit(1)
return resjson
I get:
ValueError: Data must not be a string.
What am I doing wrong?

How to refer a local file for Azure emotion api

I am trying to refer a local jpg file for using in Azure Emotion API.
To do this, I refer my file through "file:///" like below.
body = "{'url': 'file:///Users/jonghkim/dev_jhk/Research/Crowdfunding/Face_Analysis/me.jpg'}"
But the response says "Invalid image URL." How could I fix it?
{"error":{"code":"InvalidUrl","message":"Invalid image URL."}}
Whole code looks like below.
########### Python 2.7 #############
import httplib, urllib, base64
headers = {
# Request headers. Replace the placeholder key below with your subscription key.
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '***********************',
}
params = urllib.urlencode({
})
# Replace the example URL below with the URL of the image you want to analyze.
body = "{'url': 'file:///Users/jonghkim/dev_jhk/Research/Crowdfunding/Face_Analysis/me.jpg'}"
try:
conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')
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))
I solved this problem. The true reason was two fold. At first, when we refer local file, we should use 'Content-Type': 'application/octet-stream' in a header.
The second problem is that the image should satisfy the condition of Azure (learn.microsoft.com/ko-kr/azure/cognitive-services/emotion/fa‌​q).
Full code is here:
########### Python 2.7 #############
import httplib, urllib, base64
headers = {
# Request headers. Replace the placeholder key below with your subscription key.
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': '**************************',
}
params = urllib.urlencode({
})
# Replace the example URL below with the URL of the image you want to analyze.
body = open('test.jpg','rb').read()
conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/emotion/v1.0/recognize?%s" % params, body, headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
You're executing the emotion API within Cognitive Services - just take a look at the URI. This code is not being executed locally. It's a service. Being run somewhere else.
So, when the service gets the URL (via url in the body), it then needs to reach out to that resource, which is impossible to do if the resource is on your computer. And file:// is going to be an invalid scheme because the service won't be reading from its own file system.
You'll need to have your resource in an accessible place (e.g. a public or SAS-signed blob, an image link from a website, etc).

Invalid Subscription Key for python code but same key is working fine on westus.dev.cognitive.microsoft.com

I am just getting started with microsoft's computer vision OCR api, Subscription key and image url is working fine on https://westus.dev.cognitive.microsoft.com/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fc/console
But I am getting the following error when using the python code
{"statusCode": 401, "message": "Access denied due to invalid subscription key. Make sure to provide a valid key for an active subscription."}
I have tried my best to figure out the error but failed.
What am I doing wrong?
Thanks in advance.
import httplib, urllib, base64
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '{1111460aa78d4b27****************}',
}
params = urllib.urlencode({
# Request parameters
'language': 'unk',
'detectOrientation ': 'true',
})
try:
conn = httplib.HTTPSConnection('westus.api.cognitive.microsoft.com')
conn.request("POST", "/vision/v1.0/ocr?%s" % params, "{\"url\":\"https://s-media-cache-ak0.pinimg.com/originals/fb/e6/56/fbe65691cb66c6f035a859d9671c3fe5.jpg\"}", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
You need to drop the curly braces for the API key value, i.e.:
headers = {
# Request headers
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': '1111460aa78d4b27****************',
}

Categories

Resources