Spaces:
Build error
Build error
Update app.py
Browse files3 unmodified lines4567891011 unmodified lines2223242526272829307 unmodified lines383940414243444546474849505152535455565758596061626364653 unmodified lines697071727374754 unmodified lines808182838485864 unmodified lines9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271283 unmodified linesimport jsonfrom google.oauth2 import service_accountfrom googleapiclient.discovery import buildfrom googleapiclient.http import MediaIoBaseDownload, MediaFileUpload# Load Google Drive API credentials from the uploaded JSON fileSERVICE_ACCOUNT_FILE = './.env' # Assuming the uploaded JSON file is named '.env'11 unmodified linescphotos_folder_id = '1DGeRqRbCPcfLDdEgP0h5fyX-MF8EQ8AH'suspects_folder_id = '1N3RMhVD0OygeufLPYod6IYLtqzvlm3Jv'# Increase the efficiency of ThreadPoolExecutor by balancing the number of threadsMAX_WORKERS = 10# Improved function to batch process images with better face comparison logicdef batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):start_time = time.time()7 unmodified linesprint("Extracting embeddings from Aadhar images...")with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:future_to_aadhar = {executor.submit(download_and_extract_embedding, file): file for file in aadhar_files}for future in as_completed(future_to_aadhar):try:result = future.result()if result:file_name, embedding = resultaadhar_embeddings.append((file_name, embedding))except Exception as e:file = future_to_aadhar[future]print(f"Error processing Aadhar file {file['name']}: {e}")# Verify that embeddings were successfully extracted for at least one Aadhar fileif not aadhar_embeddings:print("No valid Aadhar face embeddings found. Exiting.")return# Process CCTV files and compare with Aadhar embeddingsunmatched_files = []print("Processing CCTV images and comparing embeddings...")with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:future_to_cphoto = {executor.submit(download_and_extract_embedding, file): file for file in cphotos_files}for future in as_completed(future_to_cphoto):try:result = future.result()3 unmodified linesfile_name, embedding_cctv = result# Compare CCTV embedding with all Aadhaar embeddingsmatched = compare_faces_with_embeddings(embedding_cctv, aadhar_embeddings)if not matched:unmatched_files.append(file_name)print(f"Unmatched image queued for upload: {file_name}")4 unmodified lines# Upload unmatched files to suspect folderprint("Uploading unmatched images to the suspect folder...")with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:upload_futures = [executor.submit(upload_file, file_path, suspects_folder_id) for file_path in unmatched_files]for future in as_completed(upload_futures):try:future.result()4 unmodified linesend_time = time.time()print(f"Total processing time: {end_time - start_time:.2f} seconds.")def download_and_extract_embedding(file):"""Download the file and extract its face embedding.This function combines the download and extraction step to reduce overhead."""try:file_path = download_file(file['id'], file['name'])if file_path:embedding = extract_face_embedding(file_path)return file['name'], embeddingexcept Exception as e:print(f"Error processing file {file['name']}: {e}")return Nonedef compare_faces_with_embeddings(embedding_cctv, aadhar_embeddings, threshold=0.75):"""Compare the given CCTV embedding with a list of Aadhar embeddings.If the similarity score exceeds the threshold, it's a match."""for aadhar_name, aadhar_embedding in aadhar_embeddings:similarity = calculate_similarity(embedding_cctv, aadhar_embedding)if similarity > threshold:print(f"Match found: Similarity = {similarity:.2f} with Aadhar file: {aadhar_name}")return Truereturn Falsedef main():start_time = time.time()print("Script started...")batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id)end_time = time.time()print(f"Script completed in {end_time - start_time:.2f} seconds.")if __name__ == "__main__":main()3 unmodified lines45678910111211 unmodified lines24252627282930313233343536373839404142434445467 unmodified lines545556575859606162636465666768697071727374757677787980818283843 unmodified lines888990919293944 unmodified lines991001011021031041054 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641653 unmodified linesimport jsonfrom google.oauth2 import service_accountfrom googleapiclient.discovery import buildfrom googleapiclient.http import MediaIoBaseDownloadimport ioimport numpy as np# Load Google Drive API credentials from the uploaded JSON fileSERVICE_ACCOUNT_FILE = './.env' # Assuming the uploaded JSON file is named '.env'11 unmodified linescphotos_folder_id = '1DGeRqRbCPcfLDdEgP0h5fyX-MF8EQ8AH'suspects_folder_id = '1N3RMhVD0OygeufLPYod6IYLtqzvlm3Jv'MAX_WORKERS = 10def list_files_in_folder(folder_id):print(f"Listing files in folder ID: {folder_id}")query = f"'{folder_id}' in parents and trashed=false"try:results = drive_service.files().list(q=query, pageSize=1000, fields="files(id, name, mimeType)").execute()files = results.get('files', [])if not files:print(f"No files found in folder ID: {folder_id}. Ensure that the folder has files and the service account has access.")else:print(f"Found {len(files)} files in folder ID: {folder_id}.")return filesexcept Exception as e:print(f"Error listing files in folder ID: {folder_id} - {e}")return []# Improved function to batch process images with better face comparison logicdef batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id):start_time = time.time()7 unmodified linesprint("Extracting embeddings from Aadhar images...")with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:future_to_aadhar = {executor.submit(download_and_extract_embedding_from_memory, file): file for file in aadhar_files}for future in as_completed(future_to_aadhar):try:result = future.result()if result:file_name, embedding = resultaadhar_embeddings.append(embedding)except Exception as e:file = future_to_aadhar[future]print(f"Error processing Aadhar file {file['name']}: {e}")# Verify that embeddings were successfully extracted for at least one Aadhar fileif len(aadhar_embeddings) == 0:print("No valid Aadhar face embeddings found. Exiting.")return# Stack all embeddings for efficient vectorized comparisonaadhar_embeddings = np.vstack(aadhar_embeddings)# Process CCTV files and compare with Aadhar embeddingsunmatched_files = []print("Processing CCTV images and comparing embeddings...")with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:future_to_cphoto = {executor.submit(download_and_extract_embedding_from_memory, file): file for file in cphotos_files}for future in as_completed(future_to_cphoto):try:result = future.result()3 unmodified linesfile_name, embedding_cctv = result# Compare CCTV embedding with all Aadhaar embeddingsmatched = vectorized_compare_faces_with_embeddings(embedding_cctv, aadhar_embeddings)if not matched:unmatched_files.append(file_name)print(f"Unmatched image queued for upload: {file_name}")4 unmodified lines# Upload unmatched files to suspect folderprint("Uploading unmatched images to the suspect folder...")with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:upload_futures = [executor.submit(upload_file, file_name, suspects_folder_id) for file_name in unmatched_files]for future in as_completed(upload_futures):try:future.result()4 unmodified linesend_time = time.time()print(f"Total processing time: {end_time - start_time:.2f} seconds.")def download_and_extract_embedding_from_memory(file):"""Download the file in memory and extract its face embedding."""file_stream = download_file_in_memory(file['id'])if file_stream:embedding = extract_face_embedding_from_stream(file_stream)if embedding is not None:return file['name'], embeddingreturn Nonedef download_file_in_memory(file_id):try:request = drive_service.files().get_media(fileId=file_id)file_io = io.BytesIO()downloader = MediaIoBaseDownload(file_io, request)done = Falsewhile not done:_, done = downloader.next_chunk()file_io.seek(0)return file_ioexcept Exception as e:print(f"Error downloading file ID: {file_id} - {e}")return Nonedef extract_face_embedding_from_stream(file_stream):try:image = Image.open(file_stream)face = mtcnn(image) # Detect and crop the faceif face is not None:embedding = resnet(face.unsqueeze(0)) # Get the face embeddingreturn embedding.detach().numpy()except Exception as e:print(f"Error extracting face embedding from stream: {e}")return Nonedef vectorized_compare_faces_with_embeddings(embedding_cctv, aadhar_embeddings, threshold=0.75):"""Compare the given CCTV embedding with a list of Aadhar embeddings in a vectorized manner."""similarities = np.dot(aadhar_embeddings, embedding_cctv.T) / (np.linalg.norm(aadhar_embeddings, axis=1) * np.linalg.norm(embedding_cctv))max_similarity = np.max(similarities)if max_similarity > threshold:print(f"Match found: Similarity = {max_similarity:.2f}")return Truereturn Falsedef main():print("Script started...")batch_process_images(aadhar_folder_id, cphotos_folder_id, suspects_folder_id)if __name__ == "__main__":main()
app.py+64-27