-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
61 lines (50 loc) · 1.9 KB
/
app.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
import random, os, io, base64
from flask import Flask, render_template, request, jsonify
from azure.cognitiveservices.vision.face import FaceClient
from msrest.authentication import CognitiveServicesCredentials
credentials = CognitiveServicesCredentials(os.environ['face_api_key'])
face_client = FaceClient(os.environ['face_api_endpoint'], credentials=credentials)
def best_emotion(emotion):
emotions = {}
emotions['anger'] = emotion.anger
emotions['contempt'] = emotion.contempt
emotions['disgust'] = emotion.disgust
emotions['fear'] = emotion.fear
emotions['happiness'] = emotion.happiness
emotions['neutral'] = emotion.neutral
emotions['sadness'] = emotion.sadness
emotions['surprise'] = emotion.surprise
return max(zip(emotions.values(), emotions.keys()))[1]
app = Flask(__name__)
emotions = ['anger','contempt','disgust','fear','happiness','sadness','surprise']
@app.route('/')
def home():
page_data = {
'emotion' : random.choice(emotions)
}
return render_template('home.html', page_data = page_data)
@app.route('/result', methods=['POST'])
def check_results():
body = request.get_json()
desired_emotion = body['emotion']
image_bytes = base64.b64decode(body['image_base64'].split(',')[1])
image = io.BytesIO(image_bytes)
faces = face_client.face.detect_with_stream(image,
return_face_attributes=['emotion'])
if len(faces) == 1:
detected_emotion = best_emotion(faces[0].face_attributes.emotion)
if detected_emotion == desired_emotion:
return jsonify({
'message': '✅ You won! You showed ' + desired_emotion
})
else:
return jsonify({
'message': '❌ You failed! You needed to show ' +
desired_emotion +
' but you showed ' +
detected_emotion
})
else:
return jsonify({
'message': '☠️ ERROR: No faces detected'
})