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80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# 2:
import cv2
import numpy as np
import insightface
from insightface.app import FaceAnalysis
from insightface.utils import download_onnx
from pathlib import Path
from typing import Dict, List, Tuple
import pickle
import logging
import os

class FaceRecognitionSystem:
    def __init__(self, model_name: str = "buffalo_l", model_root: str = "./models"):
        # Set up logging
        logging.basicConfig(level=logging.INFO)
        self.logger = logging.getLogger(__name__)
        
        # Create model directory if it doesn't exist
        self.model_root = Path(model_root)
        self.model_root.mkdir(parents=True, exist_ok=True)
        
        # Set InsightFace model root
        # insightface.utils.set_download_root(str(self.model_root))
        # insightface.utils.download(root='./models_x', sub_dir='downloads', name='file')
        
        # Initialize the face analysis model
        try:
            self.face_analyzer = FaceAnalysis(
                name=model_name,
                root=str(self.model_root),
                download=True  # Allow downloading if model doesn't exist
            )
            self.face_analyzer.prepare(ctx_id=-1, det_size=(640, 640))  # Using CPU
            self.logger.info(f"Face analyzer initialized successfully in {self.model_root}")
        except Exception as e:
            self.logger.error(f"Error initializing face analyzer: {e}")
            raise
        
        # Dictionary to store known face embeddings
        self.known_face_embeddings: Dict[str, np.ndarray] = {}
        
    def process_known_faces(self, people_folder_path: str) -> None:
        """Process and store embeddings of known faces from a folder."""
        embeddings_file = self.model_root / "known_faces_embeddings.pkl"
        
        try:
            # Load existing embeddings if available
            if embeddings_file.exists():
                with open(embeddings_file, 'rb') as f:
                    self.known_face_embeddings = pickle.load(f)
                self.logger.info("Loaded existing face embeddings")
                return
                
            self.logger.info("Processing known faces...")
            people_path = Path(people_folder_path)
            if not people_path.exists():
                self.logger.warning(f"Directory not found: {people_folder_path}")
                return
                
            for person_path in people_path.glob("*"):
                if person_path.is_dir():
                    person_name = person_path.name
                    embeddings_list = []
                    
                    for img_path in person_path.glob("*"):
                        if img_path.suffix.lower() in ['.jpg', '.jpeg', '.png']:
                            img = cv2.imread(str(img_path))
                            if img is None:
                                self.logger.warning(f"Could not read image: {img_path}")
                                continue
                                
                            faces = self.face_analyzer.get(img)
                            if faces:
                                embeddings_list.append(faces[0].embedding)
                            else:
                                self.logger.warning(f"No face detected in {img_path}")
                    
                    if embeddings_list:
                        self.known_face_embeddings[person_name] = np.mean(embeddings_list, axis=0)
                        self.logger.info(f"Processed {person_name}'s faces")
                    else:
                        self.logger.warning(f"No valid faces found for {person_name}")
            
            # Save embeddings in model directory
            with open(embeddings_file, 'wb') as f:
                pickle.dump(self.known_face_embeddings, f)
            self.logger.info(f"Face embeddings saved to {embeddings_file}")
            
        except Exception as e:
            self.logger.error(f"Error processing known faces: {e}")
            raise
    
    def identify_face(self, face_embedding: np.ndarray, threshold: float = 0.6) -> Tuple[str, float]:
        """Identify a face by comparing its embedding with known faces."""
        try:
            best_match = "Unknown"
            best_score = float('inf')
            
            for person_name, known_embedding in self.known_face_embeddings.items():
                similarity = np.dot(face_embedding, known_embedding) / (
                    np.linalg.norm(face_embedding) * np.linalg.norm(known_embedding)
                )
                distance = 1 - similarity
                
                if distance < best_score:
                    best_score = distance
                    best_match = person_name
            
            return (best_match, best_score) if best_score < threshold else ("Unknown", best_score)
            
        except Exception as e:
            self.logger.error(f"Error in face identification: {e}")
            return ("Error", 1.0)
    
    def detect_and_identify(self, image_input) -> np.ndarray:
        """Detect and identify faces in an input image."""
        try:
            # Handle both string paths and numpy arrays
            if isinstance(image_input, str):
                img = cv2.imread(image_input)
            else:
                img = image_input

            if img is None:
                raise ValueError("Could not read input image")
            
            faces = self.face_analyzer.get(img)
            
            for face in faces:
                bbox = face.bbox.astype(int)
                embedding = face.embedding
                name, score = self.identify_face(embedding)
                
                cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
                label = f"{name} ({1-score:.2f})"
                
                cv2.putText(img, label.upper(), (bbox[0], bbox[1]-10),
                        cv2.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 0), 2)
            
            return img
            
        except Exception as e:
            self.logger.error(f"Error in detection and identification: {e}")
            raise


