RajaThor commited on
Commit
7e4f930
·
verified ·
1 Parent(s): 235faca

Create back

Browse files
Files changed (1) hide show
  1. back +362 -0
back ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ st.markdown("This tour will guide you through the application.")
238
+
239
+ with st.expander("Welcome"):
240
+ st.write("This is a tour guide to help you navigate through the application.")
241
+
242
+ with st.expander("Options Sidebar"):
243
+ 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.")
244
+
245
+ with st.expander("Main Interface"):
246
+ st.write("This is where the main functionality of the application is displayed.")
247
+
248
+ with st.expander("Upload Image"):
249
+ st.write("You can upload an image here for face recognition or adding a person.")
250
+
251
+ with st.expander("Text Input"):
252
+ st.write("Enter text here such as the person's name or Instagram handle.")
253
+
254
+ with st.expander("Buttons"):
255
+ st.write("Click on these buttons to perform actions like adding a person or recognizing a face.")
256
+
257
+ # Streamlit interface for user authentication
258
+ def authenticate_user_ui():
259
+ st.title("Insta's EYE")
260
+ st.sidebar.title("Options")
261
+
262
+ if st.session_state.auth_state["signed_in"]:
263
+ st.sidebar.button("Sign Out", on_click=logout)
264
+ st.title("Welcome!")
265
+ main()
266
+ else:
267
+ option = st.sidebar.radio("Select Option", ["Login", "Sign-Up"])
268
+
269
+ email = st.text_input("Enter Email", help="Enter your email address")
270
+ password = st.text_input("Enter Password", type="password", help="Enter your password")
271
+
272
+ if option == "Login":
273
+ if st.button("Login"):
274
+ if not email or not password:
275
+ st.error("Please enter both email and password.")
276
+ else:
277
+ success, user = authenticate_user(email, password)
278
+ if success:
279
+ st.session_state.auth_state["user"] = user
280
+ st.session_state.auth_state["signed_in"] = True
281
+ st.success("Authentication successful! You can now manage your set of images and profiles.")
282
+ main()
283
+ else:
284
+ st.error("Authentication failed. Please check your email and password.")
285
+
286
+ elif option == "Sign-Up":
287
+ confirm_password = st.text_input("Confirm Password", type="password", help="Re-enter your password for confirmation")
288
+ if st.button("Sign-Up"):
289
+ if not email or not password or not confirm_password:
290
+ st.error("Please fill all the fields.")
291
+ elif password != confirm_password:
292
+ st.error("Passwords do not match.")
293
+ else:
294
+ success, uid = create_user(email, password)
295
+ if success:
296
+ st.success(f"User with UID: {uid} created successfully! You can now log in.")
297
+ else:
298
+ st.error("User creation failed. Please try again.")
299
+
300
+ # Log out user
301
+ def logout():
302
+ st.session_state.auth_state["user"] = None
303
+ st.session_state.auth_state["signed_in"] = False
304
+
305
+ # Define tour steps
306
+ steps = [
307
+ {
308
+ "title": "Welcome to Insta's EYE",
309
+ "content": "This is a tour guide to help you navigate through the application.",
310
+ },
311
+ {
312
+ "title": "Options Sidebar",
313
+ "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.",
314
+ },
315
+ {
316
+ "title": "Main Interface",
317
+ "content": "This is where the main functionality of the application is displayed.",
318
+ },
319
+ {
320
+ "title": "Upload Image",
321
+ "content": "You can upload an image here for face recognition or adding a person.",
322
+ },
323
+ {
324
+ "title": "Text Input",
325
+ "content": "Enter text here such as the person's name or Instagram handle.",
326
+ },
327
+ {
328
+ "title": "Buttons",
329
+ "content": "Click on these buttons to perform actions like adding a person or recognizing a face.",
330
+ },
331
+ ]
332
+
333
+ # Function to display tour steps
334
+ def display_tour_steps(steps):
335
+ st.markdown("# Tour Guide")
336
+ st.markdown("This tour will guide you through the application.")
337
+ st.markdown("---")
338
+
339
+ for step in steps:
340
+ st.markdown(f"## {step['title']}")
341
+ st.write(step['content'])
342
+ st.markdown("---")
343
+
344
+ # Update the main function to include the new option
345
+ def main():
346
+ st.sidebar.title("Options")
347
+ option = st.sidebar.radio("Select Option", ["Add Person", "Recognize Face", "Delete Person", "Recognize Face (Optimal)","Tour Guide"])
348
+
349
+ if option == "Add Person":
350
+ add_person_ui()
351
+ elif option == "Recognize Face":
352
+ recognize_face_ui()
353
+ elif option == "Delete Person":
354
+ delete_person_ui()
355
+ elif option == "Recognize Face (Optimal)":
356
+ recognize_face_optimal_ui()
357
+ elif option == "Tour Guide":
358
+ tour_guide_ui()
359
+
360
+ # Run the tour guide
361
+ if __name__ == "__main__":
362
+ authenticate_user_ui()