RajaThor commited on
Commit
3741049
·
verified ·
1 Parent(s): ee2caf3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -71
app.py CHANGED
@@ -8,21 +8,20 @@ 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, "projectinsta-s-firebase-adminsdk-y6vlu-9a1345f468.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://projectinsta-s-default-rtdb.firebaseio.com/',
21
  'projectId': 'projectinsta-s'
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:
@@ -40,7 +39,6 @@ shape_predictor = dlib.shape_predictor(shape_predictor_path)
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)}")
@@ -80,7 +78,6 @@ def load_and_encode(image_path):
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)
@@ -88,18 +85,15 @@ def detect_and_align_faces(image_path):
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
 
@@ -110,11 +104,9 @@ def add_person(name, image_path, instagram_handle):
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,
@@ -137,7 +129,7 @@ def recognize_face(image_path):
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"]))
@@ -166,7 +158,7 @@ def recognize_face_optimal(image_path):
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))
@@ -174,7 +166,7 @@ def recognize_face_optimal(image_path):
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>'
@@ -187,7 +179,7 @@ def recognize_face_optimal(image_path):
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)}"
@@ -220,7 +212,7 @@ def recognize_face_optimal_ui():
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")
@@ -232,10 +224,6 @@ def delete_person_ui():
232
  result = delete_person(name)
233
  st.success(result)
234
 
235
- def tour_guide_ui():
236
- st.title("Tour Guide")
237
- display_tour_steps(steps)
238
-
239
  # Streamlit interface for user authentication
240
  def authenticate_user_ui():
241
  st.title("Insta's EYE")
@@ -284,56 +272,61 @@ def logout():
284
  st.session_state.auth_state["user"] = None
285
  st.session_state.auth_state["signed_in"] = False
286
 
287
- # Define tour steps
288
- steps = [
289
- {
290
- "element": "h1",
291
- "title": "Welcome to Insta's EYE",
292
- "content": "This is a tour guide to help you navigate through the application.",
293
- },
294
- {
295
- "element": '[aria-label="Select Option"]',
296
- "title": "Options Sidebar",
297
- "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.",
298
- },
299
- {
300
- "element": "div[class='element-container']",
301
- "title": "Main Interface",
302
- "content": "This is where the main functionality of the application is displayed.",
303
- },
304
- {
305
- "element": "[data-testid='stFileUploader']",
306
- "title": "Upload Image",
307
- "content": "You can upload an image here for face recognition or adding a person.",
308
- },
309
- {
310
- "element": "[data-testid='stTextInput']",
311
- "title": "Text Input",
312
- "content": "Enter text here such as the person's name or Instagram handle.",
313
- },
314
- {
315
- "element": "[data-testid='stButton']",
316
- "title": "Buttons",
317
- "content": "Click on these buttons to perform actions like adding a person or recognizing a face.",
318
- },
319
- ]
320
-
321
- # Function to display tour steps
322
- def display_tour_steps(steps):
323
- st.markdown("# Tour Guide")
324
- st.markdown("This tour will guide you through the application.")
325
- st.markdown("---")
326
-
327
- for step in steps:
328
- st.markdown(f"## {step['title']}")
329
- st.write(step['content'])
330
- st.markdown("---")
331
-
332
- # Update the main function to include the new option
 
 
 
 
 
333
  def main():
334
  st.sidebar.title("Options")
335
- option = st.sidebar.radio("Select Option", ["Tour Guide", "Add Person", "Recognize Face", "Delete Person", "Recognize Face (Optimal)"])
336
-
337
  if option == "Tour Guide":
338
  tour_guide_ui()
339
  elif option == "Add Person":
@@ -344,7 +337,9 @@ def main():
344
  delete_person_ui()
345
  elif option == "Recognize Face (Optimal)":
346
  recognize_face_optimal_ui()
 
 
347
 
348
- # Run the tour guide
349
  if __name__ == "__main__":
350
  authenticate_user_ui()
 
8
  import cv2
9
  import dlib
10
 
11
+ # Firebase Realtime Database initialization
12
  current_directory = os.path.dirname(os.path.abspath(__file__))
13
  skp_path = os.path.join(current_directory, "projectinsta-s-firebase-adminsdk-y6vlu-9a1345f468.json")
14
 
 
15
  if not firebase_admin._apps:
 
16
  cred = credentials.Certificate(skp_path)
17
  firebase_admin.initialize_app(cred, {
18
  'databaseURL': 'https://projectinsta-s-default-rtdb.firebaseio.com/',
19
  'projectId': 'projectinsta-s'
20
  })
21
 
 
22
  ref = db.reference('/')
23
+ encodings_ref = ref.child('encodings') # Node to store encodings
24
+ messages_ref = ref.child('messages') # Node to store chat messages
25
 
26
  # Streamlit session state
27
  if "auth_state" not in st.session_state:
 
39
  def authenticate_user(email, password):
40
  try:
41
  user = auth.get_user_by_email(email)
 
42
  return True, user
43
  except auth.AuthError as e:
44
  print(f"Authentication error: {str(e)}")
 
78
  def detect_and_align_faces(image_path):
79
  image = face_recognition.load_image_file(image_path)
80
 
 
81
  target_width = 800
82
  aspect_ratio = image.shape[1] / image.shape[0]
83
  target_height = int(target_width / aspect_ratio)
 
85
 
