RajaThor commited on
Commit
14ea48a
·
verified ·
1 Parent(s): 97dcb68

Upload 7 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ shape_predictor_68_face_landmarks.dat filter=lfs diff=lfs merge=lfs -text
Add.png ADDED
Explore+.png ADDED
Explore.png ADDED
app.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ import firebase_admin
4
+ from firebase_admin import credentials, db, auth
5
+ import face_recognition
6
+ from PIL import Image
7
+ import numpy as np
8
+ import cv2
9
+ import dlib
10
+
11
+ # Get the current working directory
12
+ current_directory = os.path.dirname(os.path.abspath(__file__))
13
+ skp_path = os.path.join(current_directory, "data-2b2e6-firebase-adminsdk-w4rgg-31b7778252.json")
14
+
15
+ # Check if the app is already initialized
16
+ if not firebase_admin._apps:
17
+ # Initialize Firebase Admin SDK
18
+ cred = credentials.Certificate(skp_path)
19
+ firebase_admin.initialize_app(cred, {
20
+ 'databaseURL': 'https://data-2b2e6-default-rtdb.firebaseio.com/',
21
+ 'projectId': 'data-2b2e6'
22
+ })
23
+
24
+ # Reference to the root of your Firebase Realtime Database
25
+ ref = db.reference('/')
26
+
27
+ # Streamlit session state
28
+ if "auth_state" not in st.session_state:
29
+ st.session_state.auth_state = {
30
+ "user": None,
31
+ "signed_in": False,
32
+ }
33
+
34
+ # Add the shape predictor model for face alignment
35
+ shape_predictor_path = "shape_predictor_68_face_landmarks.dat"
36
+ detector = dlib.get_frontal_face_detector()
37
+ shape_predictor = dlib.shape_predictor(shape_predictor_path)
38
+
39
+ # Firebase Authentication
40
+ def authenticate_user(email, password):
41
+ try:
42
+ user = auth.get_user_by_email(email)
43
+ # The user is successfully fetched, meaning the email and password are valid.
44
+ return True, user
45
+ except auth.AuthError as e:
46
+ print(f"Authentication error: {str(e)}")
47
+ return False, None
48
+
49
+ # Sign-up Functionality
50
+ def create_user(email, password):
51
+ try:
52
+ user = auth.create_user(
53
+ email=email,
54
+ password=password
55
+ )
56
+ return True, user.uid
57
+ except Exception as e:
58
+ print(f"User creation error: {str(e)}")
59
+ return False, None
60
+
61
+ # Update load_and_encode function to use the aligned face without normalization
62
+ def load_and_encode(image_path):
63
+ try:
64
+ aligned_face = detect_and_align_faces(image_path)
65
+
66
+ if aligned_face is not None:
67
+ encoding = face_recognition.face_encodings(aligned_face)
68
+
69
+ if encoding:
70
+ return encoding
71
+ else:
72
+ return None
73
+ else:
74
+ return None
75
+ except Exception as e:
76
+ print(f"Error loading and encoding image: {str(e)}")
77
+ return None
78
+
79
+ # Function to detect and align faces in an image with preprocessing
80
+ def detect_and_align_faces(image_path):
81
+ image = face_recognition.load_image_file(image_path)
82
+
83
+ # Resize the image to a fixed width (you can adjust the width as needed)
84
+ target_width = 800
85
+ aspect_ratio = image.shape[1] / image.shape[0]
86
+ target_height = int(target_width / aspect_ratio)
87
+ resized_image = cv2.resize(image, (target_width, target_height))
88
+
89
+ gray = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)
90
+
91
+ # Detect faces using dlib
92
+ faces = detector(gray)
93
+
94
+ if not faces:
95
+ return None
96
+
97
+ # Use the first face found (you can modify this to handle multiple faces)
98
+ face = faces[0]
99
+
100
+ # Use dlib for face alignment
101
+ landmarks = shape_predictor(gray, face)
102
+ aligned_face = dlib.get_face_chip(resized_image, landmarks, size=256) # Adjust the size as needed
103
+
104
+ return aligned_face
105
+
106
+ # Add person to database
107
+ def add_person(name, image_path, instagram_handle):
108
+ try:
109
+ encoding = load_and_encode(image_path)
110
+ if not encoding:
111
+ return "No face found in the provided image."
112
+
113
+ # Convert NumPy arrays to lists for JSON serialization
114
+ encoding = encoding[0].tolist()
115
+
116
+ # Save data to Firebase Realtime Database
117
+ ref.child(name).set({
118
+ "encoding": encoding,
119
+ "info": {
120
+ "instagram_handle": instagram_handle,
121
+ "instagram_link": f"https://www.instagram.com/{instagram_handle}/"
122
+ }
123
+ })
124
+
125
+ return f"Success: {name} added to the database!"
126
+ except Exception as e:
127
+ return f"Failed to add person: {str(e)}"
128
+
129
+ # Recognize face from image
130
+ def recognize_face(image_path):
131
+ if not image_path:
132
+ return "Please upload an image."
133
+
134
+ try:
135
+ unknown_encoding = load_and_encode(image_path)
136
+ if not unknown_encoding:
137
+ return "No face found in the provided image."
138
+
139
+ matches = []
140
+ for name, data in ref.get().items():
141
+ known_encoding = np.array(data["encoding"])
142
+ if face_recognition.compare_faces([known_encoding], unknown_encoding[0])[0]:
143
+ matches.append((name, data["info"]))
144
+
145
+ if matches:
146
+ results = []
147
+ for name, info in matches:
148
+ insta_handle = info["instagram_handle"]
149
+ insta_link = info["instagram_link"]
150
+ insta_link_html = f'<a href="{insta_link}" target="_blank"><font color="red">{insta_handle}</font></a>'
151
+ results.append(f"- It's a picture of {name}! Insta handle: {insta_link_html}")
152
+ return "\n".join(results)
153
+ else:
154
+ return "Face not found in the database."
155
+ except Exception as e:
156
+ return f"Failed to recognize face: {str(e)}"
157
+
158
+ # Recognize face from image and return optimal or highest matching ID
159
+ def recognize_face_optimal(image_path):
160
+ if not image_path:
161
+ return "Please upload an image."
162
+
163
+ try:
164
+ unknown_encoding = load_and_encode(image_path)
165
+ if not unknown_encoding:
166
+ return "No face found in the provided image."
167
+
168
+ matches = []
169
+ for name, data in ref.get().items():
170
+ known_encoding = np.array(data["encoding"])
171
+ similarity_score = face_recognition.face_distance([known_encoding], unknown_encoding[0])[0]
172
+ matches.append((name, similarity_score))
173
+
174
+ if matches:
175
+ best_match = min(matches, key=lambda x: x[1])
176
+ best_name, best_score = best_match
177
+ info = ref.child(best_name).child("info").get()
178
+ insta_handle = info["instagram_handle"]
179
+ insta_link = info["instagram_link"]
180
+ insta_link_html = f'<a href="{insta_link}" target="_blank"><font color="red">{insta_handle}</font></a>'
181
+ return f"Best match: {best_name} with a similarity score of {1 - best_score:.2%}. Insta handle: {insta_link_html}"
182
+ else:
183
+ return "Face not found in the database."
184
+ except Exception as e:
185
+ return f"Failed to recognize face: {str(e)}"
186
+
187
+ # Delete person from database
188
+ def delete_person(name):
189
+ try:
190
+ ref.child(name).delete()
191
+ return f"{name} deleted from the database!"
192
+ except Exception as e:
193
+ return f"Failed to delete person: {str(e)}"
194
+
195
+ # Streamlit interface for adding a person
196
+ def add_person_ui():
197
+ st.title("Add Person")
198
+ name = st.text_input("Enter Name", help="Enter the name of the person")
199
+ image_path = st.file_uploader("Upload Image", help="Upload an image containing the person's face")
200
+ instagram_handle = st.text_input("Enter Instagram Handle", help="Enter the person's Instagram handle")
201
+ if st.button("Add Person"):
202
+ if not name or not image_path or not instagram_handle:
203
+ st.error("Please fill all the fields.")
204
+ else:
205
+ result = add_person(name, image_path, instagram_handle)
206
+ st.success(result)
207
+
208
+ # Streamlit interface for recognizing face
209
+ def recognize_face_ui():
210
+ st.title("Recognize Face")
211
+ image_path = st.file_uploader("Upload Image", help="Upload an image for face recognition")
212
+ if st.button("Recognize Face"):
213
+ result = recognize_face(image_path)
214
+ st.write(result, unsafe_allow_html=True)
215
+
216
+ # Streamlit interface for recognizing face with optimal ID
217
+ def recognize_face_optimal_ui():
218
+ st.title("Recognize Face (Optimal)")
219
+ image_path = st.file_uploader("Upload Image", help="Upload an image for optimal face recognition")
220
+ if st.button("Recognize Face (Optimal)"):
221
+ result = recognize_face_optimal(image_path)
222
+ st.write(result, unsafe_allow_html=True)
223
+
224
+ # Streamlit interface for deleting a person
225
+ def delete_person_ui():
226
+ st.title("Delete Person")
227
+ name = st.text_input("Enter Name", help="Enter the name of the person to delete")
228
+ if st.button("Delete Person"):
229
+ if not name:
230
+ st.error("Please enter a name.")
231
+ else:
232
+ result = delete_person(name)
233
+ st.success(result)
234
+
235
+ # Streamlit interface for user authentication
236
+ def authenticate_user_ui():
237
+ st.title("Insta's EYE")
238
+ st.sidebar.title("Options")
239
+
240
+ if st.session_state.auth_state["signed_in"]:
241
+ st.sidebar.button("Sign Out", on_click=logout)
242
+ st.title("Welcome!")
243
+ main()
244
+ else:
245
+ option = st.sidebar.radio("Select Option", ["Login", "Sign-Up"])
246
+
247
+ email = st.text_input("Enter Email", help="Enter your email address")
248
+ password = st.text_input("Enter Password", type="password", help="Enter your password")
249
+
250
+ if option == "Login":
251
+ if st.button("Login"):
252
+ if not email or not password:
253
+ st.error("Please enter both email and password.")
254
+ else:
255
+ success, user = authenticate_user(email, password)
256
+ if success:
257
+ st.session_state.auth_state["user"] = user
258
+ st.session_state.auth_state["signed_in"] = True
259
+ st.success("Authentication successful! You can now manage your set of images and profiles.")
260
+ main()
261
+ else:
262
+ st.error("Authentication failed. Please check your email and password.")
263
+
264
+ elif option == "Sign-Up":
265
+ confirm_password = st.text_input("Confirm Password", type="password", help="Re-enter your password for confirmation")
266
+ if st.button("Sign-Up"):
267
+ if not email or not password or not confirm_password:
268
+ st.error("Please fill all the fields.")
269
+ elif password != confirm_password:
270
+ st.error("Passwords do not match.")
271
+ else:
272
+ success, uid = create_user(email, password)
273
+ if success:
274
+ st.success(f"User with UID: {uid} created successfully! You can now log in.")
275
+ else:
276
+ st.error("User creation failed. Please try again.")
277
+
278
+ # Log out user
279
+ def logout():
280
+ st.session_state.auth_state["user"] = None
281
+ st.session_state.auth_state["signed_in"] = False
282
+
283
+ # Update the main function to include the new option
284
+ def main():
285
+ st.sidebar.title("Options")
286
+
287
+ add_icon = Image.open(current_directory, "Add.png")
288
+ delete_icon = Image.open(current_directory, "delete.png")
289
+ recognize_icon = Image.open(current_directory, "Explore.png")
290
+ recognize_optimal_icon = Image.open(current_directory, "Explore+.png")
291
+
292
+ option = st.sidebar.selectbox("Select Option", [add_icon, delete_icon, recognize_icon, recognize_optimal_icon], index=0, format_func=lambda x: "")
293
+
294
+ if option == add_icon:
295
+ add_person_ui()
296
+ elif option == delete_icon:
297
+ delete_person_ui()
298
+ elif option == recognize_icon:
299
+ recognize_face_ui()
300
+ elif option == recognize_optimal_icon:
301
+ recognize_face_optimal_ui()
302
+
303
+ if __name__ == "__main__":
304
+ authenticate_user_ui()
305
+
306
+
307
+ # add_icon_path = os.path.join
308
+ # delete_icon_path = os.path.join(current_directory, "delete.png")
309
+ # recognize_icon_path = os.path.join(current_directory, "Explore.png")
310
+ # recognize_optimal_icon_path = os.path.join(current_directory, "Explore+.png")
311
+ #
312
+ # selected_option = st.sidebar.radio("Select Option", ["Add Person", "Delete Person", "Recognize Face", "Recognize Face (Optimal)"], format_func=lambda x: "")
313
+ #
314
+ # if selected_option == "Add Person":
315
+ # add_person_ui()
316
+ # elif selected_option == "Delete Person":
317
+ # delete_person_ui()
318
+ # elif selected_option == "Recognize Face":
319
+ # recognize_face_ui()
320
+ # elif selected_option == "Recognize Face (Optimal)":
321
+ # recognize_face_optimal_ui()
322
+ #
323
+ # st.sidebar.title("Options")
324
+ # st.sidebar.image(add_icon_path, use_column_width=True)
325
+ # st.sidebar.image(delete_icon_path, use_column_width=True)
326
+ # st.sidebar.image(recognize_icon_path, use_column_width=True)
327
+ # st.sidebar.image(recognize_optimal_icon_path, use_column_width=True)//
delete.png ADDED
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ numpy
2
+ opencv-python
3
+ face-recognition
4
+ firebase-admin
5
+ streamlit
6
+ instapy
7
+ clarifai==2.6.2
8
+ emoji==1.5.0
shape_predictor_68_face_landmarks.dat ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbdc2cb80eb9aa7a758672cbfdda32ba6300efe9b6e6c7a299ff7e736b11b92f
3
+ size 99693937