RajaThor commited on
Commit
b3e7a66
·
verified ·
1 Parent(s): 8653c61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -29
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, db, auth, firestore
5
  import face_recognition
6
  from PIL import Image
7
  import numpy as np
@@ -12,18 +12,22 @@ 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
- # 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
- db = firestore.client()
24
 
25
- # Reference to the root of your Firebase Realtime Database
26
- ref = db.reference('/')
 
 
 
 
 
27
 
28
  # Streamlit session state
29
  if "auth_state" not in st.session_state:
@@ -62,28 +66,48 @@ def create_user(email, password):
62
  # Function to send a message
63
  def send_message(sender, recipient, message):
64
  try:
65
- # Add a new document with a generated ID
66
- db.collection("messages").add({
67
  "sender": sender,
68
  "recipient": recipient,
69
  "message": message,
70
  "timestamp": firebase_admin.firestore.SERVER_TIMESTAMP
71
  })
 
 
 
 
 
 
 
 
 
72
  return "Message sent successfully!"
73
  except Exception as e:
74
  return f"Failed to send message: {str(e)}"
75
 
76
- # Function to retrieve messages
77
- def retrieve_messages():
78
  try:
79
- # Retrieve all documents from the 'messages' collection
80
- messages_ref = db.collection("messages").order_by("timestamp")
81
  for message in messages_ref.stream():
82
  message_data = message.to_dict()
83
  # Display the message in the chat interface
84
  st.write(f"{message_data['sender']}: {message_data['message']} ({message_data['timestamp']})")
85
  except Exception as e:
86
- st.error(f"Failed to retrieve messages: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  # Update load_and_encode function to use the aligned face without normalization
89
  def load_and_encode(image_path):
@@ -140,8 +164,8 @@ def add_person(name, image_path, instagram_handle):
140
  # Convert NumPy arrays to lists for JSON serialization
141
  encoding = encoding[0].tolist()
142
 
143
- # Save data to Firebase Realtime Database
144
- ref.child(name).set({
145
  "encoding": encoding,
146
  "info": {
147
  "instagram_handle": instagram_handle,
@@ -149,9 +173,9 @@ def add_person(name, image_path, instagram_handle):
149
  }
150
  })
151
 
152
- return f"Success: {name} added to the database!"
153
  except Exception as e:
154
- return f"Failed to add person: {str(e)}"
155
 
156
  # Recognize face from image
157
  def recognize_face(image_path):
@@ -164,10 +188,11 @@ def recognize_face(image_path):
164
  return "No face found in the provided image."
165
 
166
  matches = []
167
- for name, data in ref.get().items():
 
168
  known_encoding = np.array(data["encoding"])
169
  if face_recognition.compare_faces([known_encoding], unknown_encoding[0])[0]:
170
- matches.append((name, data["info"]))
171
 
172
  if matches:
173
  results = []
@@ -193,15 +218,16 @@ def recognize_face_optimal(image_path):
193
  return "No face found in the provided image."
194
 
195
  matches = []
196
- for name, data in ref.get().items():
 
197
  known_encoding = np.array(data["encoding"])
198
  similarity_score = face_recognition.face_distance([known_encoding], unknown_encoding[0])[0]
199
- matches.append((name, similarity_score))
200
 
201
  if matches:
202
  best_match = min(matches, key=lambda x: x[1])
203
  best_name, best_score = best_match
204
- info = ref.child(best_name).child("info").get()
205
  insta_handle = info["instagram_handle"]
206
  insta_link = info["instagram_link"]
207
  insta_link_html = f'<a href="{insta_link}" target="_blank"><font color="red">{insta_handle}</font></a>'
@@ -211,13 +237,13 @@ def recognize_face_optimal(image_path):
211
  except Exception as e:
212
  return f"Failed to recognize face: {str(e)}"
213
 
214
- # Delete person from database
215
  def delete_person(name):
216
  try:
217
- ref.child(name).delete()
218
- return f"{name} deleted from the database!"
219
  except Exception as e:
220
- return f"Failed to delete person: {str(e)}"
221
 
222
  # Streamlit interface for adding a person
223
  def add_person_ui():
@@ -240,7 +266,7 @@ def recognize_face_ui():
240
  result = recognize_face(image_path)
241
  st.write(result, unsafe_allow_html=True)
242
 
243
- # Streamlit interface for chat
244
  def chat_ui():
245
  st.title("Chat")
246
  sender = st.session_state.auth_state["user"]["email"]
@@ -249,8 +275,10 @@ def chat_ui():
249
  if st.button("Send"):
250
  result = send_message(sender, recipient, message)
251
  st.write(result)
252
- st.header("Messages")
253
- retrieve_messages()
 
 
254
 
255
  # Streamlit interface for recognizing face with optimal ID
256
  def recognize_face_optimal_ui():
 
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
  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
+ 'projectId': 'projectinsta-s'
29
+ })
30
+ db_realtime = realtimedb.reference()
31
 
32
  # Streamlit session state
33
  if "auth_state" not in st.session_state:
 
66
  # Function to send a message
67
  def send_message(sender, recipient, message):