86
  gray = cv2.cvtColor(resized_image, cv2.COLOR_BGR2GRAY)
87
 
 
88
  faces = detector(gray)
89
 
90
  if not faces:
91
  return None
92
 
 
93
  face = faces[0]
94
 
 
95
  landmarks = shape_predictor(gray, face)
96
+ aligned_face = dlib.get_face_chip(resized_image, landmarks, size=256)
97
 
98
  return aligned_face
99
 
 
104
  if not encoding:
105
  return "No face found in the provided image."
106
 
 
107
  encoding = encoding[0].tolist()
108
 
109
+ encodings_ref.child(name).set({
 
110
  "encoding": encoding,
111
  "info": {
112
  "instagram_handle": instagram_handle,
 
129
  return "No face found in the provided image."
130
 
131
  matches = []
132
+ for name, data in encodings_ref.get().items():
133
  known_encoding = np.array(data["encoding"])
134
  if face_recognition.compare_faces([known_encoding], unknown_encoding[0])[0]:
135
  matches.append((name, data["info"]))
 
158
  return "No face found in the provided image."
159
 
160
  matches = []
161
+ for name, data in encodings_ref.get().items():
162
  known_encoding = np.array(data["encoding"])
163
  similarity_score = face_recognition.face_distance([known_encoding], unknown_encoding[0])[0]
164
  matches.append((name, similarity_score))
 
166
  if matches:
167
  best_match = min(matches, key=lambda x: x[1])
168
  best_name, best_score = best_match
169
+ info = encodings_ref.child(best_name).child("info").get()
170
  insta_handle = info["instagram_handle"]
171
  insta_link = info["instagram_link"]
172
  insta_link_html = f'<a href="{insta_link}" target="_blank"><font color="red">{insta_handle}</font></a>'
 
179
  # Delete person from database
180
  def delete_person(name):
181
  try:
182
+ encodings_ref.child(name).delete()
183
  return f"{name} deleted from the database!"
184
  except Exception as e:
185
  return f"Failed to delete person: {str(e)}"
 
212
  if st.button("Recognize Face (Optimal)"):
213
  result = recognize_face_optimal(image_path)
214
  st.write(result, unsafe_allow_html=True)
215
+
216
  # Streamlit interface for deleting a person
217
  def delete_person_ui():
218
  st.title("Delete Person")
 
224
  result = delete_person(name)
225
  st.success(result)
226
 
 
 
 
 
227
  # Streamlit interface for user authentication
228
  def authenticate_user_ui():
229
  st.title("Insta's EYE")
 
272
  st.session_state.auth_state["user"] = None
273
  st.session_state.auth_state["signed_in"] = False
274
 
275
+ # Function to send message to Firebase Realtime Database
276
+ def send_message(sender_email, receiver_email, message):
277
+ try:
278
+ sender_ref = messages_ref.child(sender_email).child(receiver_email)
279
+ receiver_ref = messages_ref.child(receiver_email).child(sender_email)
280
+
281
+ sender_ref.push().set({
282
+ 'sender_email': sender_email,
283
+ 'message': message
284
+ })
285
+
286
+ receiver_ref.push().set({
287
+ 'sender_email': sender_email,
288
+ 'message': message
289
+ })
290
+
291
+ return True
292
+ except Exception as e:
293
+ print(f"Failed to send message: {str(e)}")
294
+ return False
295
+
296
+ # Function to get messages from Firebase Realtime Database
297
+ def get_messages(sender_email, receiver_email):
298
+ try:
299
+ messages = messages_ref.child(sender_email).child(receiver_email).get()
300
+ return messages
301
+ except Exception as e:
302
+ print(f"Failed to get messages: {str(e)}")
303
+ return None
304
+
305
+ # Streamlit interface for chat
306
+ def chat_ui(sender_email, receiver_email):
307
+ st.title("Chat")
308
+ message = st.text_input("Type your message", help="Type your message here")
309
+ receiver_email = st.text_input("Receiver's Email", help="Enter the receiver's email address")
310
+ if st.button("Send"):
311
+ if not message or not receiver_email:
312
+ st.error("Please enter both a message and the receiver's email.")
313
+ else:
314
+ if send_message(sender_email, receiver_email, message):
315
+ st.success("Message sent successfully!")
316
+ else:
317
+ st.error("Failed to send message.")
318
+
319
+ st.title("Messages")
320
+ messages = get_messages(sender_email, receiver_email)
321
+ if messages:
322
+ for key, value in messages.items():
323
+ st.write(f"{value['sender_email']}: {value['message']}")
324
+
325
+ # Update the main function to include the chat UI option
326
  def main():
327
  st.sidebar.title("Options")
328
+ option = st.sidebar.radio("Select Option", ["Tour Guide", "Add Person", "Recognize Face", "Delete Person", "Recognize Face (Optimal)", "Chat"])
329
+
330
  if option == "Tour Guide":
331
  tour_guide_ui()
332
  elif option == "Add Person":
 
337
  delete_person_ui()
338
  elif option == "Recognize Face (Optimal)":
339
  recognize_face_optimal_ui()
340
+ elif option == "Chat":
341
+ chat_ui(st.session_state.auth_state["user"].email, "RECEIVER_EMAIL") # Change RECEIVER_EMAIL to the actual receiver's email
342
 
343
+ # Run the application
344
  if __name__ == "__main__":
345
  authenticate_user_ui()