-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdraft.py
298 lines (252 loc) · 10.3 KB
/
draft.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
292
293
import cv2
import pytesseract
import re
import numpy as np
from PIL import Image
import streamlit as st
st.markdown(
"""
<style>
.stApp{
background-color: #1f2b2b;
color: #E5E5E5;
}
html, body, [class*="css"] {
color: #E5E5E5 !important;
}
header[data-testid="stHeader"] {
background-color: #1f2b2b;
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 1rem;
}
.nav-buttons {
display: flex;
gap: 1rem;
}
.nav-buttons a {
text-decoration: none;
color: #1f2b2b;
background-color: #E5E5E5;
padding: 0.5rem 1rem;
border-radius: 5px;
font-weigth: bold;
transition: background-color 0.3s,color 0.3s;
}
.nav-buttons a:hover {
background-color: #1f2b2b;
color: #e5E5E5;
}
</style>
<header data-testid="stHeader">
<div class="nav-buttons">
<a href="/?nav=home">Home</a>
<a href="/?nav=about">About Us</a>
</div>
</header>
"""
)
st.title("PII shield")
# query_params = st.experimental_get_query_params()
# nav = query+params.get("nav" , ["home"])[0]
# if nav == "home":
st.title("Home")
st.write("Welcome to the Home Page!")
st.write("Our solution for the PII shield involves a robust software application designed to scan and detect government issued PII in documents or data.Uses Regular expression (Regex) patterns to identify PII in Aadhaar cards, PAN, Driving Lincense, etc. Allows user to redact or mask PII to ensure privacy compliance.")
# elif nav == "about":
st.title("About Us")
st.title("Learn more about us on this page")
st.title("Who are we?")
st.write("We are an enthusiastic team of learners and innovators, starting our journey to help individuals and businesses safeguard their sensitive information in the digital age. With a growing passion for data security,and privacy protection, we are committed to building simple, effective tools that make privacy management accessible to everyone. ")
st.write("Our Mission")
st.write("Our mission is to create effective and easy-to-use tools that help safeguard Personally Identifiable Information (PII). As beginners, we are dedicated to developing solutions for detecting, masking, and alerting users about sensitive information, making privacy protection simple, accessible, and reliable for everyone.")
pytesseract.pytesseract.tesseract_cmd= r"C:\Program Files\Tesseract-OCR\tesseract.exe"
face_cascade=cv2.CascadeClassifier(cv2.data.haarcascades+ "haarcasade_frontalface_default.xml")
def extract_aadhaar_number (text):
aadhaar_pattern =r"\b\d{4}[- ]?\d{4}[- ]?\d{4}\b"
match = re.search(aadhaar_pattern,text)
return match.group (0) if match else None
def extract_pan_number(text):
pan_pattern= r"\b[A-Z]{5}\d{4}[A-Z]\b"
match= re.search(pan_pattern, text)
return match.group (0) if match else None
def extract_voter_id(text):
voter_id_pattern = r"\b[A-Z]{3}\d{7}\b"
match = re.search(voter_id_pattern, text)
return match.group (0) if match else None
def extract_driving_license(text):
dl_pattern = r"\b[A-Z]{2}[- ]?\d{2}[- ]?\d{7,13}\b"
match = re.search(dl_pattern, text)
return match.group (0) if match else None
def extract_dob(text):
dob_pattern = r"\b\d{2}/\d{2}/\d{4}\b"
match = re.search(dob_pattern, text)
return match.group (0) if match else None
def extract_address(text):
lines = text.split('\n')
address_block=[]
address_started = False
for line in lines:
if "Address" in line or "पता" in line:
address_started = True
if address_started:
address_block.append(line.strip())
if len(address_block) >=4:
break
address = " ".join(address_block).replace("Address","").replace("पता","").strip()
return address if address else None
def mask_aadhaar_number (img,aadhaar_number):
text_data = pytesseract.image_to_data(img, output_type =pytesseract.output.DICT)
for i,word in enumerate (text_data["text"]):
if word in aadhaar_number and len(word)==4:
x,y,w,h= (
text_data["left"][i],
text_data["top"][i],
text_data["width"][i],
text_data["height"][i],
)
img =cv2.rectangle(img, (x, y) , (x + w, y + h ), (0, 0, 0), -1)
return img
def mask_pan_number (img,pan_number):
text_data = pytesseract.image_to_data(img, output_type =pytesseract.output.DICT)
for i,word in enumerate (text_data["text"]):
if word ==pan_number:
x,y,w,h= (
text_data["left"][i],
text_data["top"][i],
text_data["width"][i],
text_data["height"][i],
)
img =cv2.rectangle(img , (x, y) , (x + w, y + h) , (0, 0, 0) , -1)
return img
def mask_voter_id (img,voter_id):
text_data = pytesseract.image_to_data(img, output_type =pytesseract.output.DICT)
for i,word in enumerate (text_data["text"]):
if word ==voter_id:
x,y,w,h= (
text_data["left"][i],
text_data["top"][i],
text_data["width"][i],
text_data["height"][i],
)
img =cv2.rectangle(img , (x,y) , (x+w,y+h) , (0,0,0) , -1)
return img
def mask_driving_license (img,driving_license):
text_data = pytesseract.image_to_data(img, output_type =pytesseract.output.DICT)
for i , word in enumerate (text_data["text"]):
if word ==driving_license:
x,y,w,h = (
text_data["left"][i],
text_data["top"][i],
text_data["width"][i],
text_data["height"][i],
)
img =cv2.rectangle(img , (x,y) , (x+w,y+h) , (0,0,0) , -1)
return img
def mask_text (img,text_to_mask):
text_data = pytesseract.image_to_data( img, output_type =pytesseract.output.DICT)
for i, word in enumerate (text_data["text"]):
if text_to_mask in word:
x,y,w,h = (
text_data["left"][i],
text_data["top"][i],
text_data["width"][i],
text_data["height"][i],
)
img =cv2.rectangle(img , (x,y) , (x+w,y+h) , (0,0,0) , -1)
return img
def mask_address (img,address):
text_data = pytesseract.image_to_data(img, output_type =pytesseract.output.DICT)
coords=[]
for i , word in enumerate (text_data["text"]):
if word.strip() in address and len(word.strip()) > 1:
x, y, w, h = (
text_data["left"][i],
text_data["top"][i],
text_data["width"][i],
text_data["height"][i],
)
coords.append((x , y , x + w , y + h))
if not coords:
return img
coords=np.array(coords)
img=cv2.rectangle(img, (coords[:, 0].min(), coords[:, 1].min()),
(coords[:, 2].max(), coords[:, 3].max()), (0, 0, 0), -1)
return img
def blur_faces(img):
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray_img, scalefactor=1.1, minNeighbors=5, minSize=(30, 30))
for (x, y, w, h) in faces:
face=img[y:y+h, x:x+w]
blurred_face=cv2.GaussianBlur(face, (51,51), 30)
img[y:y+h,x:x+w]=blurred_face
return img
st.title("Document Details Extractor & Masker")
st.write("Upload an image to extract Aadhaar, PAN, Voter ID, Driving License numbers, DOB details, and optionally mask them along with face blurring.")
uploaded_file = st.file_uploader("Choose an image", type=["png", "jpg", "jpeg"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
img_array = np.array(image)
#img_array = cv2.erode(img_array, kernel=np.ones((2,1)), iterations=1)
img_rgb = img_array.copy()
extracted_text = pytesseract.image_to_string(img_array)
aadhaar_number = extract_aadhaar_number(extracted_text)
pan_number = extract_pan_number(extracted_text)
voter_id = extract_voter_id(extracted_text)
driving_license = extract_driving_license(extracted_text)
dob = extract_dob(extracted_text)
address=extract_address(extracted_text)
st.write("Extracted Information: ")
extracted_info = {}
if aadhaar_number:
st.success(f"Aadhaar Number: {aadhaar_number}")
extracted_info["Aadhaar Number"] = aadhaar_number
if pan_number:
st.success(f"PAN Number: {pan_number}")
extracted_info["PAN Number"] = pan_number
if voter_id:
st.success(f"Voter ID: {voter_id}")
extracted_info["Voter ID"] = voter_id
if driving_license:
st.success(f"Driving License: {driving_license}")
extracted_info["Driving License"] = driving_license
if dob:
st.success(f"Date of Birth: {dob}")
extracted_info["Date of Birth"] = dob
if address:
st.success(f"Address: {address}")
extracted_info["Address"] = address
extracted_info["Blur Faces"] = "Yes"
if extracted_info:
selected_pii = st.multiselect(
"Select the PII to Mask or Blur",
options=extracted_info.keys(),
default=list(extracted_info.keys())
)
if st.button("Apply Masking"):
for pii_type in selected_pii:
if pii_type == "Aadhaar Number":
img_rgb = mask_aadhaar_number(img_rgb, extracted_info[pii_type])
elif pii_type == "PAN Number":
img_rgb = mask_pan_number(img_rgb, extracted_info[pii_type])
elif pii_type == "Voter ID":
img_rgb = mask_voter_id(img_rgb, extracted_info[pii_type])
elif pii_type == "Driving License":
img_rgb = mask_driving_license(img_rgb, extracted_info[pii_type])
elif pii_type == "Date of Birth":
img_rgb = mask_text(img_rgb, extracted_info[pii_type])
elif pii_type == "Address":
img_rgb = mask_address(img_rgb, extracted_info[pii_type])
elif pii_type=="Blur Faces":
img_rgb = blur_faces(img_rgb)
masked_pil = Image.fromarray(img_rgb)
st.image(masked_pil, caption="Masked and Blurred Image", use_container_width = True)
masked_pil.save("masked_image.png")
with open("masked_image.png", "rb") as file:
st.download_button(
label="Download Masked and Blurred Image",
data=file,
file_name="masked_image.png",
mime="image/png",
)