68
  try:
69
+ # Add a new document with a generated ID to Firestore
70
+ db_firestore.collection("messages").add({
71
  "sender": sender,
72
  "recipient": recipient,
73
  "message": message,
74
  "timestamp": firebase_admin.firestore.SERVER_TIMESTAMP
75
  })
76
+
77
+ # Add a new child with a generated ID to Realtime Database
78
+ db_realtime.child("messages").push({
79
+ "sender": sender,
80
+ "recipient": recipient,
81
+ "message": message,
82
+ "timestamp": firebase_admin.firestore.SERVER_TIMESTAMP
83
+ })
84
+
85
  return "Message sent successfully!"
86
  except Exception as e:
87
  return f"Failed to send message: {str(e)}"
88
 
89
+ # Function to retrieve messages from Firestore
90
+ def retrieve_messages_firestore():
91
  try:
92
+ # Retrieve all documents from the 'messages' collection in Firestore
93
+ messages_ref = db_firestore.collection("messages").order_by("timestamp")
94
  for message in messages_ref.stream():
95
  message_data = message.to_dict()
96
  # Display the message in the chat interface
97
  st.write(f"{message_data['sender']}: {message_data['message']} ({message_data['timestamp']})")
98
  except Exception as e:
99
+ st.error(f"Failed to retrieve messages from Firestore: {str(e)}")
100
+
101
+ # Function to retrieve messages from Realtime Database
102
+ def retrieve_messages_realtime():
103
+ try:
104
+ # Retrieve all documents from the 'messages' collection in Realtime Database
105
+ messages_ref = db_realtime.child("messages").get()
106
+ for message_id, message_data in messages_ref.items():
107
+ # Display the message in the chat interface
108
+ st.write(f"{message_data['sender']}: {message_data['message']} ({message_data['timestamp']})")
109
+ except Exception as e:
110
+ st.error(f"Failed to retrieve messages from Realtime Database: {str(e)}")
111
 
112
  # Update load_and_encode function to use the aligned face without normalization
113
  def load_and_encode(image_path):
 
164
  # Convert NumPy arrays to lists for JSON serialization
165
  encoding = encoding[0].tolist()
166
 
167
+ # Save data to Firestore
168
+ db_firestore.collection("persons").document(name).set({
169
  "encoding": encoding,
170
  "info": {
171
  "instagram_handle": instagram_handle,
 
173
  }
174
  })
175
 
176
+ return f"Success: {name} added to Firestore!"
177
  except Exception as e:
178
+ return f"Failed to add person to Firestore: {str(e)}"
179
 
180
  # Recognize face from image
181
  def recognize_face(image_path):
 
188
  return "No face found in the provided image."
189
 
190
  matches = []
191
+ for person_ref in db_firestore.collection("persons").stream():
192
+ data = person_ref.to_dict()
193
  known_encoding = np.array(data["encoding"])
194
  if face_recognition.compare_faces([known_encoding], unknown_encoding[0])[0]:
195
+ matches.append((person_ref.id, data["info"]))
196
 
197
  if matches:
198
  results = []
 
218
  return "No face found in the provided image."
219
 
220
  matches = []
221
+ for person_ref in db_firestore.collection("persons").stream():
222
+ data = person_ref.to_dict()
223
  known_encoding = np.array(data["encoding"])
224
  similarity_score = face_recognition.face_distance([known_encoding], unknown_encoding[0])[0]
225
+ matches.append((person_ref.id, similarity_score))
226
 
227
  if matches:
228
  best_match = min(matches, key=lambda x: x[1])
229
  best_name, best_score = best_match
230
+ info = db_firestore.collection("persons").document(best_name).get().to_dict()["info"]
231
  insta_handle = info["instagram_handle"]
232
  insta_link = info["instagram_link"]
233
  insta_link_html = f'<a href="{insta_link}" target="_blank"><font color="red">{insta_handle}</font></a>'
 
237
  except Exception as e:
238
  return f"Failed to recognize face: {str(e)}"
239
 
240
+ # Delete person from Firestore
241
  def delete_person(name):
242
  try:
243
+ db_firestore.collection("persons").document(name).delete()
244
+ return f"{name} deleted from Firestore!"
245
  except Exception as e:
246
+ return f"Failed to delete person from Firestore: {str(e)}"
247
 
248
  # Streamlit interface for adding a person
249
  def add_person_ui():
 
266
  result = recognize_face(image_path)
267
  st.write(result, unsafe_allow_html=True)
268
 
269
+ # Streamlit interface for chat (Retrieve messages from both Firestore and Realtime Database)
270
  def chat_ui():
271
  st.title("Chat")
272
  sender = st.session_state.auth_state["user"]["email"]
 
275
  if st.button("Send"):
276
  result = send_message(sender, recipient, message)
277
  st.write(result)
278
+ st.header("Messages (Firestore)")
279
+ retrieve_messages_firestore()
280
+ st.header("Messages (Realtime Database)")
281
+ retrieve_messages_realtime()
282
 
283
  # Streamlit interface for recognizing face with optimal ID
284
  def recognize_face_optimal_ui():