-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfacematch.py
More file actions
executable file
·140 lines (115 loc) · 4.38 KB
/
facematch.py
File metadata and controls
executable file
·140 lines (115 loc) · 4.38 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
#!/usr/bin/env python
import boto3 as b3
import pygame, StringIO
import sys, traceback
import time
from argparse import ArgumentParser
from time import gmtime, strftime
from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
def get_client():
return b3.client('rekognition')
def greeting_time():
currentTime = int(time.strftime('%H:%M').split(':')[0])
greetingItem=''
if currentTime < 12 :
greetingItem='Good morning'
elif currentTime > 12 :
greetingItem='Good afternoon'
else :
greetingItem='Good evening'
return greetingItem
def get_args():
parser = ArgumentParser(description='Compare an image')
parser.add_argument('-i', '--image')
parser.add_argument('-c', '--collection')
return parser.parse_args()
def check_face(client, file):
face_detected = False
with open(file, 'rb') as image:
response = client.detect_faces(Image={'Bytes': image.read()})
if (not response['FaceDetails']):
face_detected = False
else:
face_detected = True
return face_detected, response
def check_matches(client, file, collection):
face_matches = False
with open(file, 'rb') as image:
response = client.search_faces_by_image(CollectionId=collection, Image={'Bytes': image.read()}, MaxFaces=1, FaceMatchThreshold=85)
if (not response['FaceMatches']):
face_matches = False
else:
face_matches = True
return face_matches, response
def main():
args = get_args()
client = get_client()
print '[+] Running face checks against image...'
result, resp = check_face(client, args.image)
import sys, traceback
# Test code
debugging = False
try:
if (result):
print '[+] Face(s) detected with %r confidence...' % (round(resp['FaceDetails'][0]['Confidence'], 2))
print '[+] Checking for a face match...'
resu, res = check_matches(client, args.image, args.collection)
if (resu):
greet=greeting_time()
speak = greet + "%s" % (res['FaceMatches'][0]['Face']['ExternalImageId'])
synthesizer = VoiceSynthesizer(0.9)
synthesizer.say(speak)
else:
print '[-] No face matches detected...'
else :
print "[-] No faces detected..."
# synthesizer = VoiceSynthesizer(0.1)
# synthesizer.say("Hi Renjith.")
except:
print "exception occurred!"
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=5, file=sys.stdout)
class VoiceSynthesizer(object):
def __init__(self, volume=0.1):
pygame.mixer.init()
self._volume = volume
session = Session(profile_name="default")
self.__polly = session.client("polly")
def _getVolume(self):
return self._volume
def say(self, text):
self._synthesize(text)
def _synthesize(self, text):
# Implementation specific synthesis
try:
# Request speech synthesis
response = self.__polly.synthesize_speech(Text=text,
OutputFormat="ogg_vorbis",VoiceId="Joanna")
except (BotoCoreError, ClientError) as error:
# The service returned an error
print(error)
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback,
limit=5, file=sys.stdout)
# Access the audio stream from the response
if "AudioStream" in response:
# Note: Closing the stream is important as the service throttles on the
# number of parallel connections. Here we are using contextlib.closing to
# ensure the close method of the stream object will be called automatically
# at the end of the with statement's scope.
with closing(response["AudioStream"]) as stream:
data = stream.read()
filelike = StringIO.StringIO(data) # Gives you a file-like object
sound = pygame.mixer.Sound(file=filelike)
sound.set_volume(self._getVolume())
sound.play()
while pygame.mixer.get_busy() == True:
continue
else:
# The response didn't contain audio data, exit gracefully
print("Could not stream audio - no audio data in response")
if __name__ == '__main__':
main()