-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathanalyzeVideo.py
246 lines (191 loc) · 8.49 KB
/
analyzeVideo.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
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#PDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-rekognition-developer-guide/blob/master/LICENSE-SAMPLECODE.)
import boto3
import json
import sys
import time
class VideoDetect:
jobId = ''
rek = boto3.client('rekognition')
sqs = boto3.client('sqs')
sns = boto3.client('sns')
roleArn = ''
bucket = ''
video = ''
startJobId = ''
sqsQueueUrl = ''
snsTopicArn = ''
processType = ''
def __init__(self, role, bucket, video):
self.roleArn = role
self.bucket = bucket
self.video = video
def GetSQSMessageSuccess(self):
jobFound = False
succeeded = False
dotLine=0
while jobFound == False:
print("SQS Queue ARN: ",self.sqsQueueUrl)
sqsResponse = self.sqs.receive_message(QueueUrl=self.sqsQueueUrl, MessageAttributeNames=['ALL'],
MaxNumberOfMessages=10)
if sqsResponse:
print("response: ", sqsResponse)
if 'Messages' not in sqsResponse:
if dotLine >= 5:
return True
if dotLine<40:
print('.')
dotLine=dotLine+1
else:
print()
dotLine=0
sys.stdout.flush()
time.sleep(5)
continue
for message in sqsResponse['Messages']:
notification = json.loads(message['Body'])
rekMessage = json.loads(notification['Message'])
print(rekMessage['JobId'])
print(rekMessage['Status'])
if rekMessage['JobId'] == self.startJobId:
print('Matching Job Found:' + rekMessage['JobId'])
jobFound = True
if (rekMessage['Status']=='SUCCEEDED'):
succeeded=True
self.sqs.delete_message(QueueUrl=self.sqsQueueUrl,
ReceiptHandle=message['ReceiptHandle'])
else:
print("Job didn't match:" +
str(rekMessage['JobId']) + ' : ' + self.startJobId)
# Delete the unknown message. Consider sending to dead letter queue
self.sqs.delete_message(QueueUrl=self.sqsQueueUrl,
ReceiptHandle=message['ReceiptHandle'])
return succeeded
def StartLabelDetection(self):
print("SNS ARN: ",self.snsTopicArn)
response=self.rek.start_label_detection(Video={'S3Object': {'Bucket': self.bucket, 'Name': self.video}},
NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn})
self.startJobId=response['JobId']
print('Start Job Id: ' + self.startJobId)
def GetLabelDetectionResults(self):
maxResults = 10
paginationToken = ''
finished = False
while finished == False:
response = self.rek.get_label_detection(JobId=self.startJobId,
MaxResults=maxResults,
NextToken=paginationToken,
SortBy='TIMESTAMP')
print('Codec: ' + response['VideoMetadata']['Codec'])
print('Duration: ' + str(response['VideoMetadata']['DurationMillis']))
print('Format: ' + response['VideoMetadata']['Format'])
print('Frame rate: ' + str(response['VideoMetadata']['FrameRate']))
print()
for labelDetection in response['Labels']:
label=labelDetection['Label']
print("Timestamp: " + str(labelDetection['Timestamp']))
print(" Label: " + label['Name'])
print(" Confidence: " + str(label['Confidence']))
print(" Instances:")
for instance in label['Instances']:
print (" Confidence: " + str(instance['Confidence']))
print (" Bounding box")
print (" Top: " + str(instance['BoundingBox']['Top']))
print (" Left: " + str(instance['BoundingBox']['Left']))
print (" Width: " + str(instance['BoundingBox']['Width']))
print (" Height: " + str(instance['BoundingBox']['Height']))
print()
print()
print (" Parents:")
for parent in label['Parents']:
print (" " + parent['Name'])
print ()
if 'NextToken' in response:
paginationToken = response['NextToken']
else:
finished = True
def CreateTopicandQueue(self):
millis = str(int(round(time.time() * 1000)))
#Create SNS topic
snsTopicName="AmazonRekognitionExample" + millis
topicResponse=self.sns.create_topic(Name=snsTopicName)
self.snsTopicArn = topicResponse['TopicArn']
#create SQS queue
sqsQueueName="AmazonRekognitionQueue" + millis
self.sqs.create_queue(QueueName=sqsQueueName)
self.sqsQueueUrl = self.sqs.get_queue_url(QueueName=sqsQueueName)['QueueUrl']
attribs = self.sqs.get_queue_attributes(QueueUrl=self.sqsQueueUrl,
AttributeNames=['QueueArn'])['Attributes']
sqsQueueArn = attribs['QueueArn']
# Subscribe SQS queue to SNS topic
self.sns.subscribe(
TopicArn=self.snsTopicArn,
Protocol='sqs',
Endpoint=sqsQueueArn)
#Authorize SNS to write SQS queue
policy = """{{
"Version":"2012-10-17",
"Statement":[
{{
"Sid":"MyPolicy",
"Effect":"Allow",
"Principal" : {{"AWS" : "*"}},
"Action":"SQS:SendMessage",
"Resource": "{}",
"Condition":{{
"ArnEquals":{{
"aws:SourceArn": "{}"
}}
}}
}}
]
}}""".format(sqsQueueArn, self.snsTopicArn)
response = self.sqs.set_queue_attributes(
QueueUrl = self.sqsQueueUrl,
Attributes = {
'Policy' : policy
})
def DeleteTopicandQueue(self):
self.sqs.delete_queue(QueueUrl=self.sqsQueueUrl)
self.sns.delete_topic(TopicArn=self.snsTopicArn)
# ============== Celebrities ===============
def StartCelebrityDetection(self):
response=self.rek.start_celebrity_recognition(Video={'S3Object': {'Bucket': self.bucket, 'Name': self.video}},
NotificationChannel={'RoleArn': self.roleArn, 'SNSTopicArn': self.snsTopicArn})
print("Celeb Response: ",response)
print("ROLE ARN: ", self.roleArn)
self.startJobId=response['JobId']
print('Start Job Id: ' + self.startJobId)
def GetCelebrityDetectionResults(self):
maxResults = 10
paginationToken = ''
finished = False
while finished == False:
response = self.rek.get_celebrity_recognition(JobId=self.startJobId,
MaxResults=maxResults,
NextToken=paginationToken)
print(response['VideoMetadata']['Codec'])
print(str(response['VideoMetadata']['DurationMillis']))
print(response['VideoMetadata']['Format'])
print(response['VideoMetadata']['FrameRate'])
for celebrityRecognition in response['Celebrities']:
print('Celebrity: ' +
str(celebrityRecognition['Celebrity']['Name']))
print('Timestamp: ' + str(celebrityRecognition['Timestamp']))
print()
if 'NextToken' in response:
paginationToken = response['NextToken']
else:
finished = True
def main():
roleArn = 'arn:aws:iam::408250821051:role/CelebRekognitionRole'
bucket = 'video-recognizer-bucket'
video = 'JawsScene1.mp4'
analyzer=VideoDetect(roleArn, bucket,video)
analyzer.CreateTopicandQueue()
analyzer.StartCelebrityDetection()
if analyzer.GetSQSMessageSuccess()==True:
pass
analyzer.GetCelebrityDetectionResults()
analyzer.DeleteTopicandQueue()
if __name__ == "__main__":
main()