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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ import firebase_admin
4
+ from firebase_admin import credentials, db, auth, firestore
5
+ import face_recognition
6
+ from PIL import Image
7
+ import numpy as np
8
+ import cv2
9
+ import dlib
10
+ from streamlit import cache as st_cache
11
+
12
+ # Get the current working directory
13
+ current_directory = os.path.dirname(os.path.abspath(__file__))
14
+ skp_path = os.path.join(current_directory, "projectinsta-s-firebase-adminsdk-y6vlu-9a1345f468.json")
15
+
16
+ # Check if the app is already initialized
17
+ if not firebase_admin._apps:
18
+ # Initialize Firebase Admin SDK
19
+ cred = credentials.Certificate(skp_path)
20
+ firebase_admin.initialize_app(cred, {
21
+ 'databaseURL': 'https://projectinsta-s-default-rtdb.firebaseio.com/',
22
+ 'projectId': 'projectinsta-s'
23
+ })
24
+
25
+ # Reference to the root of your Firebase Realtime Database
26
+ ref = db.reference('/')
27
+
28
+ # Initialize Firestore client
29
+ db_firestore = firestore.client()
30
+
31
+ # Streamlit session state
32
+ if "auth_state" not in st.session_state:
33
+ st.session_state.auth_state = {
34
+ "user": None,
35
+ "signed_in": False,
36
+ }
37
+
38
+ # Add the shape predictor model for face alignment
39
+ shape_predictor_path = "shape_predictor_68_face_landmarks.dat"
40
+ detector = dlib.get_frontal_face_detector()
41
+ shape_predictor = dlib.shape_predictor(shape_predictor_path)
42
+
43
+ # Firebase Authentication
44
+ def authenticate_user(email, password):
45
+ try:
46
+ user = auth.get_user_by_email(email)
47
+ # The user is successfully fetched, meaning the email and password are valid.
48
+ return True, user
49
+ except auth.AuthError as e:
50
+ print(f"Authentication error: {str(e)}")
51
+ return False, None
52
+
53
+ # Sign-up Functionality
54
+ def create_user(email, password):
55
+ try:
56
+ user = auth.create_user(
57
+ email=email,
58
+ password=password
59
+ )
60
+ return True, user.uid
61
+ except Exception as e:
62
+ print(f"User creation error: {str(e)}")
63
+ return False, None
64
+
65
+ # Update load_and_encode function to use the aligned face without normalization
66
+ @st_cache
67
+ def load_and_encode(image_path):
68
+ try:
69
+ aligned_face = detect_and_align_faces(image_path)
70
+
71
+ if aligned_face is not None:
72
+ encoding = face_recognition.face_encodings(aligned_face)
73
+
74
+ if encoding:
75
+ return encoding
76
+ else:
77
+ return None
78
+ else:
79
+ return None
80
+ except Exception as e:
81
+ print(f"Error loading and encoding image: {str(e)}")
82
+ return None
83
+
84
+ # Function to detect and align faces in an image with preprocessing
85
+ def detect_and_align_faces(image_path):
86
+ image = face_recognition.load_image_file(image_path)
87
+
88
+ # Resize the image to a fixed width (you can adjust the width as needed)
89
+ target_width = 800
90
+ aspect_ratio = image.shape[1] / image.shape[0]
91
+ target_height = int(target_width / aspect_ratio)
92
+ resized_image = cv2.resize(image, (target_width, target_height))
93
+
94
+ gray = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)
95
+
96
+ # Detect faces using dlib
97
+ faces = detector(gray)
98
+
99
+ if not faces:
100
+ return None
101
+
102
+ # Use the first face found (you can modify this to handle multiple faces)
103
+ face = faces[0]
104
+
105
+ # Use dlib for face alignment
106
+ landmarks = shape_predictor(gray, face)
107
+ aligned_face = dlib.get_face_chip(resized_image, landmarks, size=256) # Adjust the size as needed
108
+
109
+ return aligned_face
110
+
111
+ # Add person to database
112
+ @st_cache
113
+ def add_person(name, image_path, instagram_handle, email=None):
114
+ try:
115
+ encoding = load_and_encode(image_path)
116
+ if not encoding:
117
+ return "No face found in the provided image."
118
+
119
+ # Convert NumPy arrays to lists for JSON serialization
120
+ encoding = encoding[0].tolist()
121
+
122
+ # Save data to Firebase Realtime Database
123
+ person_data = {
124
+ "encoding": encoding,
125
+ "info": {
126
+ "instagram_handle": instagram_handle,
127
+ "instagram_link": f"https://www.instagram.com/{instagram_handle}/"
128
+ }
129
+ }
130
+ if email:
131
+ person_data["info"]["email"] = email
132
+
133
+ ref.child(name).set(person_data)
134
+
135
+ log_action(st.session_state.auth_state["user"].email, "Added person")
136
+ return f"Success: {name} added to the database!"
137
+ except Exception as e:
138
+ return f"Failed to add person: {str(e)}"
139
+
140
+ # Recognize face from image
141
+ @st_cache
142
+ def recognize_face(image_path):
143
+ if not image_path:
144
+ return "Please upload an image."
145
+
146
+ try:
147
+ unknown_encoding = load_and_encode(image_path)
148
+ if not unknown_encoding:
149
+ return "No face found in the provided image."
150
+
151
+ matches = []
152
+ for name, data in ref.get().items():
153
+ known_encoding = np.array(data["encoding"])
154
+ if face_recognition.compare_faces([known_encoding], unknown_encoding[0])[0]:
155
+ info = data["info"]
156
+ email = info.get("email", "Email not provided")
157
+ matches.append((name, info["instagram_handle"], email))
158
+
159
+ if matches:
160
+ results = []
161
+ for name, insta_handle, email in matches:
162
+ insta_link = f"https://www.instagram.com/{insta_handle}/"
163
+ insta_link_html = f'<a href="{insta_link}" target="_blank"><font color="red">{insta_handle}</font></a>'
164
+ results.append(f"- It's a picture of {name}! Insta handle: {insta_link_html}, Email: {email}")
165
+ log_action(st.session_state.auth_state["user"].email, "Recognized face")
166
+ return "\n".join(results)
167
+ else:
168
+ return "Face not found in the database."
169
+ except Exception as e:
170
+ return f"Failed to recognize face: {str(e)}"
171
+
172
+ # Recognize face from image and return optimal or highest matching ID
173
+ @st_cache
174
+ def recognize_face_optimal(image_path):
175
+ if not image_path:
176
+ return "Please upload an image."
177
+
178
+ try:
179
+ unknown_encoding = load_and_encode(image_path)
180
+ if not unknown_encoding:
181
+ return "No face found in the provided image."
182
+
183
+ matches = []
184
+ for name, data in ref.get().items():
185
+ known_encoding = np.array(data["encoding"])
186
+ similarity_score = face_recognition.face_distance([known_encoding], unknown_encoding[0])[0]
187
+ if similarity_score > 0.50: # Only consider matches above 50.00% similarity
188
+ continue
189
+ matches.append((name, similarity_score))
190
+
191
+ if matches:
192
+ best_match = min(matches, key=lambda x: x[1])
193
+ best_name, best_score = best_match
194
+ info = ref.child(best_name).child("info").get()
195
+ insta_handle = info["instagram_handle"]
196
+ insta_link = info["instagram_link"]
197
+ insta_link_html = f'<a href="{insta_link}" target="_blank"><font color="red">{insta_handle}</font></a>'
198
+ return f"Best match: {best_name} with a similarity score of {1 - best_score:.2%}. Insta handle: {insta_link_html}"
199
+ else:
200
+ return "Face not found in the database."
201
+ except Exception as e:
202
+ return f"Failed to recognize face: {str(e)}"
203
+
204
+ # Delete person from database
205
+ @st_cache
206
+ def delete_person(name):
207
+ try:
208
+ ref.child(name).delete()
209
+ log_action(st.session_state.auth_state["user"].email, "Deleted person")
210
+ return f"{name} deleted from the database!"
211
+ except Exception as e:
212
+ return f"Failed to delete person: {str(e)}"
213
+
214
+ # Delete user from Firebase Authentication
215
+ def delete_user(email):
216
+ try:
217
+ user = auth.get_user_by_email(email)
218
+ auth.delete_user(user.uid)
219
+ return "User deleted successfully!"
220
+ except Exception as e:
221
+ return f"Failed to delete user: {str(e)}"
222
+
223
+ # Send feedback to Firebase
224
+ def send_feedback(feedback_data):
225
+ try:
226
+ db_firestore.collection('feedback').add(feedback_data)
227
+ except Exception as e:
228
+ st.error(f"Failed to submit feedback: {str(e)}")
229
+
230
+ # Streamlit interface for adding a person
231
+ def add_person_ui():
232
+ st.title("😎 Add Person")
233
+ name = st.text_input("Enter Name", help="Enter the name of the person")
234
+ image_path = st.file_uploader("Upload Image", help="Upload an image containing the person's face")
235
+ email = st.text_input("Enter Email (Optional)", help="Enter the person's email address (optional)")
236
+ instagram_handle = st.text_input("Enter Instagram Handle", help="Enter the person's Instagram handle")
237
+ if st.button("Add Person"):
238
+ if not name or not image_path or not instagram_handle:
239
+ st.error("Please fill all the required fields.")
240
+ else:
241
+ result = add_person(name, image_path, instagram_handle, email)
242
+ st.success(result)
243
+
244
+ # Streamlit interface for recognizing face
245
+ def recognize_face_ui():
246
+ st.title("🔍 Recognize Face")
247
+ image_path = st.file_uploader("Upload Image", help="Upload an image for face recognition")
248
+ if st.button("Recognize Face"):
249
+ result = recognize_face(image_path)
250
+ st.write(result, unsafe_allow_html=True)
251
+
252
+ if "It's a picture of" in result:
253
+ # Extract email from the result
254
+ email_start = result.find("Insta handle: ") + len("Insta handle: ")
255
+ email_end = result.find("</font></a>", email_start)
256
+ email = result[email_start:email_end]
257
+ st.write(f"Email: {email}")
258
+
259
+ def recognize_face_optimal_ui():
260
+ st.title("🔍 Recognize Face (Optimal)")
261
+ image_path = st.file_uploader("Upload Image", help="Upload an image for optimal face recognition")
262
+ if st.button("Recognize Face (Optimal)"):
263
+ result = recognize_face_optimal(image_path)
264
+ if "not found" in result.lower(): # Check if "not found" is in the result message
265
+ st.error(result)
266
+ else:
267
+ st.write(result, unsafe_allow_html=True)
268
+
269
+ # Streamlit interface for deleting a person
270
+ def delete_person_ui():
271
+ st.title("🗑️ Delete Person")
272
+ name = st.text_input("Enter Name", help="Enter the name of the person to delete")
273
+ if st.button("Delete Person"):
274
+ if not name:
275
+ st.error("Please enter a name.")
276
+ else:
277
+ result = delete_person(name)
278
+ st.success(result)
279
+
280
+ # Streamlit interface for feedback
281
+ def feedback_ui():
282
+ st.title("✍️ Feedback")
283
+ st.write("Your feedback is important to us! Please fill out the form below:")
284
+
285
+ name = st.text_input("Name (optional)")
286
+ email = st.text_input("Email (optional)")
287
+ category = st.selectbox("Category", ["Bug Report", "Feature Request", "General Feedback"])
288
+ message = st.text_area("Feedback Message")
289
+
290
+ if st.button("Submit Feedback"):
291
+ if not message:
292
+ st.error("Please enter your feedback message.")
293
+ else:
294
+ feedback_data = {
295
+ "name": name,
296
+ "email": email,
297
+ "category": category,
298
+ "message": message,
299
+ }
300
+ send_feedback(feedback_data)
301
+ st.success("Feedback submitted successfully! Thank you for your feedback.")
302
+
303
+ #section for messaging
304
+
305
+ # Function to send a message
306
+ def send_message(sender_email, receiver_email, message_content):
307
+ try:
308
+ # Add message to Firestore
309
+ db_firestore.collection('messages').add({
310
+ 'sender_email': sender_email,
311
+ 'receiver_email': receiver_email,
312
+ 'message_content': message_content,
313
+ 'timestamp': firestore.SERVER_TIMESTAMP
314
+ })
315
+ return "Message sent successfully!"
316
+ except Exception as e:
317
+ return f"Failed to send message: {str(e)}"
318
+
319
+ # Function to retrieve messages for a user
320
+ def get_messages(user_email):
321
+ try:
322
+ messages = db_firestore.collection('messages').where('receiver_email', '==', user_email).order_by('timestamp', direction=firestore.Query.DESCENDING).stream()
323
+ return messages
324
+ except Exception as e:
325
+ return None
326
+
327
+ # Streamlit interface for messaging
328
+ def messaging_ui():
329
+ st.title("💬 Messaging")
330
+
331
+ if st.session_state.auth_state["signed_in"]:
332
+ sender_email = st.session_state.auth_state["user"].email
333
+ receiver_email = st.text_input("Receiver's Email", help="Enter the receiver's email address")
334
+ message_content = st.text_area("Message Content")
335
+
336
+ if st.button("Send Message"):
337
+ result = send_message(sender_email, receiver_email, message_content)
338
+ st.write(result)
339
+
340
+ messages = get_messages(sender_email)
341
+ if messages:
342
+ st.write("Your messages:")
343
+ for message in messages:
344
+ message_data = message.to_dict()
345
+ st.write(f"From: {message_data['sender_email']}")
346
+ st.write(f"Message: {message_data['message_content']}")
347
+ st.write("---")
348
+ else:
349
+ st.write("Please sign in to send and view messages.")
350
+
351
+ #end of messaging section
352
+
353
+ # History section
354
+ def log_action(user_email, action):
355
+ try:
356
+ db_firestore.collection('history').add({
357
+ 'user_email': user_email,
358
+ 'action': action,
359
+ 'timestamp': firestore.SERVER_TIMESTAMP
360
+ })
361
+ except Exception as e:
362
+ st.error(f"Failed to log action: {str(e)}")
363
+
364
+ # Display history of actions taken by the user
365
+ def display_history(user_email):
366
+ st.title("📜 History")
367
+ st.write("Here is the history of actions taken by you:")
368
+
369
+ try:
370
+ history = db_firestore.collection('history').where('user_email', '==', user_email).order_by('timestamp', direction=firestore.Query.DESCENDING).stream()
371
+ for entry in history:
372
+ entry_data = entry.to_dict()
373
+ action = entry_data['action']
374
+ timestamp = entry_data['timestamp']
375
+ st.write(f"- {action} at {timestamp}")
376
+ except Exception as e:
377
+ st.error(f"Failed to retrieve history: {str(e)}")
378
+ #End of history section
379
+
380
+ # Streamlit interface for Deleting user
381
+ def delete_user_ui():
382
+ st.title("Delete User")
383
+ email = st.text_input("Enter User's Email", help="Enter the email of the user to delete")
384
+ if st.button("Delete User"):
385
+ if not email:
386
+ st.error("Please enter a user's email.")
387
+ else:
388
+ result = delete_user(email)
389
+ st.success(result)
390
+
391
+ def tour_guide_ui():
392
+ st.title("🗺️ Tour Guide")
393
+ st.markdown("This tour will guide you through the application.")
394
+
395
+ with st.expander("Welcome"):
396
+ st.write("This is a tour guide to help you navigate through the application.")
397
+
398
+ with st.expander("Options Sidebar"):
399
+ st.write("Here you can select different options such as adding a person, recognizing a face, deleting a person, or recognizing a face with optimal identification.")
400
+
401
+ with st.expander("Main Interface"):
402
+ st.write("This is where the main functionality of the application is displayed.")
403
+
404
+ with st.expander("Upload Image"):
405
+ st.write("You can upload an image here for face recognition or adding a person.")
406
+
407
+ with st.expander("Text Input"):
408
+ st.write("Enter text here such as the person's name or Instagram handle.")
409
+
410
+ with st.expander("Buttons"):
411
+ st.write("Click on these buttons to perform actions like adding a person or recognizing a face.")
412
+
413
+ def authenticate_user_ui():
414
+ # Display logo and title
415
+ c30, c31, c32 = st.columns([0.2, 0.1, 3])
416
+ with c30:
417
+ st.caption("")
418
+ # Display the logo
419
+ logo_path = os.path.join(current_directory, "Explore+.png")
420
+ logo = Image.open(logo_path)
421
+ st.image(logo, width=60)
422
+
423
+ with c32:
424
+ st.title("Insta's EYE")
425
+ st.sidebar.title("Options")
426
+
427
+ if st.session_state.auth_state["signed_in"]:
428
+ st.sidebar.button("Sign Out", on_click=logout)
429
+ st.title("Welcome!")
430
+ main()
431
+ else:
432
+ option = st.sidebar.radio("Select Option", ["Login", "Sign-Up"])
433
+
434
+ email = st.text_input("Enter Email", help="Enter your email address")
435
+ password = st.text_input("Enter Password", type="password", help="Enter your password")
436
+
437
+ if option == "Login":
438
+ if st.button("Login"):
439
+ if not email or not password:
440
+ st.error("Please enter both email and password.")
441
+ else:
442
+ success, user = authenticate_user(email, password)
443
+ if success:
444
+ st.session_state.auth_state["user"] = user
445
+ st.session_state.auth_state["signed_in"] = True
446
+ st.success("Authentication successful! You can now manage your set of images and profiles.")
447
+ main()
448
+ else:
449
+ st.error("Authentication failed. Please check your email and password.")
450
+
451
+ elif option == "Sign-Up":
452
+ confirm_password = st.text_input("Confirm Password", type="password", help="Re-enter your password for confirmation")
453
+ if st.button("Sign-Up"):
454
+ if not email or not password or not confirm_password:
455
+ st.error("Please fill all the fields.")
456
+ elif password != confirm_password:
457
+ st.error("Passwords do not match.")
458
+ else:
459
+ success, uid = create_user(email, password)
460
+ if success:
461
+ st.success(f"User with UID: {uid} created successfully! You can now log in.")
462
+ else:
463
+ st.error("User creation failed. Please try again.")
464
+
465
+ # Log out user
466
+ def logout():
467
+ st.session_state.auth_state["user"] = None
468
+ st.session_state.auth_state["signed_in"] = False
469
+
470
+ # Define tour steps
471
+ steps = [
472
+ {
473
+ "title": "Welcome to Insta's EYE",
474
+ "content": "This is a tour guide to help you navigate through the application.",
475
+ },
476
+ {
477
+ "title": "Options Sidebar",
478
+ "content": "Here you can select different options such as adding a person, recognizing a face, deleting a person, or recognizing a face with optimal identification.",
479
+ },
480
+ {
481
+ "title": "Main Interface",
482
+ "content": "This is where the main functionality of the application is displayed.",
483
+ },
484
+ {
485
+ "title": "Upload Image",
486
+ "content": "You can upload an image here for face recognition or adding a person.",
487
+ },
488
+ {
489
+ "title": "Text Input",
490
+ "content": "Enter text here such as the person's name or Instagram handle.",
491
+ },
492
+ {
493
+ "title": "Buttons",
494
+ "content": "Click on these buttons to perform actions like adding a person or recognizing a face.",
495
+ },
496
+ ]
497
+
498
+ # Function to display tour steps
499
+ def display_tour_steps(steps):
500
+ st.markdown("# Tour Guide")
501
+ st.markdown("This tour will guide you through the application.")
502
+ st.markdown("---")
503
+
504
+ for step in steps:
505
+ st.markdown(f"## {step['title']}")
506
+ st.write(step['content'])
507
+ st.markdown("---")
508
+
509
+ # Update the main function to include the feedback option
510
+ def main():
511
+ st.sidebar.title("Options")
512
+ option = st.sidebar.radio("Select Option", ["Add Person", "Recognize Face", "Delete Person", "Recognize Face (Optimal)", "Tour Guide", "Feedback", "Messaging", "History", "Delete User"])
513
+
514
+ if option == "Add Person":
515
+ add_person_ui()
516
+ elif option == "Recognize Face":
517
+ recognize_face_ui()
518
+ elif option == "Delete Person":
519
+ delete_person_ui()
520
+ elif option == "Recognize Face (Optimal)":
521
+ recognize_face_optimal_ui()
522
+ elif option == "Tour Guide":
523
+ tour_guide_ui()
524
+ elif option == "Feedback":
525
+ feedback_ui()
526
+ elif option == "Messaging":
527
+ messaging_ui()
528
+ elif option == "History":
529
+ display_history(st.session_state.auth_state["user"].email)
530
+ elif option == "Delete User":
531
+ delete_user_ui()
532
+
533
+ # Run the tour guide
534
+ if __name__ == "__main__":
535
+ authenticate_user_ui()