-
Notifications
You must be signed in to change notification settings - Fork 0
/
emotion.py
97 lines (70 loc) · 2.54 KB
/
emotion.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import time
import requests
import cv2
import operator
import numpy as np
# The emotion list
emotions = [
'sadness',
'happiness',
'disgust',
'anger',
'surprise',
'fear',
'neutral',
'contempt'
]
# Import library to display results
# Display images within Jupyter
# Variables
_url = 'https://westus.api.cognitive.microsoft.com/emotion/v1.0/recognize'
_key = '2cf0098356e243dcaeffefe42307109a'
_maxNumRetries = 10
def processRequest( json, data, headers, params ):
"""
Helper function to process the request to Project Oxford
Parameters:
json: Used when processing images from its URL. See API Documentation
data: Used when processing image read from disk. See API Documentation
headers: Used to pass the key information and the data type request
"""
retries = 0
result = None
while True:
response = requests.request( 'post', _url, json = json, data = data, headers = headers, params = params )
if response.status_code == 429:
print( "Message: %s" % ( response.json()['error']['message'] ) )
if retries <= _maxNumRetries:
time.sleep(1)
retries += 1
continue
else:
print( 'Error: failed after retrying!' )
break
elif response.status_code == 200 or response.status_code == 201:
if 'content-length' in response.headers and int(response.headers['content-length']) == 0:
result = None
elif 'content-type' in response.headers and isinstance(response.headers['content-type'], str):
if 'application/json' in response.headers['content-type'].lower():
result = response.json() if response.content else None
elif 'image' in response.headers['content-type'].lower():
result = response.content
else:
print( "Error code: %d" % ( response.status_code ) )
print( "Message: %s" % ( response.json()['error']['message'] ) )
break
return result
# FROM WEBPAGE
# ============
def imageRequest(url):
# Load raw image file into memory
pathToFileInDisk = url
with open( pathToFileInDisk, 'rb' ) as f:
data = f.read()
headers = dict()
headers['Ocp-Apim-Subscription-Key'] = _key
headers['Content-Type'] = 'application/octet-stream'
json = None
params = None
return processRequest( json, data, headers, params )
#print(imageRequest('/home/chrishittner/Desktop/sample.jpg'))