RajaThor commited on
Commit
9303e93
·
verified ·
1 Parent(s): 9148ade

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -94
app.py CHANGED
@@ -1,7 +1,7 @@
1
  import os
2
  import streamlit as st
3
  import firebase_admin
4
- from firebase_admin import credentials, auth, firestore, db as realtimedb
5
  import face_recognition
6
  from PIL import Image
7
  import numpy as np
@@ -12,23 +12,17 @@ import dlib
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
- # Initialize Firebase Admin SDK for Firestore
16
  if not firebase_admin._apps:
 
17
  cred = credentials.Certificate(skp_path)
18
  firebase_admin.initialize_app(cred, {
19
  'databaseURL': 'https://projectinsta-s-default-rtdb.firebaseio.com/',
20
  'projectId': 'projectinsta-s'
21
  })
22
- db_firestore = firestore.client()
23
 
24
- # Initialize Firebase Admin SDK for Realtime Database
25
- if not firebase_admin._apps:
26
- cred = credentials.Certificate(skp_path)
27
- firebase_admin.initialize_app(cred, {
28
- 'databaseURL': 'https://projectinsta-s-default-rtdb.firebaseio.com/',
29
- 'projectId': 'projectinsta-s'
30
- })
31
- db_realtime = realtimedb.reference()
32
 
33
  # Streamlit session state
34
  if "auth_state" not in st.session_state:
@@ -63,52 +57,6 @@ def create_user(email, password):
63
  except Exception as e:
64
  print(f"User creation error: {str(e)}")
65
  return False, None
66
-
67
- # Function to send a message
68
- def send_message(db_firestore, db_realtime, sender, recipient, message):
69
- try:
70
- # Add a new document with a generated ID to Firestore
71
- db_firestore.collection("messages").add({
72
- "sender": sender,
73
- "recipient": recipient,
74
- "message": message,
75
- "timestamp": firebase_admin.firestore.SERVER_TIMESTAMP
76
- })
77
-
78
- # Add a new child with a generated ID to Realtime Database
79
- db_realtime.child("messages").push({
80
- "sender": sender,
81
- "recipient": recipient,
82
- "message": message,
83
- "timestamp": firebase_admin.firestore.SERVER_TIMESTAMP
84
- })
85
-
86
- return "Message sent successfully!"
87
- except Exception as e:
88
- return f"Failed to send message: {str(e)}"
89
-
90
- # Function to retrieve messages from Firestore
91
- def retrieve_messages_firestore(db_firestore):
92
- try:
93
- # Retrieve all documents from the 'messages' collection in Firestore
94
- messages_ref = db_firestore.collection("messages").order_by("timestamp")
95
- for message in messages_ref.stream():
96
- message_data = message.to_dict()
97
- # Display the message in the chat interface
98
- st.write(f"{message_data['sender']}: {message_data['message']} ({message_data['timestamp']})")
99
- except Exception as e:
100
- st.error(f"Failed to retrieve messages from Firestore: {str(e)}")
101
-
102
- # Function to retrieve messages from Realtime Database
103
- def retrieve_messages_realtime(db_realtime):
104
- try:
105
- # Retrieve all documents from the 'messages' collection in Realtime Database
106
- messages_ref = db_realtime.child("messages").get()
107
- for message_id, message_data in messages_ref.items():
108
- # Display the message in the chat interface
109
- st.write(f"{message_data['sender']}: {message_data['message']} ({message_data['timestamp']})")
110
- except Exception as e:
111
- st.error(f"Failed to retrieve messages from Realtime Database: {str(e)}")
112
 
113
  # Update load_and_encode function to use the aligned face without normalization
114
  def load_and_encode(image_path):
@@ -165,8 +113,8 @@ def add_person(name, image_path, instagram_handle):
165
  # Convert NumPy arrays to lists for JSON serialization
166
  encoding = encoding[0].tolist()
167
 
168
- # Save data to Firestore
169
- db_firestore.collection("persons").document(name).set({
170
  "encoding": encoding,
171
  "info": {
172
  "instagram_handle": instagram_handle,
@@ -174,9 +122,9 @@ def add_person(name, image_path, instagram_handle):
174
  }
175
  })
176
 
177
- return f"Success: {name} added to Firestore!"
178
  except Exception as e:
179
- return f"Failed to add person to Firestore: {str(e)}"
180
 
181
  # Recognize face from image
182
  def recognize_face(image_path):
@@ -189,11 +137,10 @@ def recognize_face(image_path):
189
  return "No face found in the provided image."
190
 
191
  matches = []
192
- for person_ref in db_firestore.collection("persons").stream():
193
- data = person_ref.to_dict()
194
  known_encoding = np.array(data["encoding"])
195
  if face_recognition.compare_faces([known_encoding], unknown_encoding[0])[0]:
