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

Create Backup.py

Browse files
Files changed (1) hide show
  1. Backup.py +350 -0
Backup.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, "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:
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
+ 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")
242
+ st.sidebar.title("Options")
243
+
244
+ if st.session_state.auth_state["signed_in"]:
245
+ st.sidebar.button("Sign Out", on_click=logout)
246
+ st.title("Welcome!")
247
+ main()
248
+ else:
249
+ option = st.sidebar.radio("Select Option", ["Login", "Sign-Up"])
250
+
251
+ email = st.text_input("Enter Email", help="Enter your email address")
252
+ password = st.text_input("Enter Password", type="password", help="Enter your password")
253
+
254
+ if option == "Login":
255
+ if st.button("Login"):
256
+ if not email or not password:
257
+ st.error("Please enter both email and password.")
258
+ else:
259
+ success, user = authenticate_user(email, password)
260
+ if success:
261
+ st.session_state.auth_state["user"] = user
262
+ st.session_state.auth_state["signed_in"] = True
263
+ st.success("Authentication successful! You can now manage your set of images and profiles.")
264
+ main()
265
+ else:
266
+ st.error("Authentication failed. Please check your email and password.")
267
+
268
+ elif option == "Sign-Up":
269
+ confirm_password = st.text_input("Confirm Password", type="password", help="Re-enter your password for confirmation")
270
+ if st.button("Sign-Up"):
271
+ if not email or not password or not confirm_password:
272
+ st.error("Please fill all the fields.")
273
+ elif password != confirm_password:
274
+ st.error("Passwords do not match.")
275
+ else:
276
+ success, uid = create_user(email, password)
277
+ if success:
278
+ st.success(f"User with UID: {uid} created successfully! You can now log in.")
279
+ else:
280
+ st.error("User creation failed. Please try again.")
281
+
282
+ # Log out user
283
+ 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":
340
+ add_person_ui()
341
+ elif option == "Recognize Face":
342
+ recognize_face_ui()
343
+ elif option == "Delete Person":
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()