# 1:
# import cv2
# import numpy as np
# import insightface
# from insightface.app import FaceAnalysis
# from pathlib import Path
# from typing import Dict, List, Tuple
# import pickle
# import logging

# class FaceRecognitionSystem:
#     def __init__(self, model_name: str = "buffalo_l"):
#         # Set up logging
#         logging.basicConfig(level=logging.INFO)
#         self.logger = logging.getLogger(__name__)
        
#         # Initialize the face analysis model
#         try:
#             self.face_analyzer = FaceAnalysis(name=model_name)
#             self.face_analyzer.prepare(ctx_id=-1, det_size=(640, 640))  # Using CPU
#             self.logger.info("Face analyzer initialized successfully")
#         except Exception as e:
#             self.logger.error(f"Error initializing face analyzer: {e}")
#             raise
        
#         # Dictionary to store known face embeddings
#         self.known_face_embeddings: Dict[str, np.ndarray] = {}
        
#     def process_known_faces(self, people_folder_path: str) -> None:
#         """Process and store embeddings of known faces from a folder."""
#         embeddings_file = Path("known_faces_embeddings.pkl")
        
#         try:
#             # Load existing embeddings if available
#             if embeddings_file.exists():
#                 with open(embeddings_file, 'rb') as f:
#                     self.known_face_embeddings = pickle.load(f)
#                 self.logger.info("Loaded existing face embeddings")
#                 return
                
#             self.logger.info("Processing known faces...")
#             people_path = Path(people_folder_path)
#             if not people_path.exists():
#                 self.logger.warning(f"Directory not found: {people_folder_path}")
#                 return
                
#             for person_path in people_path.glob("*"):
#                 if person_path.is_dir():
#                     person_name = person_path.name
#                     embeddings_list = []
                    
#                     for img_path in person_path.glob("*"):
#                         if img_path.suffix.lower() in ['.jpg', '.jpeg', '.png']:
#                             img = cv2.imread(str(img_path))
#                             if img is None:
#                                 self.logger.warning(f"Could not read image: {img_path}")
#                                 continue
                                
#                             faces = self.face_analyzer.get(img)
#                             if faces:
#                                 embeddings_list.append(faces[0].embedding)
#                             else:
#                                 self.logger.warning(f"No face detected in {img_path}")
                    
#                     if embeddings_list:
#                         self.known_face_embeddings[person_name] = np.mean(embeddings_list, axis=0)
#                         self.logger.info(f"Processed {person_name}'s faces")
#                     else:
#                         self.logger.warning(f"No valid faces found for {person_name}")
            
#             # Save embeddings
#             with open(embeddings_file, 'wb') as f:
#                 pickle.dump(self.known_face_embeddings, f)
#             self.logger.info("Face processing complete")
            
#         except Exception as e:
#             self.logger.error(f"Error processing known faces: {e}")
#             raise
    
#     def identify_face(self, face_embedding: np.ndarray, threshold: float = 0.6) -> Tuple[str, float]:
#         """Identify a face by comparing its embedding with known faces."""
#         try:
#             best_match = "Unknown"
#             best_score = float('inf')
            
#             for person_name, known_embedding in self.known_face_embeddings.items():
#                 similarity = np.dot(face_embedding, known_embedding) / (
#                     np.linalg.norm(face_embedding) * np.linalg.norm(known_embedding)
#                 )
#                 distance = 1 - similarity
                
#                 if distance < best_score:
#                     best_score = distance
#                     best_match = person_name
            
#             return (best_match, best_score) if best_score < threshold else ("Unknown", best_score)
            
#         except Exception as e:
#             self.logger.error(f"Error in face identification: {e}")
#             return ("Error", 1.0)
    
#     def detect_and_identify(self, image_input) -> np.ndarray:
#         """Detect and identify faces in an input image."""
#         try:
#             # Handle both string paths and numpy arrays
#             if isinstance(image_input, str):
#                 img = cv2.imread(image_input)
#             else:
#                 img = image_input

#             if img is None:
#                 raise ValueError("Could not read input image")
            
#             faces = self.face_analyzer.get(img)
            
#             for face in faces:
#                 bbox = face.bbox.astype(int)
#                 embedding = face.embedding
#                 name, score = self.identify_face(embedding)
                
#                 cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
#                 label = f"{name} ({1-score:.2f})"
                
#                 cv2.putText(img, label.upper(), (bbox[0], bbox[1]-10),
#                         cv2.FONT_HERSHEY_PLAIN, 2.0, (0, 255, 0), 2)
            
#             return img
            
#         except Exception as e:
#             self.logger.error(f"Error in detection and identification: {e}")
#             raise



# OLD:
# import cv2
# import numpy as np
# import insightface
# from insightface.app import FaceAnalysis
# from insightface.data import get_image as ins_get_image
# import os
# from pathlib import Path
# from typing import Dict, List, Tuple
# import pickle

