Microsoft Emotion API for video with Python - python

I'm using the following code to send my video and apparently I got no error. But the response is coming blank. How can I read the response?
########### Python 2.7 #############
import httplib, urllib, base64, json
headers = {
# Request headers
'Ocp-Apim-Subscription-Key': 'xxxxxxxxxxxxxxxxxxxx',
'Content-Type': 'application/json'
}
video_filename = {"url":"https://fsarquivoeastus.blob.core.windows.net/public0/WhatsApp-Video-20160727.mp4"}
params = urllib.urlencode({})
try:
conn = httplib.HTTPSConnection('api.projectoxford.ai')
conn.request("POST", "/emotion/v1.0/recognizeinvideo?%s" % params, json.dumps(video_filename), headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))

The Cognitive Service Video APIs, including Emotion, operate asynchronously, and by design return an empty response body when the POST succeeds. What you must do instead is retrieve the operation URL from the headers, as shown here:
response = conn.getresponse()
location = response.getheader('operation-location');
print(location);
You call GET on that location URL to check on the status of the operation. More on that here.

#FelipeSouzaLima, To getting the operation result from Emotion Recognition in Video, you need to do two steps as below.
Call the REST API for Emotion Recognition in Video, then you will get the blank response body and the operation-location header which will be called at the next step as #cthrash said.
Call the url of the value of operation-location header above with the same Ocp-Apim-Subscription-Key as request header, then you can get the json response body which includes the recognition job status. If the value of status field in the json response is Succeeded, you will get the operation result as processingResult field in the json result, please refer to the REST API of Get Recognition in Video Operation Result.

Related

I need to perform a GET Request on a URL using python requests library and fetch only the last 100 lines

Summary:
Currently i am doing a GET Request on a {.log} URL which is having around 7000+ lines.
I need to GET the Response, validate for a particular message in the response and if its not present, i need to do a GET Request again on the same URL.
This iteration on the GET is very time consuming and most of the time results in a stuck state
Expectation:
I need a way out wherein i do a GET Request operation and fetch only last 100 lines as a response rather than fetching all the 7000+ lines every time.
URL = "http://sdd.log"
Code
def get_log(self):
logging.info("Sending a get request to retrieve pronghorn log")
resp = requests.request("GET", "http://ssdg.log")
logging.info("Printing the callback url response")
#logging.info(resp)
#logging.info(resp.text)
return resp.text
You cannot simply download only the last 100 lines of an HTTP request. You can however simply get the last 100 lines of the resulting response by using
data = resp.text.split('\n')
last_lines = '\n'.join(data[-100:])
return last_lines
So, if your server accepts range requests then you can use code like this to get the last 4096 bytes
import requests
from io import BytesIO
url = 'https://file-examples.com/wp-content/uploads/2017/10/file_example_JPG_100kB.jpg'
resp = requests.request("HEAD", url)
unit = resp.headers['Accept-Ranges']
print(resp.headers['Content-Length'])
print(unit)
headers = {'Range': f'{unit}=-4096'}
print(headers)
resp = requests.request("GET", url, headers=headers)
b = BytesIO()
for chunk in resp.iter_content(chunk_size=128):
b.write(chunk)
print(b.tell())
b.seek(0)
data = b.read()
print(f"len(data): {len(data)}")

Python How to GET Image and then POST (via requests library)

I am using python to try and get an image from one API, and then post it to a separate API.
So far I have this code:
def create_item(token, user_id):
url = '<api_url_to_post_to>'
headers = {"Authorization": "Token {0}".format(token)}
image_url = '<some_random_image_url>'
image_obj = requests.get(image_url)
data = {
"image": image_obj.content
}
r = requests.post(url, headers=headers, files=data)
response = r.json()
print(response)
return response
The issue is that when I try to post it to the second API, I get a "File extension '' is not allowed." error. This is obviously a custom error message, but it signifies that there is something wrong with the file that I am posting.
Any suggestions on what I may be doing wrong?
Try specifying the file type, just image_obj.content is the raw binary image:
r = requests.post(
url,
headers=headers,
files={'image': ('my_image.jpg', image_obj.content, 'image/jpg')})
This should add the correct headers to the multipart boundary for the image.
If you don't know for sure the content type, you might actually get it from the headers of your previous response: image_obj.headers['Content-Type'] should be "image/jpg" but for a different image it might be "image/png".
It wants a file extension, I'd hazard a guess that image should be image.<SOME_FORMAT>.

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

Python HTTP request: no adapters found

I'm trying to generate an http(s) request via Python Requests however I'm running into a problem:
No connection adapters were found for 'set(['http://www.example.com/target'])'
I'm attempting to make the connection like so:
url = ['http://www.example.com/target']
headers = {"Content-Type":"application/json"}
ver = False;
message = { bunch of json data }
curl_request(url,message,headers,ver)
With the curl_request API call being:
# API call to perform curl request and return resulting json status
def curl_request(url,message,headers,ver):
requests.post(url, data=json.dumps(message), verify=ver, headers=headers)
data = response.json()
return data
Use a string, not a set.
url = 'http://www.example.com/target'

How to access the list of Azure AD Groups using python?

I'm new to python. I found the following sample code to retrieve the Azure AD groups from https://msdn.microsoft.com/en-us/Library/Azure/Ad/Graph/api/groups-operations#BasicoperationsongroupsGetgroups
the code is:
########### Python 3.2 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64
# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
headers = {}
params = urllib.parse.urlencode({
# Specify values for the following required parameters
'api-version': '1.5',
})
try:
conn = http.client.HTTPSConnection('graph.windows.net')
#Specify values for path parameters (shown as {...}) and request body if needed
conn.request("GET", "/myorganization/groups?%s" % params, "", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
####################################
everything is fine but i don't know what would be the value of "headers = {}".
I need help i spent a lot of hours on this but no luck yet.
Base on my understanding, you need to write the Oauth Authorization information into headers, like the code below:
headers = {
#set your access token
'Authorization':'your access token'
}
Before you accessing the Graph API, you need to get the access token form AD. You can add the authorization information into your headers and request.
About how to get the access token, I suggest that you can refer to this page:
Active Directory -Authentication Scenarios

Categories

Resources