196
- matches.append((person_ref.id, data["info"]))
197
 
198
  if matches:
199
  results = []
@@ -219,16 +166,15 @@ def recognize_face_optimal(image_path):
219
  return "No face found in the provided image."
220
 
221
  matches = []
222
- for person_ref in db_firestore.collection("persons").stream():
223
- data = person_ref.to_dict()
224
  known_encoding = np.array(data["encoding"])
225
  similarity_score = face_recognition.face_distance([known_encoding], unknown_encoding[0])[0]
226
- matches.append((person_ref.id, similarity_score))
227
 
228
  if matches:
229
  best_match = min(matches, key=lambda x: x[1])
230
  best_name, best_score = best_match
231
- info = db_firestore.collection("persons").document(best_name).get().to_dict()["info"]
232
  insta_handle = info["instagram_handle"]
233
  insta_link = info["instagram_link"]
234
  insta_link_html = f'<a href="{insta_link}" target="_blank"><font color="red">{insta_handle}</font></a>'
@@ -238,13 +184,13 @@ def recognize_face_optimal(image_path):
238
  except Exception as e:
239
  return f"Failed to recognize face: {str(e)}"
240
 
241
- # Delete person from Firestore
242
  def delete_person(name):
243
  try:
244
- db_firestore.collection("persons").document(name).delete()
245
- return f"{name} deleted from Firestore!"
246
  except Exception as e:
247
- return f"Failed to delete person from Firestore: {str(e)}"
248
 
249
  # Streamlit interface for adding a person
250
  def add_person_ui():
@@ -266,20 +212,6 @@ def recognize_face_ui():
266
  if st.button("Recognize Face"):
267
  result = recognize_face(image_path)
268
  st.write(result, unsafe_allow_html=True)
269
-
270
- # Streamlit interface for chat (Retrieve messages from both Firestore and Realtime Database)
271
- def chat_ui(db_firestore, db_realtime):
272
- st.title("Chat")
273
- sender = st.session_state.auth_state["user"]["email"]
274
- recipient = st.text_input("Recipient", help="Enter the recipient's email address")
275
- message = st.text_area("Message", help="Type your message here")
276
- if st.button("Send"):
277
- result = send_message(sender, recipient, message)
278
- st.write(result)
279
- st.header("Messages (Firestore)")
280
- retrieve_messages_firestore(db_firestore)
281
- st.header("Messages (Realtime Database)")
282
- retrieve_messages_realtime(db_realtime)
283
 
284
  # Streamlit interface for recognizing face with optimal ID
285
  def recognize_face_optimal_ui():
@@ -301,7 +233,7 @@ def delete_person_ui():
301
  st.success(result)
302
 
303
  # Streamlit interface for user authentication
304
- def authenticate_user_ui(db_firestore, db_realtime): # Pass the database references as arguments
305
  st.title("Insta's EYE")
306
  st.sidebar.title("Options")
307
 
@@ -322,9 +254,7 @@ def authenticate_user_ui(db_firestore, db_realtime): # Pass the database refere
322
  else:
323
  success, user = authenticate_user(email, password)
324
  if success:
325
- # Extract user's email from UserRecord object
326
- user_email = user.email
327
- st.session_state.auth_state["user"] = {"email": user_email}
328
  st.session_state.auth_state["signed_in"] = True
329
  st.success("Authentication successful! You can now manage your set of images and profiles.")
330
  main()
@@ -353,7 +283,7 @@ def logout():
353
  # Update the main function to include the new option
354
  def main():
355
  st.sidebar.title("Options")
356
- option = st.sidebar.radio("Select Option", ["Add Person", "Recognize Face", "Delete Person", "Recognize Face (Optimal)", "Chat"])
357
 
358
  if option == "Add Person":
359
  add_person_ui()
@@ -363,8 +293,6 @@ def main():
363
  delete_person_ui()
364
  elif option == "Recognize Face (Optimal)":
365
  recognize_face_optimal_ui()
366
- elif option == "Chat":
367
- chat_ui()
368
 
369
  if __name__ == "__main__":
370
- authenticate_user_ui(db_firestore, db_realtime)
 
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
 
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:
 
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):
 
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,
 
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):
 
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 = []
 
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>'
 
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():
 
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():
 
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
 
 
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()
 
283
  # Update the main function to include the new option
284
  def main():
285
  st.sidebar.title("Options")
286
+ option = st.sidebar.radio("Select Option", ["Add Person", "Recognize Face", "Delete Person", "Recognize Face (Optimal)"])
287
 
288
  if option == "Add Person":
289
  add_person_ui()
 
293
  delete_person_ui()
294
  elif option == "Recognize Face (Optimal)":
295
  recognize_face_optimal_ui()
 
 
296
 
297
  if __name__ == "__main__":
298
+ authenticate_user_ui()