# class FaceRecognitionSystem:
#     def __init__(self, model_name: str = "buffalo_l"):
#         # Initialize the face analysis model
#         self.face_analyzer = FaceAnalysis(name=model_name)
#         self.face_analyzer.prepare(ctx_id=0, det_size=(640, 640))
        
#         # Dictionary to store known face embeddings
#         self.known_face_embeddings: Dict[str, np.ndarray] = {}
        
#     def process_known_faces(self, people_folder_path: str) -> None:
#         """Process and store embeddings of known faces from a folder."""
#         # Create embeddings file path
#         # embeddings_file = Path("known_face_embeddings copy2.pkl")
#         embeddings_file = Path("data/model/known_faces_embeddings.pkl")
        
#         # Load existing embeddings if available
#         if embeddings_file.exists():
#             with open(embeddings_file, 'rb') as f:
#                 self.known_face_embeddings = pickle.load(f)
#             print("Loaded existing face embeddings.")
#             return
            
#         print("Processing known faces...")
#         for person_path in Path(people_folder_path).glob("*"):
#             if person_path.is_dir():
#                 person_name = person_path.name
#                 embeddings_list = []
                
#                 # Process each image in person's folder
#                 for img_path in person_path.glob("*"):
#                     if img_path.suffix.lower() in ['.jpg', '.jpeg', '.png']:
#                         img = cv2.imread(str(img_path))
#                         if img is None:
#                             continue
                            
#                         # Get face embedding
#                         faces = self.face_analyzer.get(img)
#                         if faces:
#                             embeddings_list.append(faces[0].embedding)
                
#                 if embeddings_list:
#                     # Average all embeddings for this person
#                     self.known_face_embeddings[person_name] = np.mean(embeddings_list, axis=0)
#                     print(f"Processed {person_name}'s faces")
        
#         # Save embeddings for future use
#         with open(embeddings_file, 'wb') as f:
#             pickle.dump(self.known_face_embeddings, f)
#         print("Face processing complete.")
    
#     # OLD:
#     def identify_face(self, face_embedding: np.ndarray, threshold: float = 0.6) -> Tuple[str, float]:
#         """Identify a face by comparing its embedding with known faces."""
#         best_match = "Unknown"
#         best_score = float('inf')
        
#         for person_name, known_embedding in self.known_face_embeddings.items():
#             # Calculate cosine similarity
#             similarity = np.dot(face_embedding, known_embedding) / (
#                 np.linalg.norm(face_embedding) * np.linalg.norm(known_embedding)
#             )
#             distance = 1 - similarity
            
#             if distance < best_score:
#                 best_score = distance
#                 best_match = person_name
        
#         return (best_match, best_score) if best_score < threshold else ("Unknown", best_score)
    
  
    
#     def detect_and_identify(self, image_input, output_path: str = None) -> np.ndarray:
#         """Detect and identify faces in an input image."""
#         # Handle both string paths and numpy arrays
#         if isinstance(image_input, str):
#             img = cv2.imread(image_input)
#         else:
#             img = image_input

#         if img is None:
#             raise ValueError("Could not read input image")
        
#         # Rest of the code remains the same
#         faces = self.face_analyzer.get(img)
        
#         for face in faces:
#             bbox = face.bbox.astype(int)
#             embedding = face.embedding
#             name, score = self.identify_face(embedding)
            
#             cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
#             label = f"{name} ({1-score:.2f})"
            
#             cv2.putText(img, label.upper(), (bbox[0], bbox[1]-10),
#                     cv2.FONT_HERSHEY_PLAIN, 4.2, (0, 255, 0), 2)
#                     # cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
        
#         if output_path:
#             cv2.imwrite(output_path, img)
        
#         return img
    
    
#     # def detect_and_identify(self, image_path: str, output_path: str = None) -> np.ndarray:
#         #     """Detect and identify faces in an input image."""
#         #     # Read input image
#         #     img = cv2.imread(image_path)
#         #     if img is None:
#         #         raise ValueError("Could not read input image")
            
#         #     # Detect faces
#         #     faces = self.face_analyzer.get(img)
            
#         #     # Draw results on image
#         #     for face in faces:
#         #         bbox = face.bbox.astype(int)
#         #         embedding = face.embedding
#         #         name, score = self.identify_face(embedding)
                
#         #         # Draw rectangle around face
#         #         cv2.rectangle(img, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 2)
                
#         #         # Add name and confidence score
#         #         label = f"{name} ({1-score:.2f})"
#         #         cv2.putText(img, label, (bbox[0], bbox[1]-10),
#         #                    cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)
            
#             # # Save output image if path provided
#             # if output_path:
#             #     cv2.imwrite(output_path, img)
            
#             # return img