forked from Vivek0712/blur-pii-aws-ai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pii-detect-blur.py
291 lines (218 loc) · 8.69 KB
/
pii-detect-blur.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import os
import boto3
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import io
from PIL import Image, ImageDraw, ImageFilter
import cv2
import math
import json
#### UTIL METHODS ####
def readImagefromS3(bucket, photo):
s3 = boto3.resource('s3', region_name='us-east-1')
bucket = s3.Bucket(bucket)
object = bucket.Object(photo)
response = object.get()
file_stream = response['Body']
image = Image.open(file_stream)
return image
def readImagefromLocal(filepath):
image = Image.open(filepath)
return image
def PILimageToBytes(image,form="PNG"):
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format=form)
img_byte_arr = img_byte_arr.getvalue()
return img_byte_arr
def uploadtoS3(localSourcefile, bucket, obj):
s3 = boto3.resource('s3')
s3.Bucket(bucket).upload_file(localSourcefile, obj)
def getS3ObjectURL(bucket,key):
s3 = boto3.client('s3')
url = s3.generate_presigned_url('get_object',
Params = {'Bucket': bucket, 'Key': key}, ExpiresIn = 600)
return url
def readTextfromS3(bucket,item):
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket)
obj = bucket.Object(item)
body = obj.get()['Body'].read().decode("utf-8")
return body
def readTextFromLocal(filepath):
f = open(filepath, "r")
body = f.read()
return body
def saveTextToLocal(text,filepath):
with open(filepath, 'w+') as f:
f.write(text)
def saveImageToLocal(image,filepath):
image.save(filepath)
#### HElPER METHODS #####
def redactPII_Text(entities, clean_text):
for NER in reversed(entities):
clean_text = clean_text[:NER['BeginOffset']] + "[" + NER['Type'] + "]" + clean_text[NER['EndOffset']:]
return clean_text
def blurmask(image,box):
imgWidth, imgHeight = image.size
left = imgWidth * box['Left']
top = imgHeight * box['Top']
width = imgWidth * box['Width']
height = imgHeight * box['Height']
mask = Image.new('L', image.size, 0)
draw = ImageDraw.Draw(mask)
draw.rectangle([left,top, left + width, top + height], fill=255)
blurred = image.filter(ImageFilter.GaussianBlur(52))
image.paste(blurred, mask=mask)
return image
def blurPII_Image(image, entities, boundingbox,text):
for NER in reversed(entities):
targetText = text[NER['BeginOffset']:NER['EndOffset']]
if targetText not in boundingbox.keys():
brokenstring = targetText.split(" ")
else:
brokenstring = []
brokenstring.append(targetText)
for targetText in brokenstring:
if targetText not in boundingbox.keys():
pass
else:
box = boundingbox[targetText]
image = blurmask(image,box)
return image
def detect_pii_from_text(text, language_code="en"):
comp_detect = boto3.client('comprehend')
entities =""
try:
response = comp_detect.detect_pii_entities(
Text=text, LanguageCode=language_code)
entities = response['Entities']
finally:
return entities
def detect_text_from_image(image):
client=boto3.client('rekognition')
response=client.detect_text(Image={
'Bytes': PILimageToBytes(image),
})
textDetections=response['TextDetections']
text_corpus = []
text_bounding_box = {}
for text in textDetections:
if text["Type"] == 'WORD':
text_corpus.append(text['DetectedText'])
text_bounding_box[text['DetectedText']] = text["Geometry"]["BoundingBox"]
final_text_corpus = " ".join(text_corpus)
return final_text_corpus,text_bounding_box
def detect_redact_pii_from_text(text):
entities = detect_pii_from_text(text)
clean_text = redactPII_Text(entities, text)
return clean_text
def detect_blur_pii_from_image(image):
text,text_bounding_box = detect_text_from_image(image)
entities = detect_pii_from_text(text)
blurredimage = blurPII_Image(image, entities, text_bounding_box,text)
return blurredimage
def detect_blur_pii_from_video(sourceVideopath,destVideoPath):
client=boto3.client('rekognition')
cap = cv2.VideoCapture(sourceVideopath)
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frame_count/fps
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(destVideoPath, fourcc, fps, (frame_width, frame_height))
frameRate = fps
while(cap.isOpened()):
frameId = cap.get(1) #current frame number
ret, frame = cap.read()
if (ret != True):
break
if (frameId % math.floor(frameRate) == 0):
hasFrame, imageBytes = cv2.imencode(".jpg", frame)
if(hasFrame):
image = Image.fromarray(np.uint8(frame)).convert('RGB')
blurredimage = detect_blur_pii_from_image(image)
open_cv_image = np.array(blurredimage)
out.write(open_cv_image)
cap.release()
out.release()
##### USAGE ######
"""
PII Content Format: Text
Source: Local File
"""
def redact_text_Local_File(sourceTextFilePath, DestTextFilePath):
textContent = readTextFromLocal(sourceTextFilePath)
PIIRedactText = detect_redact_pii_from_text(textContent)
saveTextToLocal(PIIRedactText, DestTextFilePath)
"""
PII Content Format: Text
Source: S3 Bucket
"""
def redact_text_S3_bucket(sourceS3bucket, sourceS3Object,destS3bucket, destS3Object):
textContent = readTextfromS3(sourceS3bucket,sourceS3Object)
PIIRedactText = detect_redact_pii_from_text(textContent)
saveTextToLocal(PIIRedactText, "sourceS3Object.txt")
uploadtoS3("sourceS3Object.txt", destS3bucket, destS3Object)
os.remove("sourceS3Object.txt")
"""
PII Content Format: Image
Source: Local File
"""
def blur_PII_image_Local_File(sourceImageFilePath, DestImageFilePath):
Sourceimage = readImagefromLocal(sourceImageFilePath)
blurredimage = detect_blur_pii_from_image(Sourceimage)
saveImageToLocal(blurredimage,DestImageFilePath)
"""
PII Content Format: Image
Source: S3 Bucket
"""
def blur_PII_image_S3_bucket(sourceS3bucket, sourceS3Object,destS3bucket, destS3Object):
Sourceimage = readImagefromS3(sourceS3bucket, sourceS3Object)
blurredimage = detect_blur_pii_from_image(Sourceimage)
tempimage = "temp"+ sourceS3Object.split("/")[-1]
saveImageToLocal(blurredimage,tempimage)
uploadtoS3(tempimage, destS3bucket, destS3Object)
os.remove(tempimage)
"""
PII Content Format: Video
Source: Local File
"""
def blur_PII_video_Local_File(sourceVideoFilePath, DestVideoFilePath, ):
detect_blur_pii_from_video(sourceVideoFilePath,DestVideoFilePath)
"""
PII Content Format: Video
Source: S3 Bucket
"""
def blur_PII_video_S3_bucket(sourceS3bucket, sourceS3Object,destS3bucket, destS3Object):
sourceVideoFilePath = getS3ObjectURL(sourceS3bucket, sourceS3Object)
tempvideo = "temp"+ sourceS3Object.split("/")[-1]
detect_blur_pii_from_video(sourceVideoFilePath,tempvideo)
uploadtoS3(tempvideo, destS3bucket, destS3Object)
os.remove(tempvideo)
##### DEMO ######
def PII_text_image_video_demo():
s3Bucket = "rek-pii"
## TEXT ##
sourceTextFilePath = "piitext.txt"
DestTextFilePath = "piitextredact.txt"
sourceS3Object = "media/text/source/piitext.txt"
destS3Object = "media/text/output/piitexts3.txt"
redact_text_Local_File(sourceTextFilePath, DestTextFilePath)
redact_text_S3_bucket(s3Bucket, sourceS3Object,s3Bucket, destS3Object)
## IMAGE ##
sourceImageFilePath = "rawimage.png"
DestImageFilePath = "piiblurredimage.png"
sourceS3Object = "media/image/source/rawimage.png"
destS3Object = "media/image/output/piiblurredimage.png"
blur_PII_image_Local_File(sourceImageFilePath, DestImageFilePath)
blur_PII_image_S3_bucket(s3Bucket, sourceS3Object,s3Bucket, destS3Object)
## VIDEO ##
sourceVideoFilePath = "rawvideo.mp4"
DestVideoFilePath = "piiblurredvideo.mp4"
sourceS3Object = "media/video/source/rawvideo.mp4"
destS3Object = "media/video/output/piiblurredvideo.mp4"
blur_PII_video_Local_File(sourceVideoFilePath, DestVideoFilePath)
blur_PII_video_S3_bucket(s3Bucket, sourceS3Object,s3Bucket, destS3Object)
PII_text_image_video_demo()